GRPCMessageFramer.swift 4.2 KB

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