GRPCClientChannelHandler.swift 19 KB

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