LengthPrefixedMessageReader.swift 4.6 KB

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