GRPCMessageFramer.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. * Copyright 2024, 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. internal import GRPCCore
  17. internal import NIOCore
  18. /// A ``GRPCMessageFramer`` helps with the framing of gRPC data frames:
  19. /// - It prepends data with the required metadata (compression flag and message length).
  20. /// - It compresses messages using the specified compression algorithm (if configured).
  21. /// - It coalesces multiple messages (appended into the `Framer` by calling ``append(_:compress:)``)
  22. /// into a single `ByteBuffer`.
  23. @available(gRPCSwiftNIOTransport 1.0, *)
  24. struct GRPCMessageFramer {
  25. /// Length of the gRPC message header (1 compression byte, 4 bytes for the length).
  26. static let metadataLength = 5
  27. /// Maximum size the `writeBuffer` can be when concatenating multiple frames.
  28. /// This limit will not be considered if only a single message/frame is written into the buffer, meaning
  29. /// frames with messages over 64KB can still be written.
  30. /// - Note: This is expressed as the power of 2 closer to 64KB (i.e., 64KiB) because `ByteBuffer`
  31. /// reserves capacity in powers of 2. This way, we can take advantage of the whole buffer.
  32. static let maxWriteBufferLength = 65_536
  33. private var pendingMessages: OneOrManyQueue<(bytes: ByteBuffer, promise: EventLoopPromise<Void>?)>
  34. private var writeBuffer: ByteBuffer
  35. /// Create a new ``GRPCMessageFramer``.
  36. init() {
  37. self.pendingMessages = OneOrManyQueue()
  38. self.writeBuffer = ByteBuffer()
  39. }
  40. /// Queue the given bytes to be framed and potentially coalesced alongside other messages in a `ByteBuffer`.
  41. /// The resulting data will be returned when calling ``GRPCMessageFramer/next()``.
  42. mutating func append(_ bytes: ByteBuffer, promise: EventLoopPromise<Void>?) {
  43. self.pendingMessages.append((bytes, promise))
  44. }
  45. /// If there are pending messages to be framed, a `ByteBuffer` will be returned with the framed data.
  46. /// Data may also be compressed (if configured) and multiple frames may be coalesced into the same `ByteBuffer`.
  47. /// - Parameter compressor: An optional compressor: if present, payloads will be compressed; otherwise
  48. /// they'll be framed as-is.
  49. /// - Throws: If an error is encountered, such as a compression failure, an error will be thrown.
  50. mutating func nextResult(
  51. compressor: Zlib.Compressor? = nil
  52. ) -> (result: Result<ByteBuffer, RPCError>, promise: EventLoopPromise<Void>?)? {
  53. if self.pendingMessages.isEmpty {
  54. // Nothing pending: exit early.
  55. return nil
  56. }
  57. defer {
  58. // To avoid holding an excessively large buffer, if its size is larger than
  59. // our threshold (`maxWriteBufferLength`), then reset it to a new `ByteBuffer`.
  60. if self.writeBuffer.capacity > Self.maxWriteBufferLength {
  61. self.writeBuffer = ByteBuffer()
  62. }
  63. }
  64. var requiredCapacity = 0
  65. for message in self.pendingMessages {
  66. requiredCapacity += message.bytes.readableBytes + Self.metadataLength
  67. }
  68. self.writeBuffer.clear(minimumCapacity: requiredCapacity)
  69. var pendingWritePromise: EventLoopPromise<Void>?
  70. while let message = self.pendingMessages.pop() {
  71. pendingWritePromise.setOrCascade(to: message.promise)
  72. do {
  73. try self.encode(message.bytes, compressor: compressor)
  74. } catch let rpcError {
  75. return (result: .failure(rpcError), promise: pendingWritePromise)
  76. }
  77. }
  78. return (result: .success(self.writeBuffer), promise: pendingWritePromise)
  79. }
  80. private mutating func encode(
  81. _ message: ByteBuffer,
  82. compressor: Zlib.Compressor?
  83. ) throws(RPCError) {
  84. if let compressor {
  85. self.writeBuffer.writeInteger(UInt8(1)) // Set compression flag
  86. // Write zeroes as length - we'll write the actual compressed size after compression.
  87. let lengthIndex = self.writeBuffer.writerIndex
  88. self.writeBuffer.writeInteger(UInt32(0))
  89. // Compress and overwrite the payload length field with the right length.
  90. do {
  91. let writtenBytes = try compressor.compress(message, into: &self.writeBuffer)
  92. self.writeBuffer.setInteger(UInt32(writtenBytes), at: lengthIndex)
  93. } catch let zlibError {
  94. throw RPCError(code: .internalError, message: "Compression failed", cause: zlibError)
  95. }
  96. } else {
  97. self.writeBuffer.writeMultipleIntegers(
  98. UInt8(0), // Clear compression flag
  99. UInt32(message.readableBytes) // Set message length
  100. )
  101. self.writeBuffer.writeImmutableBuffer(message)
  102. }
  103. }
  104. }