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