LengthPrefixedMessageWriter.swift 4.8 KB

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