LengthPrefixedMessageReader.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. import NIOHTTP1
  19. import Logging
  20. /// This class reads and decodes length-prefixed gRPC messages.
  21. ///
  22. /// Messages are expected to be in the following format:
  23. /// - compression flag: 0/1 as a 1-byte unsigned integer,
  24. /// - message length: length of the message as a 4-byte unsigned integer,
  25. /// - message: `message_length` bytes.
  26. ///
  27. /// Messages may span multiple `ByteBuffer`s, and `ByteBuffer`s may contain multiple
  28. /// length-prefixed messages.
  29. ///
  30. /// - SeeAlso:
  31. /// [gRPC Protocol](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md)
  32. internal struct LengthPrefixedMessageReader {
  33. /// The mechanism that messages will be compressed with.
  34. var compressionMechanism: CompressionMechanism
  35. init(compressionMechanism: CompressionMechanism) {
  36. self.compressionMechanism = compressionMechanism
  37. }
  38. /// The result of trying to parse a message with the bytes we currently have.
  39. ///
  40. /// - needMoreData: More data is required to continue reading a message.
  41. /// - continue: Continue reading a message.
  42. /// - message: A message was read.
  43. internal enum ParseResult {
  44. case needMoreData
  45. case `continue`
  46. case message(ByteBuffer)
  47. }
  48. /// The parsing state; what we expect to be reading next.
  49. internal enum ParseState {
  50. case expectingCompressedFlag
  51. case expectingMessageLength
  52. case expectingMessage(UInt32)
  53. }
  54. private var buffer: ByteBuffer!
  55. private var state: ParseState = .expectingCompressedFlag
  56. /// Returns the number of unprocessed bytes.
  57. internal var unprocessedBytes: Int {
  58. return self.buffer.map { $0.readableBytes } ?? 0
  59. }
  60. /// Whether the reader is mid-way through reading a message.
  61. internal var isReading: Bool {
  62. switch self.state {
  63. case .expectingCompressedFlag:
  64. return false
  65. case .expectingMessageLength, .expectingMessage:
  66. return true
  67. }
  68. }
  69. /// Appends data to the buffer from which messages will be read.
  70. internal mutating func append(buffer: inout ByteBuffer) {
  71. guard buffer.readableBytes > 0 else {
  72. return
  73. }
  74. if self.buffer == nil {
  75. self.buffer = buffer.slice()
  76. // mark the bytes as "read"
  77. buffer.moveReaderIndex(forwardBy: buffer.readableBytes)
  78. } else {
  79. self.buffer.writeBuffer(&buffer)
  80. }
  81. }
  82. /// Reads bytes from the buffer until it is exhausted or a message has been read.
  83. ///
  84. /// - Returns: A buffer containing a message if one has been read, or `nil` if not enough
  85. /// bytes have been consumed to return a message.
  86. /// - Throws: Throws an error if the compression algorithm is not supported.
  87. internal mutating func nextMessage() throws -> ByteBuffer? {
  88. switch try self.processNextState() {
  89. case .needMoreData:
  90. self.nilBufferIfPossible()
  91. return nil
  92. case .continue:
  93. return try nextMessage()
  94. case .message(let message):
  95. self.nilBufferIfPossible()
  96. return message
  97. }
  98. }
  99. /// `nil`s out `buffer` if it exists and has no readable bytes.
  100. ///
  101. /// This allows the next call to `append` to avoid writing the contents of the appended buffer.
  102. private mutating func nilBufferIfPossible() {
  103. if self.buffer?.readableBytes == 0 {
  104. self.buffer = nil
  105. }
  106. }
  107. private mutating func processNextState() throws -> ParseResult {
  108. guard self.buffer != nil else {
  109. return .needMoreData
  110. }
  111. switch self.state {
  112. case .expectingCompressedFlag:
  113. guard let compressionFlag: Int8 = self.buffer.readInteger() else {
  114. return .needMoreData
  115. }
  116. try self.handleCompressionFlag(enabled: compressionFlag != 0)
  117. self.state = .expectingMessageLength
  118. case .expectingMessageLength:
  119. guard let messageLength: UInt32 = self.buffer.readInteger() else {
  120. return .needMoreData
  121. }
  122. self.state = .expectingMessage(messageLength)
  123. case .expectingMessage(let length):
  124. let signedLength: Int = numericCast(length)
  125. guard let message = self.buffer.readSlice(length: signedLength) else {
  126. return .needMoreData
  127. }
  128. self.state = .expectingCompressedFlag
  129. return .message(message)
  130. }
  131. return .continue
  132. }
  133. private func handleCompressionFlag(enabled flagEnabled: Bool) throws {
  134. if flagEnabled && !(self.compressionMechanism.requiresFlag && self.compressionMechanism.supported) {
  135. throw GRPCError.CompressionUnsupported().captureContext()
  136. }
  137. }
  138. }