ClientCallTransport.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. /*
  2. * Copyright 2020, 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 NIOHTTP2
  20. /// This class provides much of the boilerplate for the four types of gRPC call objects returned to
  21. /// framework users. It is the glue between a call object and the underlying transport (typically a
  22. /// NIO Channel).
  23. ///
  24. /// Typically, each call will be configured on an HTTP/2 stream channel. The stream channel will
  25. /// will be configured as such:
  26. ///
  27. /// ```
  28. /// ┌────────────────────────────────────┐
  29. /// │ ChannelTransport<Request,Response> │
  30. /// └─────▲───────────────────────┬──────┘
  31. /// │ │
  32. /// --------------------------------│-----------------------│------------------------------
  33. /// HTTP2StreamChannel │ │
  34. /// ┌────────────┴──────────┐ │
  35. /// │ GRPCClientCallHandler │ │
  36. /// └────────────▲──────────┘ │
  37. /// GRPCClientResponsePart<Response>│ │GRPCClientRequestPart<Request>
  38. /// ┌─┴───────────────────────▼─┐
  39. /// │ GRPCClientChannelHandler │
  40. /// └─▲───────────────────────┬─┘
  41. /// HTTP2Frame│ │HTTP2Frame
  42. /// | |
  43. /// ```
  44. ///
  45. /// Note: the "main" pipeline provided by the channel in `ClientConnection`.
  46. internal class ChannelTransport<Request, Response> {
  47. internal typealias RequestPart = _GRPCClientRequestPart<Request>
  48. internal typealias ResponsePart = _GRPCClientResponsePart<Response>
  49. /// The `EventLoop` this call is running on.
  50. internal let eventLoop: EventLoop
  51. /// A logger.
  52. private let logger: Logger
  53. /// The current state of the call.
  54. private var state: State
  55. /// A scheduled timeout for the call.
  56. private var scheduledTimeout: Scheduled<Void>?
  57. // Note: initial capacity is 4 because it's a power of 2 and most calls are unary so will
  58. // have 3 parts.
  59. /// A buffer to store requests in before the channel has become active.
  60. private var requestBuffer = MarkedCircularBuffer<BufferedRequest>(initialCapacity: 4)
  61. /// A request that we'll deal with at a later point in time.
  62. private struct BufferedRequest {
  63. /// The request to write.
  64. var message: _GRPCClientRequestPart<Request>
  65. /// Any promise associated with the request.
  66. var promise: EventLoopPromise<Void>?
  67. }
  68. /// An error delegate provided by the user.
  69. private var errorDelegate: ClientErrorDelegate?
  70. /// A container for response part promises for the call.
  71. internal var responseContainer: ResponsePartContainer<Response>
  72. /// A stopwatch for timing the RPC.
  73. private var stopwatch: Stopwatch?
  74. enum State {
  75. // Waiting for a stream to become active.
  76. //
  77. // Valid transitions:
  78. // - active
  79. // - closed
  80. case buffering(EventLoopFuture<Channel>)
  81. // We have a channel, we're doing the RPC, there may be a timeout.
  82. //
  83. // Valid transitions:
  84. // - closed
  85. case active(Channel)
  86. // We're closed; the RPC is done for one reason or another. This is terminal.
  87. case closed
  88. }
  89. private init(
  90. eventLoop: EventLoop,
  91. state: State,
  92. responseContainer: ResponsePartContainer<Response>,
  93. errorDelegate: ClientErrorDelegate?,
  94. logger: Logger
  95. ) {
  96. self.eventLoop = eventLoop
  97. self.state = state
  98. self.responseContainer = responseContainer
  99. self.errorDelegate = errorDelegate
  100. self.logger = logger
  101. self.startTimer()
  102. }
  103. internal convenience init(
  104. eventLoop: EventLoop,
  105. responseContainer: ResponsePartContainer<Response>,
  106. timeLimit: TimeLimit,
  107. errorDelegate: ClientErrorDelegate?,
  108. logger: Logger,
  109. channelProvider: (ChannelTransport<Request, Response>, EventLoopPromise<Channel>) -> Void
  110. ) {
  111. let channelPromise = eventLoop.makePromise(of: Channel.self)
  112. self.init(
  113. eventLoop: eventLoop,
  114. state: .buffering(channelPromise.futureResult),
  115. responseContainer: responseContainer,
  116. errorDelegate: errorDelegate,
  117. logger: logger
  118. )
  119. // If the channel creation fails we need to error the call. Note that we receive an
  120. // 'activation' from the channel instead of relying on the success of the future.
  121. channelPromise.futureResult.whenFailure { error in
  122. self.handleError(error, promise: nil)
  123. }
  124. // Schedule the timeout.
  125. self.setUpTimeLimit(timeLimit)
  126. // Now attempt to make the channel.
  127. channelProvider(self, channelPromise)
  128. }
  129. internal convenience init<Serializer: MessageSerializer, Deserializer: MessageDeserializer>(
  130. multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>,
  131. serializer: Serializer,
  132. deserializer: Deserializer,
  133. responseContainer: ResponsePartContainer<Response>,
  134. callType: GRPCCallType,
  135. timeLimit: TimeLimit,
  136. errorDelegate: ClientErrorDelegate?,
  137. logger: Logger
  138. ) where Serializer.Input == Request, Deserializer.Output == Response {
  139. self.init(
  140. eventLoop: multiplexer.eventLoop,
  141. responseContainer: responseContainer,
  142. timeLimit: timeLimit,
  143. errorDelegate: errorDelegate,
  144. logger: logger
  145. ) { call, streamPromise in
  146. multiplexer.whenComplete { result in
  147. switch result {
  148. case let .success(mux):
  149. mux.createStreamChannel(promise: streamPromise) { stream in
  150. stream.pipeline.addHandlers([
  151. _GRPCClientChannelHandler(callType: callType, logger: logger),
  152. GRPCClientCodecHandler(serializer: serializer, deserializer: deserializer),
  153. GRPCClientCallHandler(call: call),
  154. ])
  155. }
  156. case let .failure(error):
  157. streamPromise.fail(error)
  158. }
  159. }
  160. }
  161. }
  162. internal convenience init(
  163. fakeResponse: _FakeResponseStream<Request, Response>,
  164. responseContainer: ResponsePartContainer<Response>,
  165. timeLimit: TimeLimit,
  166. logger: Logger
  167. ) {
  168. self.init(
  169. eventLoop: fakeResponse.channel.eventLoop,
  170. responseContainer: responseContainer,
  171. timeLimit: timeLimit,
  172. errorDelegate: nil,
  173. logger: logger
  174. ) { call, streamPromise in
  175. fakeResponse.channel.pipeline.addHandler(GRPCClientCallHandler(call: call)).map {
  176. fakeResponse.channel
  177. }.cascade(to: streamPromise)
  178. }
  179. }
  180. /// Makes a transport whose channel promise is failed immediately.
  181. internal static func makeTransportForMissingFakeResponse(
  182. eventLoop: EventLoop,
  183. responseContainer: ResponsePartContainer<Response>,
  184. logger: Logger
  185. ) -> ChannelTransport<Request, Response> {
  186. return .init(
  187. eventLoop: eventLoop,
  188. responseContainer: responseContainer,
  189. timeLimit: .none,
  190. errorDelegate: nil,
  191. logger: logger
  192. ) { _, promise in
  193. let error = GRPCStatus(
  194. code: .unavailable,
  195. message: "No fake response was registered before starting an RPC."
  196. )
  197. promise.fail(error)
  198. }
  199. }
  200. }
  201. // MARK: - Call API (i.e. called from {Unary,ClientStreaming,...}Call)
  202. extension ChannelTransport: ClientCallOutbound {
  203. /// Send a request part.
  204. ///
  205. /// Does not have to be called from the event loop.
  206. internal func sendRequest(_ part: RequestPart, promise: EventLoopPromise<Void>?) {
  207. if self.eventLoop.inEventLoop {
  208. self.writePart(part, flush: true, promise: promise)
  209. } else {
  210. self.eventLoop.execute {
  211. self.writePart(part, flush: true, promise: promise)
  212. }
  213. }
  214. }
  215. /// Send multiple request parts.
  216. ///
  217. /// Does not have to be called from the event loop.
  218. internal func sendRequests<S>(
  219. _ parts: S,
  220. promise: EventLoopPromise<Void>?
  221. ) where S: Sequence, S.Element == RequestPart {
  222. if self.eventLoop.inEventLoop {
  223. self._sendRequests(parts, promise: promise)
  224. } else {
  225. self.eventLoop.execute {
  226. self._sendRequests(parts, promise: promise)
  227. }
  228. }
  229. }
  230. /// Request that the RPC is cancelled.
  231. ///
  232. /// Does not have to be called from the event loop.
  233. internal func cancel(promise: EventLoopPromise<Void>?) {
  234. self.logger.info("rpc cancellation requested", source: "GRPC")
  235. if self.eventLoop.inEventLoop {
  236. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  237. } else {
  238. self.eventLoop.execute {
  239. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  240. }
  241. }
  242. }
  243. /// Returns the `Channel` for the HTTP/2 stream that this RPC is using.
  244. internal func streamChannel() -> EventLoopFuture<Channel> {
  245. if self.eventLoop.inEventLoop {
  246. return self.getStreamChannel()
  247. } else {
  248. return self.eventLoop.flatSubmit {
  249. self.getStreamChannel()
  250. }
  251. }
  252. }
  253. }
  254. extension ChannelTransport {
  255. /// Return a future for the stream channel.
  256. ///
  257. /// Must be called from the event loop.
  258. private func getStreamChannel() -> EventLoopFuture<Channel> {
  259. self.eventLoop.preconditionInEventLoop()
  260. switch self.state {
  261. case let .buffering(future):
  262. return future
  263. case let .active(channel):
  264. return self.eventLoop.makeSucceededFuture(channel)
  265. case .closed:
  266. return self.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)
  267. }
  268. }
  269. /// Send many requests.
  270. ///
  271. /// Must be called from the event loop.
  272. private func _sendRequests<S>(
  273. _ parts: S,
  274. promise: EventLoopPromise<Void>?
  275. ) where S: Sequence, S.Element == RequestPart {
  276. self.eventLoop.preconditionInEventLoop()
  277. // We have a promise: create one for each request part and cascade the overall result to it.
  278. // If we're flushing we'll do it at the end.
  279. if let promise = promise {
  280. let loop = promise.futureResult.eventLoop
  281. let futures: [EventLoopFuture<Void>] = parts.map { part in
  282. let partPromise = loop.makePromise(of: Void.self)
  283. self.writePart(part, flush: false, promise: partPromise)
  284. return partPromise.futureResult
  285. }
  286. // Cascade the futures to the provided promise.
  287. EventLoopFuture.andAllSucceed(futures, on: loop).cascade(to: promise)
  288. } else {
  289. for part in parts {
  290. self.writePart(part, flush: false, promise: nil)
  291. }
  292. }
  293. // Now flush.
  294. self.flush()
  295. }
  296. /// Buffer or send a flush.
  297. ///
  298. /// Must be called from the event loop.
  299. private func flush() {
  300. self.eventLoop.preconditionInEventLoop()
  301. switch self.state {
  302. case .buffering:
  303. self.requestBuffer.mark()
  304. case let .active(stream):
  305. stream.flush()
  306. case .closed:
  307. ()
  308. }
  309. }
  310. /// Write a request part.
  311. ///
  312. /// Must be called from the event loop.
  313. ///
  314. /// - Parameters:
  315. /// - part: The part to write.
  316. /// - flush: Whether we should flush the channel after this write.
  317. /// - promise: A promise to fulfill when the part has been written.
  318. private func writePart(_ part: RequestPart, flush: Bool, promise: EventLoopPromise<Void>?) {
  319. self.eventLoop.assertInEventLoop()
  320. switch self.state {
  321. // We're buffering, so buffer the message.
  322. case .buffering:
  323. self.logger.debug("buffering request part", metadata: [
  324. "request_part": "\(part.name)",
  325. "call_state": "\(self.describeCallState())",
  326. ], source: "GRPC")
  327. self.requestBuffer.append(BufferedRequest(message: part, promise: promise))
  328. if flush {
  329. self.requestBuffer.mark()
  330. }
  331. // We have an active stream, just pass the write and promise through.
  332. case let .active(stream):
  333. self.logger.debug(
  334. "writing request part",
  335. metadata: ["request_part": "\(part.name)"],
  336. source: "GRPC"
  337. )
  338. stream.write(part, promise: promise)
  339. if flush {
  340. stream.flush()
  341. }
  342. // We're closed: drop the request.
  343. case .closed:
  344. self.logger.debug("dropping request part", metadata: [
  345. "request_part": "\(part.name)",
  346. "call_state": "\(self.describeCallState())",
  347. ], source: "GRPC")
  348. promise?.fail(ChannelError.ioOnClosedChannel)
  349. }
  350. }
  351. /// The scheduled timeout triggered: timeout the RPC if it's not yet finished.
  352. ///
  353. /// Must be called from the event loop.
  354. private func timedOut(after timeLimit: TimeLimit) {
  355. self.eventLoop.preconditionInEventLoop()
  356. let error = GRPCError.RPCTimedOut(timeLimit).captureContext()
  357. self.handleError(error, promise: nil)
  358. }
  359. /// Handle an error and optionally fail the provided promise with the error.
  360. ///
  361. /// Must be called from the event loop.
  362. private func handleError(_ error: Error, promise: EventLoopPromise<Void>?) {
  363. self.eventLoop.preconditionInEventLoop()
  364. switch self.state {
  365. // We only care about errors if we're not shutdown yet.
  366. case .buffering, .active:
  367. // Add our current state to the logger we provide to the callback.
  368. var loggerWithState = self.logger
  369. loggerWithState[metadataKey: "call_state"] = "\(self.describeCallState())"
  370. let errorStatus: GRPCStatus
  371. let errorWithoutContext: Error
  372. if let errorWithContext = error as? GRPCError.WithContext {
  373. errorStatus = errorWithContext.error.makeGRPCStatus()
  374. errorWithoutContext = errorWithContext.error
  375. self.errorDelegate?.didCatchError(
  376. errorWithContext.error,
  377. logger: loggerWithState,
  378. file: errorWithContext.file,
  379. line: errorWithContext.line
  380. )
  381. } else if let transformable = error as? GRPCStatusTransformable {
  382. errorStatus = transformable.makeGRPCStatus()
  383. errorWithoutContext = error
  384. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  385. } else {
  386. errorStatus = .processingError
  387. errorWithoutContext = error
  388. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  389. }
  390. // Update our state: we're closing.
  391. self.close(error: errorWithoutContext, status: errorStatus)
  392. promise?.fail(errorStatus)
  393. case .closed:
  394. promise?.fail(ChannelError.alreadyClosed)
  395. }
  396. }
  397. /// Close the call, if it's not yet closed with the given status.
  398. ///
  399. /// Must be called from the event loop.
  400. private func close(error: Error, status: GRPCStatus) {
  401. self.eventLoop.preconditionInEventLoop()
  402. switch self.state {
  403. case let .buffering(streamFuture):
  404. // We're closed now.
  405. self.state = .closed
  406. self.stopTimer(status: status)
  407. // We're done; cancel the timeout.
  408. self.scheduledTimeout?.cancel()
  409. self.scheduledTimeout = nil
  410. // Fail any outstanding promises.
  411. self.responseContainer.fail(with: error, status: status)
  412. // Fail any buffered writes.
  413. while !self.requestBuffer.isEmpty {
  414. let write = self.requestBuffer.removeFirst()
  415. write.promise?.fail(status)
  416. }
  417. // Close the channel, if it comes up.
  418. streamFuture.whenSuccess {
  419. $0.close(mode: .all, promise: nil)
  420. }
  421. case let .active(channel):
  422. // We're closed now.
  423. self.state = .closed
  424. self.stopTimer(status: status)
  425. // We're done; cancel the timeout.
  426. self.scheduledTimeout?.cancel()
  427. self.scheduledTimeout = nil
  428. // Fail any outstanding promises.
  429. self.responseContainer.fail(with: error, status: status)
  430. // Close the channel.
  431. channel.close(mode: .all, promise: nil)
  432. case .closed:
  433. ()
  434. }
  435. }
  436. }
  437. // MARK: - Channel Inbound
  438. extension ChannelTransport: ClientCallInbound {
  439. /// Receive an error from the Channel.
  440. ///
  441. /// Must be called on the event loop.
  442. internal func receiveError(_ error: Error) {
  443. self.eventLoop.preconditionInEventLoop()
  444. self.handleError(error, promise: nil)
  445. }
  446. /// Receive a response part from the Channel.
  447. ///
  448. /// Must be called on the event loop.
  449. func receiveResponse(_ part: _GRPCClientResponsePart<Response>) {
  450. self.eventLoop.preconditionInEventLoop()
  451. switch self.state {
  452. case .buffering:
  453. preconditionFailure("Received response part in 'buffering' state")
  454. case .active:
  455. self.logger.debug(
  456. "received response part",
  457. metadata: ["response_part": "\(part.name)"],
  458. source: "GRPC"
  459. )
  460. switch part {
  461. case let .initialMetadata(metadata):
  462. self.responseContainer.lazyInitialMetadataPromise.completeWith(.success(metadata))
  463. case let .message(messageContext):
  464. switch self.responseContainer.responseHandler {
  465. case let .unary(responsePromise):
  466. responsePromise.succeed(messageContext.message)
  467. case let .stream(handler):
  468. handler(messageContext.message)
  469. }
  470. case let .trailingMetadata(metadata):
  471. self.responseContainer.lazyTrailingMetadataPromise.succeed(metadata)
  472. case let .status(status):
  473. // We're done; cancel the timeout.
  474. self.scheduledTimeout?.cancel()
  475. self.scheduledTimeout = nil
  476. // We're closed now.
  477. self.state = .closed
  478. self.stopTimer(status: status)
  479. // We're not really failing the status here; in some cases the server may fast fail, in which
  480. // case we'll only see trailing metadata and status: we should fail the initial metadata and
  481. // response in that case.
  482. self.responseContainer.fail(with: status, status: status)
  483. }
  484. case .closed:
  485. self.logger.debug("dropping response part", metadata: [
  486. "response_part": "\(part.name)",
  487. "call_state": "\(self.describeCallState())",
  488. ], source: "GRPC")
  489. }
  490. }
  491. /// The underlying channel become active and can start accepting writes.
  492. ///
  493. /// Must be called on the event loop.
  494. internal func activate(stream: Channel) {
  495. self.eventLoop.preconditionInEventLoop()
  496. self.logger.debug("activated stream channel", source: "GRPC")
  497. // The channel has become active: what now?
  498. switch self.state {
  499. case .buffering:
  500. while !self.requestBuffer.isEmpty {
  501. // Are we marked?
  502. let hadMark = self.requestBuffer.hasMark
  503. let request = self.requestBuffer.removeFirst()
  504. // We became unmarked: we need to flush.
  505. let shouldFlush = hadMark && !self.requestBuffer.hasMark
  506. self.logger.debug(
  507. "unbuffering request part",
  508. metadata: ["request_part": "\(request.message.name)"],
  509. source: "GRPC"
  510. )
  511. stream.write(request.message, promise: request.promise)
  512. if shouldFlush {
  513. stream.flush()
  514. }
  515. }
  516. self.logger.debug("request buffer drained", source: "GRPC")
  517. self.state = .active(stream)
  518. case .active:
  519. preconditionFailure("Invalid state: stream is already active")
  520. case .closed:
  521. // The channel became active but we're already closed: we must've timed out waiting for the
  522. // channel to activate so close the channel now.
  523. stream.close(mode: .all, promise: nil)
  524. }
  525. }
  526. }
  527. // MARK: Private Helpers
  528. extension ChannelTransport {
  529. private func describeCallState() -> String {
  530. self.eventLoop.preconditionInEventLoop()
  531. switch self.state {
  532. case .buffering:
  533. return "waiting for connection; \(self.requestBuffer.count) request part(s) buffered"
  534. case .active:
  535. return "active"
  536. case .closed:
  537. return "closed"
  538. }
  539. }
  540. private func startTimer() {
  541. assert(self.stopwatch == nil)
  542. self.stopwatch = Stopwatch()
  543. self.logger.debug("starting rpc", source: "GRPC")
  544. }
  545. private func stopTimer(status: GRPCStatus) {
  546. self.eventLoop.preconditionInEventLoop()
  547. if let stopwatch = self.stopwatch {
  548. let millis = stopwatch.elapsedMillis()
  549. self.logger.debug("rpc call finished", metadata: [
  550. "duration_ms": "\(millis)",
  551. "status_code": "\(status.code.rawValue)",
  552. "status_message": "\(status.message ?? "nil")",
  553. ], source: "GRPC")
  554. self.stopwatch = nil
  555. }
  556. }
  557. /// Sets a time limit for the RPC.
  558. private func setUpTimeLimit(_ timeLimit: TimeLimit) {
  559. let deadline = timeLimit.makeDeadline()
  560. guard deadline != .distantFuture else {
  561. // This is too distant to worry about.
  562. return
  563. }
  564. let timedOutTask = {
  565. self.timedOut(after: timeLimit)
  566. }
  567. // 'scheduledTimeout' must only be accessed from the event loop.
  568. if self.eventLoop.inEventLoop {
  569. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  570. } else {
  571. self.eventLoop.execute {
  572. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  573. }
  574. }
  575. }
  576. }
  577. extension _GRPCClientRequestPart {
  578. fileprivate var name: String {
  579. switch self {
  580. case .head:
  581. return "head"
  582. case .message:
  583. return "message"
  584. case .end:
  585. return "end"
  586. }
  587. }
  588. }
  589. extension _GRPCClientResponsePart {
  590. fileprivate var name: String {
  591. switch self {
  592. case .initialMetadata:
  593. return "initial metadata"
  594. case .message:
  595. return "message"
  596. case .trailingMetadata:
  597. return "trailing metadata"
  598. case .status:
  599. return "status"
  600. }
  601. }
  602. }