LengthPrefixedMessageWriter.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 NIO
  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(buffer: ByteBuffer, allocator: ByteBufferAllocator,
  72. compressed: Bool = true) throws -> ByteBuffer {
  73. if compressed, let compressor = self.compressor {
  74. return try self.compress(buffer: buffer, using: compressor, allocator: allocator)
  75. } else if buffer.readerIndex >= 5 {
  76. // We're not compressing and we have enough bytes before the reader index that we can write
  77. // over with the compression byte and length.
  78. var buffer = buffer
  79. // Get the size of the message.
  80. let messageSize = buffer.readableBytes
  81. // Move the reader index back 5 bytes. This is okay: we validated the `readerIndex` above.
  82. buffer.moveReaderIndex(to: buffer.readerIndex - 5)
  83. // Fill in the compression byte and message length.
  84. buffer.setInteger(UInt8(0), at: buffer.readerIndex)
  85. buffer.setInteger(UInt32(messageSize), at: buffer.readerIndex + 1)
  86. // The message bytes are already in place, we're done.
  87. return buffer
  88. } else {
  89. // We're not compressing and we don't have enough space before the message bytes passed in.
  90. // We need a new buffer.
  91. var lengthPrefixed = allocator.buffer(capacity: 5 + buffer.readableBytes)
  92. // Write the compression byte.
  93. lengthPrefixed.writeInteger(UInt8(0))
  94. // Write the message length.
  95. lengthPrefixed.writeInteger(UInt32(buffer.readableBytes))
  96. // Write the message.
  97. var buffer = buffer
  98. lengthPrefixed.writeBuffer(&buffer)
  99. return lengthPrefixed
  100. }
  101. }
  102. /// Writes the data into a `ByteBuffer` as a gRPC length-prefixed message.
  103. ///
  104. /// - Parameters:
  105. /// - payload: The payload to serialize and write.
  106. /// - buffer: The buffer to write the message into.
  107. /// - Returns: A `ByteBuffer` containing a gRPC length-prefixed message.
  108. /// - Precondition: `compression.supported` is `true`.
  109. /// - Note: See `LengthPrefixedMessageReader` for more details on the format.
  110. func write(_ payload: GRPCPayload, into buffer: inout ByteBuffer,
  111. compressed: Bool = true) throws {
  112. buffer.reserveCapacity(buffer.writerIndex + LengthPrefixedMessageWriter.metadataLength)
  113. if compressed, let compressor = self.compressor {
  114. // Set the compression byte.
  115. buffer.writeInteger(UInt8(1))
  116. // Leave a gap for the length, we'll set it in a moment.
  117. let payloadSizeIndex = buffer.writerIndex
  118. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  119. var messageBuf = ByteBufferAllocator().buffer(capacity: 0)
  120. try payload.serialize(into: &messageBuf)
  121. // Compress the message.
  122. let bytesWritten = try compressor.deflate(&messageBuf, into: &buffer)
  123. // Now fill in the message length.
  124. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  125. // Finally, the compression context should be reset between messages.
  126. compressor.reset()
  127. } else {
  128. // We could be using 'identity' compression, but since the result is the same we'll just
  129. // say it isn't compressed.
  130. buffer.writeInteger(UInt8(0))
  131. // Leave a gap for the length, we'll set it in a moment.
  132. let payloadSizeIndex = buffer.writerIndex
  133. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  134. let payloadPrefixedBytes = buffer.readableBytes
  135. // Writes the payload into the buffer
  136. try payload.serialize(into: &buffer)
  137. // Calculates the Written bytes with respect to the prefixed ones
  138. let bytesWritten = buffer.readableBytes - payloadPrefixedBytes
  139. // Write the message length.
  140. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  141. }
  142. }
  143. }
  144. extension ByteBuffer {
  145. @discardableResult
  146. mutating func writePayloadLength(_ length: UInt32, at index: Int) -> Int {
  147. let writerIndex = self.writerIndex
  148. defer {
  149. self.moveWriterIndex(to: writerIndex)
  150. }
  151. self.moveWriterIndex(to: index)
  152. return self.writeInteger(length)
  153. }
  154. }