LengthPrefixedMessageWriter.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. import NIOHPACK
  19. internal struct LengthPrefixedMessageWriter {
  20. static let metadataLength = 5
  21. /// The compression algorithm to use, if one should be used.
  22. let compression: CompressionAlgorithm?
  23. private let compressor: Zlib.Deflate?
  24. /// Whether the compression message flag should be set.
  25. private var shouldSetCompressionFlag: Bool {
  26. return self.compression != nil
  27. }
  28. /// A scratch buffer that we encode messages into: if the buffer isn't held elsewhere then we
  29. /// can avoid having to allocate a new one.
  30. private var scratch: ByteBuffer
  31. init(compression: CompressionAlgorithm? = nil, allocator: ByteBufferAllocator) {
  32. self.compression = compression
  33. self.scratch = allocator.buffer(capacity: 0)
  34. switch self.compression?.algorithm {
  35. case .none, .some(.identity):
  36. self.compressor = nil
  37. case .some(.deflate):
  38. self.compressor = Zlib.Deflate(format: .deflate)
  39. case .some(.gzip):
  40. self.compressor = Zlib.Deflate(format: .gzip)
  41. }
  42. }
  43. private mutating func compress(
  44. buffer: ByteBuffer,
  45. using compressor: Zlib.Deflate
  46. ) throws -> ByteBuffer {
  47. // The compressor will allocate the correct size. For now the leading 5 bytes will do.
  48. self.scratch.clear(minimumCapacity: 5)
  49. // Set the compression byte.
  50. self.scratch.writeInteger(UInt8(1))
  51. // Set the length to zero; we'll write the actual value in a moment.
  52. let payloadSizeIndex = self.scratch.writerIndex
  53. self.scratch.writeInteger(UInt32(0))
  54. let bytesWritten: Int
  55. do {
  56. var buffer = buffer
  57. bytesWritten = try compressor.deflate(&buffer, into: &self.scratch)
  58. } catch {
  59. throw error
  60. }
  61. // Now fill in the message length.
  62. self.scratch.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  63. // Finally, the compression context should be reset between messages.
  64. compressor.reset()
  65. return self.scratch
  66. }
  67. /// Writes the readable bytes of `buffer` as a gRPC length-prefixed message.
  68. ///
  69. /// - Parameters:
  70. /// - buffer: The bytes to compress and length-prefix.
  71. /// - compressed: Whether the bytes should be compressed. This is ignored if not compression
  72. /// mechanism was configured on this writer.
  73. /// - Returns: A buffer containing the length prefixed bytes.
  74. mutating func write(
  75. buffer: ByteBuffer,
  76. compressed: Bool = true
  77. ) throws -> (ByteBuffer, ByteBuffer?) {
  78. if compressed, let compressor = self.compressor {
  79. let compressedAndFramedPayload = try self.compress(buffer: buffer, using: compressor)
  80. return (compressedAndFramedPayload, nil)
  81. } else if buffer.readableBytes > Self.singleBufferSizeLimit {
  82. // Buffer is larger than the limit for emitting a single buffer: create a second buffer
  83. // containing just the message header.
  84. self.scratch.clear(minimumCapacity: 5)
  85. self.scratch.writeMultipleIntegers(UInt8(0), UInt32(buffer.readableBytes))
  86. return (self.scratch, buffer)
  87. } else {
  88. // We're not compressing and the message is within our single buffer size limit.
  89. self.scratch.clear(minimumCapacity: 5 &+ buffer.readableBytes)
  90. self.scratch.writeMultipleIntegers(UInt8(0), UInt32(buffer.readableBytes))
  91. self.scratch.writeImmutableBuffer(buffer)
  92. return (self.scratch, nil)
  93. }
  94. }
  95. /// Message size above which we emit two buffers: one containing the header and one with the
  96. /// actual message bytes. At or below the limit we copy the message into a new buffer containing
  97. /// both the header and the message.
  98. ///
  99. /// Using two buffers avoids expensive copies of large messages. For smaller messages the copy
  100. /// is cheaper than the additional allocations and overhead required to send an extra HTTP/2 DATA
  101. /// frame.
  102. ///
  103. /// The value of 8192 was chosen empirically. We subtract the length of the message header
  104. /// as `ByteBuffer` reserve capacity in powers of two and want to avoid overallocating.
  105. private static let singleBufferSizeLimit = 8192 - 5
  106. }
  107. extension ByteBuffer {
  108. @discardableResult
  109. mutating func writePayloadLength(_ length: UInt32, at index: Int) -> Int {
  110. let writerIndex = self.writerIndex
  111. defer {
  112. self.moveWriterIndex(to: writerIndex)
  113. }
  114. self.moveWriterIndex(to: index)
  115. return self.writeInteger(length)
  116. }
  117. }