LengthPrefixedMessageWriter.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import NIOCore
  18. internal struct LengthPrefixedMessageWriter {
  19. static let metadataLength = 5
  20. /// The compression algorithm to use, if one should be used.
  21. let compression: CompressionAlgorithm?
  22. private let compressor: Zlib.Deflate?
  23. /// Whether the compression message flag should be set.
  24. private var shouldSetCompressionFlag: Bool {
  25. return self.compression != nil
  26. }
  27. init(compression: CompressionAlgorithm? = nil) {
  28. self.compression = compression
  29. switch self.compression?.algorithm {
  30. case .none, .some(.identity):
  31. self.compressor = nil
  32. case .some(.deflate):
  33. self.compressor = Zlib.Deflate(format: .deflate)
  34. case .some(.gzip):
  35. self.compressor = Zlib.Deflate(format: .gzip)
  36. }
  37. }
  38. private func compress(
  39. buffer: ByteBuffer,
  40. using compressor: Zlib.Deflate,
  41. allocator: ByteBufferAllocator
  42. ) throws -> ByteBuffer {
  43. // The compressor will allocate the correct size. For now the leading 5 bytes will do.
  44. var output = allocator.buffer(capacity: 5)
  45. // Set the compression byte.
  46. output.writeInteger(UInt8(1))
  47. // Set the length to zero; we'll write the actual value in a moment.
  48. let payloadSizeIndex = output.writerIndex
  49. output.writeInteger(UInt32(0))
  50. let bytesWritten: Int
  51. do {
  52. var buffer = buffer
  53. bytesWritten = try compressor.deflate(&buffer, into: &output)
  54. } catch {
  55. throw error
  56. }
  57. // Now fill in the message length.
  58. output.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  59. // Finally, the compression context should be reset between messages.
  60. compressor.reset()
  61. return output
  62. }
  63. /// Writes the readable bytes of `buffer` as a gRPC length-prefixed message.
  64. ///
  65. /// - Parameters:
  66. /// - buffer: The bytes to compress and length-prefix.
  67. /// - allocator: A `ByteBufferAllocator`.
  68. /// - compressed: Whether the bytes should be compressed. This is ignored if not compression
  69. /// mechanism was configured on this writer.
  70. /// - Returns: A buffer containing the length prefixed bytes.
  71. func write(
  72. buffer: ByteBuffer,
  73. allocator: ByteBufferAllocator,
  74. compressed: Bool = true
  75. ) throws -> ByteBuffer {
  76. if compressed, let compressor = self.compressor {
  77. return try self.compress(buffer: buffer, using: compressor, allocator: allocator)
  78. } else if buffer.readerIndex >= 5 {
  79. // We're not compressing and we have enough bytes before the reader index that we can write
  80. // over with the compression byte and length.
  81. var buffer = buffer
  82. // Get the size of the message.
  83. let messageSize = buffer.readableBytes
  84. // Move the reader index back 5 bytes. This is okay: we validated the `readerIndex` above.
  85. buffer.moveReaderIndex(to: buffer.readerIndex - 5)
  86. // Fill in the compression byte and message length.
  87. buffer.setInteger(UInt8(0), at: buffer.readerIndex)
  88. buffer.setInteger(UInt32(messageSize), at: buffer.readerIndex + 1)
  89. // The message bytes are already in place, we're done.
  90. return buffer
  91. } else {
  92. // We're not compressing and we don't have enough space before the message bytes passed in.
  93. // We need a new buffer.
  94. var lengthPrefixed = allocator.buffer(capacity: 5 + buffer.readableBytes)
  95. // Write the compression byte.
  96. lengthPrefixed.writeInteger(UInt8(0))
  97. // Write the message length.
  98. lengthPrefixed.writeInteger(UInt32(buffer.readableBytes))
  99. // Write the message.
  100. var buffer = buffer
  101. lengthPrefixed.writeBuffer(&buffer)
  102. return lengthPrefixed
  103. }
  104. }
  105. /// Writes the data into a `ByteBuffer` as a gRPC length-prefixed message.
  106. ///
  107. /// - Parameters:
  108. /// - payload: The payload to serialize and write.
  109. /// - buffer: The buffer to write the message into.
  110. /// - Returns: A `ByteBuffer` containing a gRPC length-prefixed message.
  111. /// - Precondition: `compression.supported` is `true`.
  112. /// - Note: See `LengthPrefixedMessageReader` for more details on the format.
  113. func write(
  114. _ payload: GRPCPayload,
  115. into buffer: inout ByteBuffer,
  116. compressed: Bool = true
  117. ) throws {
  118. buffer.reserveCapacity(buffer.writerIndex + LengthPrefixedMessageWriter.metadataLength)
  119. if compressed, let compressor = self.compressor {
  120. // Set the compression byte.
  121. buffer.writeInteger(UInt8(1))
  122. // Leave a gap for the length, we'll set it in a moment.
  123. let payloadSizeIndex = buffer.writerIndex
  124. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  125. var messageBuf = ByteBufferAllocator().buffer(capacity: 0)
  126. try payload.serialize(into: &messageBuf)
  127. // Compress the message.
  128. let bytesWritten = try compressor.deflate(&messageBuf, into: &buffer)
  129. // Now fill in the message length.
  130. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  131. // Finally, the compression context should be reset between messages.
  132. compressor.reset()
  133. } else {
  134. // We could be using 'identity' compression, but since the result is the same we'll just
  135. // say it isn't compressed.
  136. buffer.writeInteger(UInt8(0))
  137. // Leave a gap for the length, we'll set it in a moment.
  138. let payloadSizeIndex = buffer.writerIndex
  139. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  140. let payloadPrefixedBytes = buffer.readableBytes
  141. // Writes the payload into the buffer
  142. try payload.serialize(into: &buffer)
  143. // Calculates the Written bytes with respect to the prefixed ones
  144. let bytesWritten = buffer.readableBytes - payloadPrefixedBytes
  145. // Write the message length.
  146. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  147. }
  148. }
  149. }
  150. extension ByteBuffer {
  151. @discardableResult
  152. mutating func writePayloadLength(_ length: UInt32, at index: Int) -> Int {
  153. let writerIndex = self.writerIndex
  154. defer {
  155. self.moveWriterIndex(to: writerIndex)
  156. }
  157. self.moveWriterIndex(to: index)
  158. return self.writeInteger(length)
  159. }
  160. }