ClientCallTransport.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. logger.trace("created http/2 stream", source: "GRPC")
  151. return stream.pipeline.addHandlers([
  152. _GRPCClientChannelHandler(callType: callType, logger: logger),
  153. GRPCClientCodecHandler(serializer: serializer, deserializer: deserializer),
  154. GRPCClientCallHandler(call: call),
  155. ])
  156. }
  157. case let .failure(error):
  158. streamPromise.fail(error)
  159. }
  160. }
  161. }
  162. }
  163. internal convenience init(
  164. fakeResponse: _FakeResponseStream<Request, Response>,
  165. responseContainer: ResponsePartContainer<Response>,
  166. timeLimit: TimeLimit,
  167. logger: Logger
  168. ) {
  169. self.init(
  170. eventLoop: fakeResponse.channel.eventLoop,
  171. responseContainer: responseContainer,
  172. timeLimit: timeLimit,
  173. errorDelegate: nil,
  174. logger: logger
  175. ) { call, streamPromise in
  176. fakeResponse.channel.pipeline.addHandler(GRPCClientCallHandler(call: call)).map {
  177. fakeResponse.channel
  178. }.cascade(to: streamPromise)
  179. }
  180. }
  181. /// Makes a transport whose channel promise is failed immediately.
  182. internal static func makeTransportForMissingFakeResponse(
  183. eventLoop: EventLoop,
  184. responseContainer: ResponsePartContainer<Response>,
  185. logger: Logger
  186. ) -> ChannelTransport<Request, Response> {
  187. return .init(
  188. eventLoop: eventLoop,
  189. responseContainer: responseContainer,
  190. timeLimit: .none,
  191. errorDelegate: nil,
  192. logger: logger
  193. ) { _, promise in
  194. let error = GRPCStatus(
  195. code: .unavailable,
  196. message: "No fake response was registered before starting an RPC."
  197. )
  198. promise.fail(error)
  199. }
  200. }
  201. }
  202. // MARK: - Call API (i.e. called from {Unary,ClientStreaming,...}Call)
  203. extension ChannelTransport: ClientCallOutbound {
  204. /// Send a request part.
  205. ///
  206. /// Does not have to be called from the event loop.
  207. internal func sendRequest(_ part: RequestPart, promise: EventLoopPromise<Void>?) {
  208. if self.eventLoop.inEventLoop {
  209. self.writePart(part, flush: true, promise: promise)
  210. } else {
  211. self.eventLoop.execute {
  212. self.writePart(part, flush: true, promise: promise)
  213. }
  214. }
  215. }
  216. /// Send multiple request parts.
  217. ///
  218. /// Does not have to be called from the event loop.
  219. internal func sendRequests<S>(
  220. _ parts: S,
  221. promise: EventLoopPromise<Void>?
  222. ) where S: Sequence, S.Element == RequestPart {
  223. if self.eventLoop.inEventLoop {
  224. self._sendRequests(parts, promise: promise)
  225. } else {
  226. self.eventLoop.execute {
  227. self._sendRequests(parts, promise: promise)
  228. }
  229. }
  230. }
  231. /// Request that the RPC is cancelled.
  232. ///
  233. /// Does not have to be called from the event loop.
  234. internal func cancel(promise: EventLoopPromise<Void>?) {
  235. self.logger.info("rpc cancellation requested", source: "GRPC")
  236. if self.eventLoop.inEventLoop {
  237. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  238. } else {
  239. self.eventLoop.execute {
  240. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  241. }
  242. }
  243. }
  244. /// Returns the `Channel` for the HTTP/2 stream that this RPC is using.
  245. internal func streamChannel() -> EventLoopFuture<Channel> {
  246. if self.eventLoop.inEventLoop {
  247. return self.getStreamChannel()
  248. } else {
  249. return self.eventLoop.flatSubmit {
  250. self.getStreamChannel()
  251. }
  252. }
  253. }
  254. }
  255. extension ChannelTransport {
  256. /// Return a future for the stream channel.
  257. ///
  258. /// Must be called from the event loop.
  259. private func getStreamChannel() -> EventLoopFuture<Channel> {
  260. self.eventLoop.preconditionInEventLoop()
  261. switch self.state {
  262. case let .buffering(future):
  263. return future
  264. case let .active(channel):
  265. return self.eventLoop.makeSucceededFuture(channel)
  266. case .closed:
  267. return self.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)
  268. }
  269. }
  270. /// Send many requests.
  271. ///
  272. /// Must be called from the event loop.
  273. private func _sendRequests<S>(
  274. _ parts: S,
  275. promise: EventLoopPromise<Void>?
  276. ) where S: Sequence, S.Element == RequestPart {
  277. self.eventLoop.preconditionInEventLoop()
  278. // We have a promise: create one for each request part and cascade the overall result to it.
  279. // If we're flushing we'll do it at the end.
  280. if let promise = promise {
  281. let loop = promise.futureResult.eventLoop
  282. let futures: [EventLoopFuture<Void>] = parts.map { part in
  283. let partPromise = loop.makePromise(of: Void.self)
  284. self.writePart(part, flush: false, promise: partPromise)
  285. return partPromise.futureResult
  286. }
  287. // Cascade the futures to the provided promise.
  288. EventLoopFuture.andAllSucceed(futures, on: loop).cascade(to: promise)
  289. } else {
  290. for part in parts {
  291. self.writePart(part, flush: false, promise: nil)
  292. }
  293. }
  294. // Now flush.
  295. self.flush()
  296. }
  297. /// Buffer or send a flush.
  298. ///
  299. /// Must be called from the event loop.
  300. private func flush() {
  301. self.eventLoop.preconditionInEventLoop()
  302. switch self.state {
  303. case .buffering:
  304. self.requestBuffer.mark()
  305. case let .active(stream):
  306. stream.flush()
  307. case .closed:
  308. ()
  309. }
  310. }
  311. /// Write a request part.
  312. ///
  313. /// Must be called from the event loop.
  314. ///
  315. /// - Parameters:
  316. /// - part: The part to write.
  317. /// - flush: Whether we should flush the channel after this write.
  318. /// - promise: A promise to fulfill when the part has been written.
  319. private func writePart(_ part: RequestPart, flush: Bool, promise: EventLoopPromise<Void>?) {
  320. self.eventLoop.assertInEventLoop()
  321. switch self.state {
  322. // We're buffering, so buffer the message.
  323. case .buffering:
  324. self.logger.debug("buffering request part", metadata: [
  325. "request_part": "\(part.name)",
  326. "call_state": "\(self.describeCallState())",
  327. ], source: "GRPC")
  328. self.requestBuffer.append(BufferedRequest(message: part, promise: promise))
  329. if flush {
  330. self.requestBuffer.mark()
  331. }
  332. // We have an active stream, just pass the write and promise through.
  333. case let .active(stream):
  334. self.logger.debug(
  335. "writing request part",
  336. metadata: ["request_part": "\(part.name)"],
  337. source: "GRPC"
  338. )
  339. stream.write(part, promise: promise)
  340. if flush {
  341. stream.flush()
  342. }
  343. // We're closed: drop the request.
  344. case .closed:
  345. self.logger.debug("dropping request part", metadata: [
  346. "request_part": "\(part.name)",
  347. "call_state": "\(self.describeCallState())",
  348. ], source: "GRPC")
  349. promise?.fail(ChannelError.ioOnClosedChannel)
  350. }
  351. }
  352. /// The scheduled timeout triggered: timeout the RPC if it's not yet finished.
  353. ///
  354. /// Must be called from the event loop.
  355. private func timedOut(after timeLimit: TimeLimit) {
  356. self.eventLoop.preconditionInEventLoop()
  357. let error = GRPCError.RPCTimedOut(timeLimit).captureContext()
  358. self.handleError(error, promise: nil)
  359. }
  360. /// Handle an error and optionally fail the provided promise with the error.
  361. ///
  362. /// Must be called from the event loop.
  363. private func handleError(_ error: Error, promise: EventLoopPromise<Void>?) {
  364. self.eventLoop.preconditionInEventLoop()
  365. switch self.state {
  366. // We only care about errors if we're not shutdown yet.
  367. case .buffering, .active:
  368. // Add our current state to the logger we provide to the callback.
  369. var loggerWithState = self.logger
  370. loggerWithState[metadataKey: "call_state"] = "\(self.describeCallState())"
  371. let errorStatus: GRPCStatus
  372. let errorWithoutContext: Error
  373. if let errorWithContext = error as? GRPCError.WithContext {
  374. errorStatus = errorWithContext.error.makeGRPCStatus()
  375. errorWithoutContext = errorWithContext.error
  376. self.errorDelegate?.didCatchError(
  377. errorWithContext.error,
  378. logger: loggerWithState,
  379. file: errorWithContext.file,
  380. line: errorWithContext.line
  381. )
  382. } else if let transformable = error as? GRPCStatusTransformable {
  383. errorStatus = transformable.makeGRPCStatus()
  384. errorWithoutContext = error
  385. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  386. } else {
  387. errorStatus = .processingError
  388. errorWithoutContext = error
  389. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  390. }
  391. // Update our state: we're closing.
  392. self.close(error: errorWithoutContext, status: errorStatus)
  393. promise?.fail(errorStatus)
  394. case .closed:
  395. promise?.fail(ChannelError.alreadyClosed)
  396. }
  397. }
  398. /// Close the call, if it's not yet closed with the given status.
  399. ///
  400. /// Must be called from the event loop.
  401. private func close(error: Error, status: GRPCStatus) {
  402. self.eventLoop.preconditionInEventLoop()
  403. switch self.state {
  404. case let .buffering(streamFuture):
  405. // We're closed now.
  406. self.state = .closed
  407. self.stopTimer(status: status)
  408. // We're done; cancel the timeout.
  409. self.scheduledTimeout?.cancel()
  410. self.scheduledTimeout = nil
  411. // Fail any outstanding promises.
  412. self.responseContainer.fail(with: error, status: status)
  413. // Fail any buffered writes.
  414. while !self.requestBuffer.isEmpty {
  415. let write = self.requestBuffer.removeFirst()
  416. write.promise?.fail(status)
  417. }
  418. // Close the channel, if it comes up.
  419. streamFuture.whenSuccess {
  420. $0.close(mode: .all, promise: nil)
  421. }
  422. case let .active(channel):
  423. // We're closed now.
  424. self.state = .closed
  425. self.stopTimer(status: status)
  426. // We're done; cancel the timeout.
  427. self.scheduledTimeout?.cancel()
  428. self.scheduledTimeout = nil
  429. // Fail any outstanding promises.
  430. self.responseContainer.fail(with: error, status: status)
  431. // Close the channel.
  432. channel.close(mode: .all, promise: nil)
  433. case .closed:
  434. ()
  435. }
  436. }
  437. }
  438. // MARK: - Channel Inbound
  439. extension ChannelTransport: ClientCallInbound {
  440. /// Receive an error from the Channel.
  441. ///
  442. /// Must be called on the event loop.
  443. internal func receiveError(_ error: Error) {
  444. self.eventLoop.preconditionInEventLoop()
  445. self.handleError(error, promise: nil)
  446. }
  447. /// Receive a response part from the Channel.
  448. ///
  449. /// Must be called on the event loop.
  450. func receiveResponse(_ part: _GRPCClientResponsePart<Response>) {
  451. self.eventLoop.preconditionInEventLoop()
  452. switch self.state {
  453. case .buffering:
  454. preconditionFailure("Received response part in 'buffering' state")
  455. case .active:
  456. self.logger.debug(
  457. "received response part",
  458. metadata: ["response_part": "\(part.name)"],
  459. source: "GRPC"
  460. )
  461. switch part {
  462. case let .initialMetadata(metadata):
  463. self.responseContainer.lazyInitialMetadataPromise.completeWith(.success(metadata))
  464. case let .message(messageContext):
  465. switch self.responseContainer.responseHandler {
  466. case let .unary(responsePromise):
  467. responsePromise.succeed(messageContext.message)
  468. case let .stream(handler):
  469. handler(messageContext.message)
  470. }
  471. case let .trailingMetadata(metadata):
  472. self.responseContainer.lazyTrailingMetadataPromise.succeed(metadata)
  473. case let .status(status):
  474. // We're done; cancel the timeout.
  475. self.scheduledTimeout?.cancel()
  476. self.scheduledTimeout = nil
  477. // We're closed now.
  478. self.state = .closed
  479. self.stopTimer(status: status)
  480. // We're not really failing the status here; in some cases the server may fast fail, in which
  481. // case we'll only see trailing metadata and status: we should fail the initial metadata and
  482. // response in that case.
  483. self.responseContainer.fail(with: status, status: status)
  484. }
  485. case .closed:
  486. self.logger.debug("dropping response part", metadata: [
  487. "response_part": "\(part.name)",
  488. "call_state": "\(self.describeCallState())",
  489. ], source: "GRPC")
  490. }
  491. }
  492. /// The underlying channel become active and can start accepting writes.
  493. ///
  494. /// Must be called on the event loop.
  495. internal func activate(stream: Channel) {
  496. self.eventLoop.preconditionInEventLoop()
  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. }