_GRPCClientChannelHandler.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 NIO
  17. import NIOHTTP1
  18. import NIOHPACK
  19. import NIOHTTP2
  20. import SwiftProtobuf
  21. import Logging
  22. /// A gRPC client request message part.
  23. public enum GRPCClientRequestPart<Request: Message> {
  24. /// The 'head' of the request, that is, information about the initiation of the RPC.
  25. case head(GRPCRequestHead)
  26. /// A deserialized request message to send to the server.
  27. case message(_Box<Request>)
  28. /// Indicates that the client does not intend to send any further messages.
  29. case end
  30. }
  31. public struct GRPCRequestHead {
  32. private final class _Storage {
  33. public var method: String
  34. public var scheme: String
  35. public var path: String
  36. public var host: String
  37. public var timeout: GRPCTimeout
  38. init(
  39. method: String,
  40. scheme: String,
  41. path: String,
  42. host: String,
  43. timeout: GRPCTimeout
  44. ) {
  45. self.method = method
  46. self.scheme = scheme
  47. self.path = path
  48. self.host = host
  49. self.timeout = timeout
  50. }
  51. func copy() -> _Storage {
  52. return .init(
  53. method: self.method,
  54. scheme: self.scheme,
  55. path: self.path,
  56. host: self.host,
  57. timeout: self.timeout
  58. )
  59. }
  60. }
  61. private var _storage: _Storage
  62. // Don't put this in storage: it would CoW for every mutation.
  63. public var customMetadata: HPACKHeaders
  64. public var method: String {
  65. get {
  66. return self._storage.method
  67. }
  68. set {
  69. if !isKnownUniquelyReferenced(&self._storage) {
  70. self._storage = self._storage.copy()
  71. }
  72. self._storage.method = newValue
  73. }
  74. }
  75. public var scheme: String {
  76. get {
  77. return self._storage.scheme
  78. }
  79. set {
  80. if !isKnownUniquelyReferenced(&self._storage) {
  81. self._storage = self._storage.copy()
  82. }
  83. self._storage.scheme = newValue
  84. }
  85. }
  86. public var path: String {
  87. get {
  88. return self._storage.path
  89. }
  90. set {
  91. if !isKnownUniquelyReferenced(&self._storage) {
  92. self._storage = self._storage.copy()
  93. }
  94. self._storage.path = newValue
  95. }
  96. }
  97. public var host: String {
  98. get {
  99. return self._storage.host
  100. }
  101. set {
  102. if !isKnownUniquelyReferenced(&self._storage) {
  103. self._storage = self._storage.copy()
  104. }
  105. self._storage.host = newValue
  106. }
  107. }
  108. public var timeout: GRPCTimeout {
  109. get {
  110. return self._storage.timeout
  111. }
  112. set {
  113. if !isKnownUniquelyReferenced(&self._storage) {
  114. self._storage = self._storage.copy()
  115. }
  116. self._storage.timeout = newValue
  117. }
  118. }
  119. public init(
  120. method: String,
  121. scheme: String,
  122. path: String,
  123. host: String,
  124. timeout: GRPCTimeout,
  125. customMetadata: HPACKHeaders
  126. ) {
  127. self._storage = .init(
  128. method: method,
  129. scheme: scheme,
  130. path: path,
  131. host: host,
  132. timeout: timeout
  133. )
  134. self.customMetadata = customMetadata
  135. }
  136. }
  137. /// A gRPC client response message part.
  138. public enum GRPCClientResponsePart<Response: Message> {
  139. /// Metadata received as the server acknowledges the RPC.
  140. case initialMetadata(HPACKHeaders)
  141. /// A deserialized response message received from the server.
  142. case message(_Box<Response>)
  143. /// The metadata received at the end of the RPC.
  144. case trailingMetadata(HPACKHeaders)
  145. /// The final status of the RPC.
  146. case status(GRPCStatus)
  147. }
  148. /// The type of gRPC call.
  149. public enum GRPCCallType {
  150. /// Unary: a single request and a single response.
  151. case unary
  152. /// Client streaming: many requests and a single response.
  153. case clientStreaming
  154. /// Server streaming: a single request and many responses.
  155. case serverStreaming
  156. /// Bidirectional streaming: many request and many responses.
  157. case bidirectionalStreaming
  158. }
  159. // MARK: - GRPCClientChannelHandler
  160. /// A channel handler for gRPC clients which translates HTTP/2 frames into gRPC messages.
  161. ///
  162. /// This channel handler should typically be used in conjunction with another handler which
  163. /// reads the parsed `GRPCClientResponsePart<Response>` messages and surfaces them to the caller
  164. /// in some fashion. Note that for unary and client streaming RPCs this handler will only emit at
  165. /// most one response message.
  166. ///
  167. /// This handler relies heavily on the `GRPCClientStateMachine` to manage the state of the request
  168. /// and response streams, which share a single HTTP/2 stream for transport.
  169. ///
  170. /// Typical usage of this handler is with a `HTTP2StreamMultiplexer` from SwiftNIO HTTP2:
  171. ///
  172. /// ```
  173. /// let multiplexer: HTTP2StreamMultiplexer = // ...
  174. /// multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in
  175. /// let clientChannelHandler = GRPCClientChannelHandler<Request, Response>(
  176. /// streamID: streamID,
  177. /// callType: callType,
  178. /// logger: logger
  179. /// )
  180. /// return channel.pipeline.addHandler(clientChannelHandler)
  181. /// }
  182. /// ```
  183. ///
  184. /// - Important: This is **NOT** part of the public API. It is declared as
  185. /// `public` because it is used within performance tests.
  186. public final class _GRPCClientChannelHandler<Request: Message, Response: Message> {
  187. private let logger: Logger
  188. private let streamID: HTTP2StreamID
  189. private var stateMachine: GRPCClientStateMachine<Request, Response>
  190. /// Creates a new gRPC channel handler for clients to translate HTTP/2 frames to gRPC messages.
  191. ///
  192. /// - Parameters:
  193. /// - streamID: The ID of the HTTP/2 stream that this handler will read and write HTTP/2
  194. /// frames on.
  195. /// - callType: Type of RPC call being made.
  196. /// - logger: Logger.
  197. public init(streamID: HTTP2StreamID, callType: GRPCCallType, logger: Logger) {
  198. self.streamID = streamID
  199. self.logger = logger
  200. switch callType {
  201. case .unary:
  202. self.stateMachine = .init(requestArity: .one, responseArity: .one)
  203. case .clientStreaming:
  204. self.stateMachine = .init(requestArity: .many, responseArity: .one)
  205. case .serverStreaming:
  206. self.stateMachine = .init(requestArity: .one, responseArity: .many)
  207. case .bidirectionalStreaming:
  208. self.stateMachine = .init(requestArity: .many, responseArity: .many)
  209. }
  210. }
  211. }
  212. // MARK: - GRPCClientChannelHandler: Inbound
  213. extension _GRPCClientChannelHandler: ChannelInboundHandler {
  214. public typealias InboundIn = HTTP2Frame
  215. public typealias InboundOut = GRPCClientResponsePart<Response>
  216. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  217. let frame = self.unwrapInboundIn(data)
  218. switch frame.payload {
  219. case .headers(let content):
  220. self.readHeaders(content: content, context: context)
  221. case .data(let content):
  222. self.readData(content: content, context: context)
  223. // We don't need to handle other frame type, just drop them instead.
  224. default:
  225. // TODO: synthesise a more precise `GRPCStatus` from RST_STREAM frames in accordance
  226. // with: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#errors
  227. break
  228. }
  229. }
  230. /// Read the content from an HTTP/2 HEADERS frame received from the server.
  231. ///
  232. /// We can receive headers in two cases:
  233. /// - when the RPC is being acknowledged, and
  234. /// - when the RPC is being terminated.
  235. ///
  236. /// It is also possible for the RPC to be acknowledged and terminated at the same time, the
  237. /// specification refers to this as a "Trailers-Only" response.
  238. ///
  239. /// - Parameter content: Content of the headers frame.
  240. /// - Parameter context: Channel handler context.
  241. private func readHeaders(content: HTTP2Frame.FramePayload.Headers, context: ChannelHandlerContext) {
  242. // In the case of a "Trailers-Only" response there's no guarantee that end-of-stream will be set
  243. // on the headers frame: end stream may be sent on an empty data frame as well. If the headers
  244. // contain a gRPC status code then they must be for a "Trailers-Only" response.
  245. if content.endStream || content.headers.contains(name: GRPCHeaderName.statusCode) {
  246. // We have the headers, pass them to the next handler:
  247. context.fireChannelRead(self.wrapInboundOut(.trailingMetadata(content.headers)))
  248. // Are they valid headers?
  249. let result = self.stateMachine.receiveEndOfResponseStream(content.headers).mapError { error -> GRPCError in
  250. // The headers aren't valid so let's figure out a reasonable error to forward:
  251. switch error {
  252. case .invalidContentType:
  253. return .client(.invalidContentType)
  254. case .invalidHTTPStatus(let status):
  255. return .client(.invalidHTTPStatus(status))
  256. case .invalidHTTPStatusWithGRPCStatus(let status):
  257. return .client(.invalidHTTPStatusWithGRPCStatus(status))
  258. case .invalidState:
  259. return .client(.invalidState("invalid state parsing end-of-stream trailers"))
  260. }
  261. }
  262. // Okay, what should we tell the next handler?
  263. switch result {
  264. case .success(let status):
  265. context.fireChannelRead(self.wrapInboundOut(.status(status)))
  266. case .failure(let error):
  267. context.fireErrorCaught(error)
  268. }
  269. } else {
  270. // "Normal" response headers, but are they valid?
  271. let result = self.stateMachine.receiveResponseHeaders(content.headers).mapError { error -> GRPCError in
  272. // The headers aren't valid so let's figure out a reasonable error to forward:
  273. switch error {
  274. case .invalidContentType:
  275. return .client(.invalidContentType)
  276. case .invalidHTTPStatus(let status):
  277. return .client(.invalidHTTPStatus(status))
  278. case .unsupportedMessageEncoding(let encoding):
  279. return .client(.unsupportedCompressionMechanism(encoding))
  280. case .invalidState:
  281. return .client(.invalidState("invalid state parsing headers"))
  282. }
  283. }
  284. // Okay, what should we tell the next handler?
  285. switch result {
  286. case .success:
  287. context.fireChannelRead(self.wrapInboundOut(.initialMetadata(content.headers)))
  288. case .failure(let error):
  289. context.fireErrorCaught(error)
  290. }
  291. }
  292. }
  293. /// Reads the content from an HTTP/2 DATA frame received from the server and buffers the bytes
  294. /// necessary to deserialize a message (or messages).
  295. ///
  296. /// - Parameter content: Content of the data frame.
  297. /// - Parameter context: Channel handler context.
  298. private func readData(content: HTTP2Frame.FramePayload.Data, context: ChannelHandlerContext) {
  299. // Note: this is replicated from NIO's HTTP2ToHTTP1ClientCodec.
  300. guard case .byteBuffer(var buffer) = content.data else {
  301. preconditionFailure("Received DATA frame with non-ByteBuffer IOData")
  302. }
  303. // Do we have bytes to read? If there are no bytes to read then we can't do anything. This may
  304. // happen if the end-of-stream flag is not set on the trailing headers frame (i.e. the one
  305. // containing the gRPC status code) and an additional empty data frame is sent with the
  306. // end-of-stream flag set.
  307. guard buffer.readableBytes > 0 else {
  308. return
  309. }
  310. // Feed the buffer into the state machine.
  311. let result = self.stateMachine.receiveResponseBuffer(&buffer).mapError { error -> GRPCError in
  312. switch error {
  313. case .cardinalityViolation:
  314. return .client(.responseCardinalityViolation)
  315. case .deserializationFailed, .leftOverBytes:
  316. return .client(.responseProtoDeserializationFailure)
  317. case .invalidState:
  318. return .client(.invalidState("invalid state when parsing data as a response message"))
  319. }
  320. }
  321. // Did we get any messages?
  322. switch result {
  323. case .success(let messages):
  324. // Awesome: we got some messages. The state machine guarantees we only get at most a single
  325. // message for unary and client-streaming RPCs.
  326. for message in messages {
  327. context.fireChannelRead(self.wrapInboundOut(.message(.init(message))))
  328. }
  329. case .failure(let error):
  330. context.fireErrorCaught(error)
  331. }
  332. }
  333. }
  334. // MARK: - GRPCClientChannelHandler: Outbound
  335. extension _GRPCClientChannelHandler: ChannelOutboundHandler {
  336. public typealias OutboundIn = GRPCClientRequestPart<Request>
  337. public typealias OutboundOut = HTTP2Frame
  338. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  339. switch self.unwrapOutboundIn(data) {
  340. case .head(let requestHead):
  341. // Feed the request into the state machine:
  342. switch self.stateMachine.sendRequestHeaders(requestHead: requestHead) {
  343. case .success(let headers):
  344. // We're clear to write some headers. Create an appropriate frame and write it.
  345. let frame = HTTP2Frame(streamID: self.streamID, payload: .headers(.init(headers: headers)))
  346. context.write(self.wrapOutboundOut(frame), promise: promise)
  347. case .failure(let sendRequestHeadersError):
  348. switch sendRequestHeadersError {
  349. case .invalidState:
  350. // This is bad: we need to trigger an error and close the channel.
  351. promise?.fail(sendRequestHeadersError)
  352. context.fireErrorCaught(GRPCError.client(.invalidState("unable to initiate RPC")))
  353. }
  354. }
  355. case .message(let request):
  356. // Feed the request message into the state machine:
  357. let result = self.stateMachine.sendRequest(request.value, allocator: context.channel.allocator)
  358. switch result {
  359. case .success(let buffer):
  360. // We're clear to send a message; wrap it up in an HTTP/2 frame.
  361. let frame = HTTP2Frame(
  362. streamID: self.streamID,
  363. payload: .data(.init(data: .byteBuffer(buffer)))
  364. )
  365. context.write(self.wrapOutboundOut(frame), promise: promise)
  366. case .failure(let writeError):
  367. switch writeError {
  368. case .cardinalityViolation:
  369. // This is fine: we can ignore the request. The RPC can continue as if nothing went wrong.
  370. promise?.fail(writeError)
  371. case .serializationFailed:
  372. // This is bad: we need to trigger an error and close the channel.
  373. promise?.fail(writeError)
  374. context.fireErrorCaught(GRPCError.client(.requestProtoSerializationFailure))
  375. case .invalidState:
  376. promise?.fail(writeError)
  377. context.fireErrorCaught(GRPCError.client(.invalidState("unable to write message")))
  378. }
  379. }
  380. case .end:
  381. // Okay: can we close the request stream?
  382. switch self.stateMachine.sendEndOfRequestStream() {
  383. case .success:
  384. // We can. Send an empty DATA frame with end-stream set.
  385. let empty = context.channel.allocator.buffer(capacity: 0)
  386. let frame = HTTP2Frame(
  387. streamID: self.streamID,
  388. payload: .data(.init(data: .byteBuffer(empty), endStream: true))
  389. )
  390. context.write(self.wrapOutboundOut(frame), promise: promise)
  391. case .failure(let error):
  392. // Why can't we close the request stream?
  393. switch error {
  394. case .alreadyClosed:
  395. // This is fine: we can just ignore it. The RPC can continue as if nothing went wrong.
  396. promise?.fail(error)
  397. case .invalidState:
  398. // This is bad: we need to trigger an error and close the channel.
  399. promise?.fail(error)
  400. context.fireErrorCaught(GRPCError.client(.invalidState("unable to close request stream")))
  401. }
  402. }
  403. }
  404. }
  405. public func triggerUserOutboundEvent(
  406. context: ChannelHandlerContext,
  407. event: Any,
  408. promise: EventLoopPromise<Void>?
  409. ) {
  410. if let userEvent = event as? GRPCClientUserEvent {
  411. switch userEvent {
  412. case .cancelled:
  413. context.fireErrorCaught(GRPCClientError.cancelledByClient)
  414. context.close(mode: .all, promise: promise)
  415. }
  416. } else {
  417. context.triggerUserOutboundEvent(event, promise: promise)
  418. }
  419. }
  420. }