LengthPrefixedMessageReader.swift 4.6 KB

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