_GRPCClientChannelHandler.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. ///
  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. }
  214. // MARK: - GRPCClientChannelHandler
  215. /// A channel handler for gRPC clients which translates HTTP/2 frames into gRPC messages.
  216. ///
  217. /// This channel handler should typically be used in conjunction with another handler which
  218. /// reads the parsed `GRPCClientResponsePart<Response>` messages and surfaces them to the caller
  219. /// in some fashion. Note that for unary and client streaming RPCs this handler will only emit at
  220. /// most one response message.
  221. ///
  222. /// This handler relies heavily on the `GRPCClientStateMachine` to manage the state of the request
  223. /// and response streams, which share a single HTTP/2 stream for transport.
  224. ///
  225. /// Typical usage of this handler is with a `HTTP2StreamMultiplexer` from SwiftNIO HTTP2:
  226. ///
  227. /// ```
  228. /// let multiplexer: HTTP2StreamMultiplexer = // ...
  229. /// multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in
  230. /// let clientChannelHandler = GRPCClientChannelHandler<Request, Response>(
  231. /// streamID: streamID,
  232. /// callType: callType,
  233. /// logger: logger
  234. /// )
  235. /// return channel.pipeline.addHandler(clientChannelHandler)
  236. /// }
  237. /// ```
  238. ///
  239. /// - Important: This is **NOT** part of the public API. It is declared as
  240. /// `public` because it is used within performance tests.
  241. public final class _GRPCClientChannelHandler {
  242. private let logger: Logger
  243. private var stateMachine: GRPCClientStateMachine
  244. /// Creates a new gRPC channel handler for clients to translate HTTP/2 frames to gRPC messages.
  245. ///
  246. /// - Parameters:
  247. /// - callType: Type of RPC call being made.
  248. /// - logger: Logger.
  249. public init(callType: GRPCCallType, logger: Logger) {
  250. self.logger = logger
  251. switch callType {
  252. case .unary:
  253. self.stateMachine = .init(requestArity: .one, responseArity: .one)
  254. case .clientStreaming:
  255. self.stateMachine = .init(requestArity: .many, responseArity: .one)
  256. case .serverStreaming:
  257. self.stateMachine = .init(requestArity: .one, responseArity: .many)
  258. case .bidirectionalStreaming:
  259. self.stateMachine = .init(requestArity: .many, responseArity: .many)
  260. }
  261. }
  262. }
  263. // MARK: - GRPCClientChannelHandler: Inbound
  264. extension _GRPCClientChannelHandler: ChannelInboundHandler {
  265. public typealias InboundIn = HTTP2Frame.FramePayload
  266. public typealias InboundOut = _RawGRPCClientResponsePart
  267. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  268. let payload = self.unwrapInboundIn(data)
  269. switch payload {
  270. case .headers(let content):
  271. self.readHeaders(content: content, context: context)
  272. case .data(let content):
  273. self.readData(content: content, context: context)
  274. // We don't need to handle other frame type, just drop them instead.
  275. default:
  276. // TODO: synthesise a more precise `GRPCStatus` from RST_STREAM frames in accordance
  277. // with: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#errors
  278. break
  279. }
  280. }
  281. /// Read the content from an HTTP/2 HEADERS frame received from the server.
  282. ///
  283. /// We can receive headers in two cases:
  284. /// - when the RPC is being acknowledged, and
  285. /// - when the RPC is being terminated.
  286. ///
  287. /// It is also possible for the RPC to be acknowledged and terminated at the same time, the
  288. /// specification refers to this as a "Trailers-Only" response.
  289. ///
  290. /// - Parameter content: Content of the headers frame.
  291. /// - Parameter context: Channel handler context.
  292. private func readHeaders(content: HTTP2Frame.FramePayload.Headers, context: ChannelHandlerContext) {
  293. // In the case of a "Trailers-Only" response there's no guarantee that end-of-stream will be set
  294. // on the headers frame: end stream may be sent on an empty data frame as well. If the headers
  295. // contain a gRPC status code then they must be for a "Trailers-Only" response.
  296. if content.endStream || content.headers.contains(name: GRPCHeaderName.statusCode) {
  297. // We have the headers, pass them to the next handler:
  298. context.fireChannelRead(self.wrapInboundOut(.trailingMetadata(content.headers)))
  299. // Are they valid headers?
  300. let result = self.stateMachine.receiveEndOfResponseStream(content.headers).mapError { error -> GRPCError.WithContext in
  301. // The headers aren't valid so let's figure out a reasonable error to forward:
  302. switch error {
  303. case .invalidContentType(let contentType):
  304. return GRPCError.InvalidContentType(contentType).captureContext()
  305. case .invalidHTTPStatus(let status):
  306. return GRPCError.InvalidHTTPStatus(status).captureContext()
  307. case .invalidHTTPStatusWithGRPCStatus(let status):
  308. return GRPCError.InvalidHTTPStatusWithGRPCStatus(status).captureContext()
  309. case .invalidState:
  310. return GRPCError.InvalidState("parsing end-of-stream trailers").captureContext()
  311. }
  312. }
  313. // Okay, what should we tell the next handler?
  314. switch result {
  315. case .success(let status):
  316. context.fireChannelRead(self.wrapInboundOut(.status(status)))
  317. case .failure(let error):
  318. context.fireErrorCaught(error)
  319. }
  320. } else {
  321. // "Normal" response headers, but are they valid?
  322. let result = self.stateMachine.receiveResponseHeaders(content.headers).mapError { error -> GRPCError.WithContext in
  323. // The headers aren't valid so let's figure out a reasonable error to forward:
  324. switch error {
  325. case .invalidContentType(let contentType):
  326. return GRPCError.InvalidContentType(contentType).captureContext()
  327. case .invalidHTTPStatus(let status):
  328. return GRPCError.InvalidHTTPStatus(status).captureContext()
  329. case .unsupportedMessageEncoding:
  330. return GRPCError.CompressionUnsupported().captureContext()
  331. case .invalidState:
  332. return GRPCError.InvalidState("parsing headers").captureContext()
  333. }
  334. }
  335. // Okay, what should we tell the next handler?
  336. switch result {
  337. case .success:
  338. context.fireChannelRead(self.wrapInboundOut(.initialMetadata(content.headers)))
  339. case .failure(let error):
  340. context.fireErrorCaught(error)
  341. }
  342. }
  343. }
  344. /// Reads the content from an HTTP/2 DATA frame received from the server and buffers the bytes
  345. /// necessary to deserialize a message (or messages).
  346. ///
  347. /// - Parameter content: Content of the data frame.
  348. /// - Parameter context: Channel handler context.
  349. private func readData(content: HTTP2Frame.FramePayload.Data, context: ChannelHandlerContext) {
  350. // Note: this is replicated from NIO's HTTP2ToHTTP1ClientCodec.
  351. guard case .byteBuffer(var buffer) = content.data else {
  352. preconditionFailure("Received DATA frame with non-ByteBuffer IOData")
  353. }
  354. // Do we have bytes to read? If there are no bytes to read then we can't do anything. This may
  355. // happen if the end-of-stream flag is not set on the trailing headers frame (i.e. the one
  356. // containing the gRPC status code) and an additional empty data frame is sent with the
  357. // end-of-stream flag set.
  358. guard buffer.readableBytes > 0 else {
  359. return
  360. }
  361. // Feed the buffer into the state machine.
  362. let result = self.stateMachine.receiveResponseBuffer(&buffer).mapError { error -> GRPCError.WithContext in
  363. switch error {
  364. case .cardinalityViolation:
  365. return GRPCError.StreamCardinalityViolation.response.captureContext()
  366. case .deserializationFailed, .leftOverBytes:
  367. return GRPCError.DeserializationFailure().captureContext()
  368. case .decompressionLimitExceeded(let compressedSize):
  369. return GRPCError.DecompressionLimitExceeded(compressedSize: compressedSize).captureContext()
  370. case .invalidState:
  371. return GRPCError.InvalidState("parsing data as a response message").captureContext()
  372. }
  373. }
  374. // Did we get any messages?
  375. switch result {
  376. case .success(let messages):
  377. // Awesome: we got some messages. The state machine guarantees we only get at most a single
  378. // message for unary and client-streaming RPCs.
  379. for message in messages {
  380. // Note: `compressed: false` is currently just a placeholder. This is fine since the message
  381. // context is not currently exposed to the user. If we implement interceptors for the client
  382. // and decide to surface this information then we'll need to extract that information from
  383. // the message reader.
  384. context.fireChannelRead(self.wrapInboundOut(.message(.init(message, compressed: false))))
  385. }
  386. case .failure(let error):
  387. context.fireErrorCaught(error)
  388. }
  389. }
  390. }
  391. // MARK: - GRPCClientChannelHandler: Outbound
  392. extension _GRPCClientChannelHandler: ChannelOutboundHandler {
  393. public typealias OutboundIn = _RawGRPCClientRequestPart
  394. public typealias OutboundOut = HTTP2Frame.FramePayload
  395. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  396. switch self.unwrapOutboundIn(data) {
  397. case .head(let requestHead):
  398. // Feed the request into the state machine:
  399. switch self.stateMachine.sendRequestHeaders(requestHead: requestHead) {
  400. case .success(let headers):
  401. // We're clear to write some headers. Create an appropriate frame and write it.
  402. let framePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers))
  403. context.write(self.wrapOutboundOut(framePayload), promise: promise)
  404. case .failure(let sendRequestHeadersError):
  405. switch sendRequestHeadersError {
  406. case .invalidState:
  407. // This is bad: we need to trigger an error and close the channel.
  408. promise?.fail(sendRequestHeadersError)
  409. context.fireErrorCaught(GRPCError.InvalidState("unable to initiate RPC").captureContext())
  410. }
  411. }
  412. case .message(let request):
  413. // Feed the request message into the state machine:
  414. let result = self.stateMachine.sendRequest(request.message, compressed: request.compressed, allocator: context.channel.allocator)
  415. switch result {
  416. case .success(let buffer):
  417. // We're clear to send a message; wrap it up in an HTTP/2 frame.
  418. let framePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(buffer)))
  419. context.write(self.wrapOutboundOut(framePayload), promise: promise)
  420. case .failure(let writeError):
  421. switch writeError {
  422. case .cardinalityViolation:
  423. // This is fine: we can ignore the request. The RPC can continue as if nothing went wrong.
  424. promise?.fail(writeError)
  425. case .serializationFailed:
  426. // This is bad: we need to trigger an error and close the channel.
  427. promise?.fail(writeError)
  428. context.fireErrorCaught(GRPCError.SerializationFailure().captureContext())
  429. case .invalidState:
  430. promise?.fail(writeError)
  431. context.fireErrorCaught(GRPCError.InvalidState("unable to write message").captureContext())
  432. }
  433. }
  434. case .end:
  435. // Okay: can we close the request stream?
  436. switch self.stateMachine.sendEndOfRequestStream() {
  437. case .success:
  438. // We can. Send an empty DATA frame with end-stream set.
  439. let empty = context.channel.allocator.buffer(capacity: 0)
  440. let framePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(empty), endStream: true))
  441. context.write(self.wrapOutboundOut(framePayload), promise: promise)
  442. case .failure(let error):
  443. // Why can't we close the request stream?
  444. switch error {
  445. case .alreadyClosed:
  446. // This is fine: we can just ignore it. The RPC can continue as if nothing went wrong.
  447. promise?.fail(error)
  448. case .invalidState:
  449. // This is bad: we need to trigger an error and close the channel.
  450. promise?.fail(error)
  451. context.fireErrorCaught(GRPCError.InvalidState("unable to close request stream").captureContext())
  452. }
  453. }
  454. }
  455. }
  456. }