_GRPCClientChannelHandler.swift 19 KB

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