CoalescingLengthPrefixedMessageWriter.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * Copyright 2022, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import DequeModule
  17. import NIOCore
  18. internal struct CoalescingLengthPrefixedMessageWriter {
  19. /// Length of the gRPC message header (1 compression byte, 4 bytes for the length).
  20. static let metadataLength = 5
  21. /// Message size above which we emit two buffers: one containing the header and one with the
  22. /// actual message bytes. At or below the limit we copy the message into a new buffer containing
  23. /// both the header and the message.
  24. ///
  25. /// Using two buffers avoids expensive copies of large messages. For smaller messages the copy
  26. /// is cheaper than the additional allocations and overhead required to send an extra HTTP/2 DATA
  27. /// frame.
  28. ///
  29. /// The value of 16k was chosen empirically. We subtract the length of the message header
  30. /// as `ByteBuffer` reserve capacity in powers of two and want to avoid overallocating.
  31. static let singleBufferSizeLimit = 16384 - Self.metadataLength
  32. /// The compression algorithm to use, if one should be used.
  33. private let compression: CompressionAlgorithm?
  34. /// Any compressor associated with the compression algorithm.
  35. private let compressor: Zlib.Deflate?
  36. /// Whether the compression message flag should be set.
  37. private var supportsCompression: Bool {
  38. return self.compression != nil
  39. }
  40. /// A scratch buffer that we encode messages into: if the buffer isn't held elsewhere then we
  41. /// can avoid having to allocate a new one.
  42. private var scratch: ByteBuffer
  43. /// Outbound buffers waiting to be written.
  44. private var pending: OneOrManyQueue<Pending>
  45. private struct Pending {
  46. var buffer: ByteBuffer
  47. var promise: EventLoopPromise<Void>?
  48. var compress: Bool
  49. init(buffer: ByteBuffer, compress: Bool, promise: EventLoopPromise<Void>?) {
  50. self.buffer = buffer
  51. self.promise = promise
  52. self.compress = compress
  53. }
  54. var isSmallEnoughToCoalesce: Bool {
  55. let limit = CoalescingLengthPrefixedMessageWriter.singleBufferSizeLimit
  56. return self.buffer.readableBytes <= limit
  57. }
  58. var shouldCoalesce: Bool {
  59. return self.isSmallEnoughToCoalesce || self.compress
  60. }
  61. }
  62. private enum State {
  63. // Coalescing pending messages.
  64. case coalescing
  65. // Emitting a non-coalesced message; the header has been written, the body
  66. // needs to be written next.
  67. case emittingLargeFrame(ByteBuffer, EventLoopPromise<Void>?)
  68. }
  69. private var state: State
  70. init(compression: CompressionAlgorithm? = nil, allocator: ByteBufferAllocator) {
  71. self.compression = compression
  72. self.scratch = allocator.buffer(capacity: 0)
  73. self.state = .coalescing
  74. self.pending = .init()
  75. switch self.compression?.algorithm {
  76. case .none, .some(.identity):
  77. self.compressor = nil
  78. case .some(.deflate):
  79. self.compressor = Zlib.Deflate(format: .deflate)
  80. case .some(.gzip):
  81. self.compressor = Zlib.Deflate(format: .gzip)
  82. }
  83. }
  84. /// Append a serialized message buffer to the writer.
  85. mutating func append(buffer: ByteBuffer, compress: Bool, promise: EventLoopPromise<Void>?) {
  86. let pending = Pending(
  87. buffer: buffer,
  88. compress: compress && self.supportsCompression,
  89. promise: promise
  90. )
  91. self.pending.append(pending)
  92. }
  93. /// Return a tuple of the next buffer to write and its associated write promise.
  94. mutating func next() -> (Result<ByteBuffer, Error>, EventLoopPromise<Void>?)? {
  95. switch self.state {
  96. case .coalescing:
  97. // Nothing pending: exit early.
  98. if self.pending.isEmpty {
  99. return nil
  100. }
  101. // First up we need to work out how many elements we're going to pop off the front
  102. // and coalesce.
  103. //
  104. // At the same time we'll compute how much capacity we'll need in the buffer and cascade
  105. // their promises.
  106. var messagesToCoalesce = 0
  107. var requiredCapacity = 0
  108. var promise: EventLoopPromise<Void>?
  109. for element in self.pending {
  110. if !element.shouldCoalesce {
  111. break
  112. }
  113. messagesToCoalesce &+= 1
  114. requiredCapacity += element.buffer.readableBytes + Self.metadataLength
  115. if let existing = promise {
  116. existing.futureResult.cascade(to: element.promise)
  117. } else {
  118. promise = element.promise
  119. }
  120. }
  121. if messagesToCoalesce == 0 {
  122. // Nothing to coalesce; this means the first element should be emitted with its header in
  123. // a separate buffer. Note: the force unwrap is okay here: we early exit if `self.pending`
  124. // is empty.
  125. let pending = self.pending.pop()!
  126. // Set the scratch buffer to just be a message header then store the message bytes.
  127. self.scratch.clear(minimumCapacity: Self.metadataLength)
  128. self.scratch.writeMultipleIntegers(UInt8(0), UInt32(pending.buffer.readableBytes))
  129. self.state = .emittingLargeFrame(pending.buffer, pending.promise)
  130. return (.success(self.scratch), nil)
  131. } else {
  132. self.scratch.clear(minimumCapacity: requiredCapacity)
  133. // Drop and encode the messages.
  134. while messagesToCoalesce > 0, let next = self.pending.pop() {
  135. messagesToCoalesce &-= 1
  136. do {
  137. try self.encode(next.buffer, compress: next.compress)
  138. } catch {
  139. return (.failure(error), promise)
  140. }
  141. }
  142. return (.success(self.scratch), promise)
  143. }
  144. case let .emittingLargeFrame(buffer, promise):
  145. // We just emitted the header, now emit the body.
  146. self.state = .coalescing
  147. return (.success(buffer), promise)
  148. }
  149. }
  150. private mutating func encode(_ buffer: ByteBuffer, compress: Bool) throws {
  151. if let compressor = self.compressor, compress {
  152. try self.encode(buffer, compressor: compressor)
  153. } else {
  154. try self.encode(buffer)
  155. }
  156. }
  157. private mutating func encode(_ buffer: ByteBuffer, compressor: Zlib.Deflate) throws {
  158. // Set the compression byte.
  159. self.scratch.writeInteger(UInt8(1))
  160. // Set the length to zero; we'll write the actual value in a moment.
  161. let payloadSizeIndex = self.scratch.writerIndex
  162. self.scratch.writeInteger(UInt32(0))
  163. let bytesWritten: Int
  164. do {
  165. var buffer = buffer
  166. bytesWritten = try compressor.deflate(&buffer, into: &self.scratch)
  167. } catch {
  168. throw error
  169. }
  170. self.scratch.setInteger(UInt32(bytesWritten), at: payloadSizeIndex)
  171. // Finally, the compression context should be reset between messages.
  172. compressor.reset()
  173. }
  174. private mutating func encode(_ buffer: ByteBuffer) throws {
  175. self.scratch.writeMultipleIntegers(UInt8(0), UInt32(buffer.readableBytes))
  176. self.scratch.writeImmutableBuffer(buffer)
  177. }
  178. }
  179. /// A FIFO-queue which allows for a single to be stored on the stack and defers to a
  180. /// heap-implementation if further elements are added.
  181. ///
  182. /// This is useful when optimising for unary streams where avoiding the cost of a heap
  183. /// allocation is desirable.
  184. internal struct OneOrManyQueue<Element>: Collection {
  185. private var backing: Backing
  186. private enum Backing: Collection {
  187. case none
  188. case one(Element)
  189. case many(Deque<Element>)
  190. var startIndex: Int {
  191. switch self {
  192. case .none, .one:
  193. return 0
  194. case let .many(elements):
  195. return elements.startIndex
  196. }
  197. }
  198. var endIndex: Int {
  199. switch self {
  200. case .none:
  201. return 0
  202. case .one:
  203. return 1
  204. case let .many(elements):
  205. return elements.endIndex
  206. }
  207. }
  208. subscript(index: Int) -> Element {
  209. switch self {
  210. case .none:
  211. fatalError("Invalid index")
  212. case let .one(element):
  213. assert(index == 0)
  214. return element
  215. case let .many(elements):
  216. return elements[index]
  217. }
  218. }
  219. func index(after index: Int) -> Int {
  220. switch self {
  221. case .none:
  222. return 0
  223. case .one:
  224. return 1
  225. case let .many(elements):
  226. return elements.index(after: index)
  227. }
  228. }
  229. var count: Int {
  230. switch self {
  231. case .none:
  232. return 0
  233. case .one:
  234. return 1
  235. case let .many(elements):
  236. return elements.count
  237. }
  238. }
  239. var isEmpty: Bool {
  240. switch self {
  241. case .none:
  242. return true
  243. case .one:
  244. return false
  245. case let .many(elements):
  246. return elements.isEmpty
  247. }
  248. }
  249. mutating func append(_ element: Element) {
  250. switch self {
  251. case .none:
  252. self = .one(element)
  253. case let .one(one):
  254. var elements = Deque<Element>()
  255. elements.reserveCapacity(16)
  256. elements.append(one)
  257. elements.append(element)
  258. self = .many(elements)
  259. case var .many(elements):
  260. self = .none
  261. elements.append(element)
  262. self = .many(elements)
  263. }
  264. }
  265. mutating func pop() -> Element? {
  266. switch self {
  267. case .none:
  268. return nil
  269. case let .one(element):
  270. self = .none
  271. return element
  272. case var .many(many):
  273. self = .none
  274. let element = many.popFirst()
  275. self = .many(many)
  276. return element
  277. }
  278. }
  279. }
  280. init() {
  281. self.backing = .none
  282. }
  283. var isEmpty: Bool {
  284. return self.backing.isEmpty
  285. }
  286. var count: Int {
  287. return self.backing.count
  288. }
  289. var startIndex: Int {
  290. return self.backing.startIndex
  291. }
  292. var endIndex: Int {
  293. return self.backing.endIndex
  294. }
  295. subscript(index: Int) -> Element {
  296. return self.backing[index]
  297. }
  298. func index(after index: Int) -> Int {
  299. return self.backing.index(after: index)
  300. }
  301. mutating func append(_ element: Element) {
  302. self.backing.append(element)
  303. }
  304. mutating func pop() -> Element? {
  305. return self.backing.pop()
  306. }
  307. }