LengthPrefixedMessageReader.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. public typealias Mode = GRPCError.Origin
  34. /// The mechanism that messages will be compressed with.
  35. var compressionMechanism: CompressionMechanism
  36. init(mode: Mode, compressionMechanism: CompressionMechanism) {
  37. self.mode = mode
  38. self.compressionMechanism = compressionMechanism
  39. }
  40. /// The result of trying to parse a message with the bytes we currently have.
  41. ///
  42. /// - needMoreData: More data is required to continue reading a message.
  43. /// - continue: Continue reading a message.
  44. /// - message: A message was read.
  45. internal enum ParseResult {
  46. case needMoreData
  47. case `continue`
  48. case message(ByteBuffer)
  49. }
  50. /// The parsing state; what we expect to be reading next.
  51. internal enum ParseState {
  52. case expectingCompressedFlag
  53. case expectingMessageLength
  54. case expectingMessage(UInt32)
  55. }
  56. private let mode: Mode
  57. private var buffer: ByteBuffer!
  58. private var state: ParseState = .expectingCompressedFlag
  59. /// Returns the number of unprocessed bytes.
  60. internal var unprocessedBytes: Int {
  61. return self.buffer.map { $0.readableBytes } ?? 0
  62. }
  63. /// Whether the reader is mid-way through reading a message.
  64. internal var isReading: Bool {
  65. switch self.state {
  66. case .expectingCompressedFlag:
  67. return false
  68. case .expectingMessageLength, .expectingMessage:
  69. return true
  70. }
  71. }
  72. /// Appends data to the buffer from which messages will be read.
  73. internal mutating func append(buffer: inout ByteBuffer) {
  74. guard buffer.readableBytes > 0 else {
  75. return
  76. }
  77. if self.buffer == nil {
  78. self.buffer = buffer.slice()
  79. // mark the bytes as "read"
  80. buffer.moveReaderIndex(forwardBy: buffer.readableBytes)
  81. } else {
  82. self.buffer.writeBuffer(&buffer)
  83. }
  84. }
  85. /// Reads bytes from the buffer until it is exhausted or a message has been read.
  86. ///
  87. /// - Returns: A buffer containing a message if one has been read, or `nil` if not enough
  88. /// bytes have been consumed to return a message.
  89. /// - Throws: Throws an error if the compression algorithm is not supported.
  90. internal mutating func nextMessage() throws -> ByteBuffer? {
  91. switch try self.processNextState() {
  92. case .needMoreData:
  93. self.nilBufferIfPossible()
  94. return nil
  95. case .continue:
  96. return try nextMessage()
  97. case .message(let message):
  98. self.nilBufferIfPossible()
  99. return message
  100. }
  101. }
  102. /// `nil`s out `buffer` if it exists and has no readable bytes.
  103. ///
  104. /// This allows the next call to `append` to avoid writing the contents of the appended buffer.
  105. private mutating func nilBufferIfPossible() {
  106. if self.buffer?.readableBytes == 0 {
  107. self.buffer = nil
  108. }
  109. }
  110. private mutating func processNextState() throws -> ParseResult {
  111. guard self.buffer != nil else {
  112. return .needMoreData
  113. }
  114. switch self.state {
  115. case .expectingCompressedFlag:
  116. guard let compressionFlag: Int8 = self.buffer.readInteger() else {
  117. return .needMoreData
  118. }
  119. try self.handleCompressionFlag(enabled: compressionFlag != 0)
  120. self.state = .expectingMessageLength
  121. case .expectingMessageLength:
  122. guard let messageLength: UInt32 = self.buffer.readInteger() else {
  123. return .needMoreData
  124. }
  125. self.state = .expectingMessage(messageLength)
  126. case .expectingMessage(let length):
  127. let signedLength: Int = numericCast(length)
  128. guard let message = self.buffer.readSlice(length: signedLength) else {
  129. return .needMoreData
  130. }
  131. self.state = .expectingCompressedFlag
  132. return .message(message)
  133. }
  134. return .continue
  135. }
  136. private func handleCompressionFlag(enabled flagEnabled: Bool) throws {
  137. guard flagEnabled else {
  138. return
  139. }
  140. guard self.compressionMechanism.requiresFlag else {
  141. throw GRPCError.common(.unexpectedCompression, origin: mode)
  142. }
  143. guard self.compressionMechanism.supported else {
  144. throw GRPCError.common(.unsupportedCompressionMechanism(compressionMechanism.rawValue), origin: mode)
  145. }
  146. }
  147. }