ClientCallTransport.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 NIO
  17. import NIOHTTP2
  18. import NIOHPACK
  19. import Logging
  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>) -> ()
  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 .success(let mux):
  149. mux.createStreamChannel(promise: streamPromise) { stream, streamID in
  150. stream.pipeline.addHandlers([
  151. _GRPCClientChannelHandler(streamID: streamID, callType: callType, logger: logger),
  152. GRPCClientCodecHandler(serializer: serializer, deserializer: deserializer),
  153. GRPCClientCallHandler(call: call)
  154. ])
  155. }
  156. case .failure(let 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. ) { call, 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")
  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 .buffering(let future):
  262. return future
  263. case .active(let 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 .active(let 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. ])
  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 .active(let stream):
  333. self.logger.debug("writing request part", metadata: ["request_part": "\(part.name)"])
  334. stream.write(part, promise: promise)
  335. if flush {
  336. stream.flush()
  337. }
  338. // We're closed: drop the request.
  339. case .closed:
  340. self.logger.debug("dropping request part", metadata: [
  341. "request_part": "\(part.name)",
  342. "call_state": "\(self.describeCallState())"
  343. ])
  344. promise?.fail(ChannelError.ioOnClosedChannel)
  345. }
  346. }
  347. /// The scheduled timeout triggered: timeout the RPC if it's not yet finished.
  348. ///
  349. /// Must be called from the event loop.
  350. private func timedOut(after timeLimit: TimeLimit) {
  351. self.eventLoop.preconditionInEventLoop()
  352. let error = GRPCError.RPCTimedOut(timeLimit).captureContext()
  353. self.handleError(error, promise: nil)
  354. }
  355. /// Handle an error and optionally fail the provided promise with the error.
  356. ///
  357. /// Must be called from the event loop.
  358. private func handleError(_ error: Error, promise: EventLoopPromise<Void>?) {
  359. self.eventLoop.preconditionInEventLoop()
  360. switch self.state {
  361. // We only care about errors if we're not shutdown yet.
  362. case .buffering, .active:
  363. // Add our current state to the logger we provide to the callback.
  364. var loggerWithState = self.logger
  365. loggerWithState[metadataKey: "call_state"] = "\(self.describeCallState())"
  366. let errorStatus: GRPCStatus
  367. let errorWithoutContext: Error
  368. if let errorWithContext = error as? GRPCError.WithContext {
  369. errorStatus = errorWithContext.error.makeGRPCStatus()
  370. errorWithoutContext = errorWithContext.error
  371. self.errorDelegate?.didCatchError(
  372. errorWithContext.error,
  373. logger: loggerWithState,
  374. file: errorWithContext.file,
  375. line: errorWithContext.line
  376. )
  377. } else if let transformable = error as? GRPCStatusTransformable {
  378. errorStatus = transformable.makeGRPCStatus()
  379. errorWithoutContext = error
  380. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  381. } else {
  382. errorStatus = .processingError
  383. errorWithoutContext = error
  384. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  385. }
  386. // Update our state: we're closing.
  387. self.close(error: errorWithoutContext, status: errorStatus)
  388. promise?.fail(errorStatus)
  389. case .closed:
  390. promise?.fail(ChannelError.alreadyClosed)
  391. }
  392. }
  393. /// Close the call, if it's not yet closed with the given status.
  394. ///
  395. /// Must be called from the event loop.
  396. private func close(error: Error, status: GRPCStatus) {
  397. self.eventLoop.preconditionInEventLoop()
  398. switch self.state {
  399. case .buffering(let streamFuture):
  400. // We're closed now.
  401. self.state = .closed
  402. self.stopTimer(status: status)
  403. // We're done; cancel the timeout.
  404. self.scheduledTimeout?.cancel()
  405. self.scheduledTimeout = nil
  406. // Fail any outstanding promises.
  407. self.responseContainer.fail(with: error, status: status)
  408. // Fail any buffered writes.
  409. while !self.requestBuffer.isEmpty {
  410. let write = self.requestBuffer.removeFirst()
  411. write.promise?.fail(status)
  412. }
  413. // Close the channel, if it comes up.
  414. streamFuture.whenSuccess {
  415. $0.close(mode: .all, promise: nil)
  416. }
  417. case .active(let channel):
  418. // We're closed now.
  419. self.state = .closed
  420. self.stopTimer(status: status)
  421. // We're done; cancel the timeout.
  422. self.scheduledTimeout?.cancel()
  423. self.scheduledTimeout = nil
  424. // Fail any outstanding promises.
  425. self.responseContainer.fail(with: error, status: status)
  426. // Close the channel.
  427. channel.close(mode: .all, promise: nil)
  428. case .closed:
  429. ()
  430. }
  431. }
  432. }
  433. // MARK: - Channel Inbound
  434. extension ChannelTransport: ClientCallInbound {
  435. /// Receive an error from the Channel.
  436. ///
  437. /// Must be called on the event loop.
  438. internal func receiveError(_ error: Error) {
  439. self.eventLoop.preconditionInEventLoop()
  440. self.handleError(error, promise: nil)
  441. }
  442. /// Receive a response part from the Channel.
  443. ///
  444. /// Must be called on the event loop.
  445. func receiveResponse(_ part: _GRPCClientResponsePart<Response>) {
  446. self.eventLoop.preconditionInEventLoop()
  447. switch self.state {
  448. case .buffering:
  449. preconditionFailure("Received response part in 'buffering' state")
  450. case .active:
  451. self.logger.debug("received response part", metadata: ["response_part": "\(part.name)"])
  452. switch part {
  453. case .initialMetadata(let metadata):
  454. self.responseContainer.lazyInitialMetadataPromise.completeWith(.success(metadata))
  455. case .message(let messageContext):
  456. switch self.responseContainer.responseHandler {
  457. case .unary(let responsePromise):
  458. responsePromise.succeed(messageContext.message)
  459. case .stream(let handler):
  460. handler(messageContext.message)
  461. }
  462. case .trailingMetadata(let metadata):
  463. self.responseContainer.lazyTrailingMetadataPromise.succeed(metadata)
  464. case .status(let status):
  465. // We're done; cancel the timeout.
  466. self.scheduledTimeout?.cancel()
  467. self.scheduledTimeout = nil
  468. // We're closed now.
  469. self.state = .closed
  470. self.stopTimer(status: status)
  471. // We're not really failing the status here; in some cases the server may fast fail, in which
  472. // case we'll only see trailing metadata and status: we should fail the initial metadata and
  473. // response in that case.
  474. self.responseContainer.fail(with: status, status: status)
  475. }
  476. case .closed:
  477. self.logger.debug("dropping response part", metadata: [
  478. "response_part": "\(part.name)",
  479. "call_state": "\(self.describeCallState())"
  480. ])
  481. }
  482. }
  483. /// The underlying channel become active and can start accepting writes.
  484. ///
  485. /// Must be called on the event loop.
  486. internal func activate(stream: Channel) {
  487. self.eventLoop.preconditionInEventLoop()
  488. // The channel has become active: what now?
  489. switch self.state {
  490. case .buffering:
  491. while !self.requestBuffer.isEmpty {
  492. // Are we marked?
  493. let hadMark = self.requestBuffer.hasMark
  494. let request = self.requestBuffer.removeFirst()
  495. // We became unmarked: we need to flush.
  496. let shouldFlush = hadMark && !self.requestBuffer.hasMark
  497. self.logger.debug("unbuffering request part", metadata: ["request_part": "\(request.message.name)"])
  498. stream.write(request.message, promise: request.promise)
  499. if shouldFlush {
  500. stream.flush()
  501. }
  502. }
  503. self.logger.debug("request buffer drained")
  504. self.state = .active(stream)
  505. case .active:
  506. preconditionFailure("Invalid state: stream is already active")
  507. case .closed:
  508. // The channel became active but we're already closed: we must've timed out waiting for the
  509. // channel to activate so close the channel now.
  510. stream.close(mode: .all, promise: nil)
  511. }
  512. }
  513. }
  514. // MARK: Private Helpers
  515. extension ChannelTransport {
  516. private func describeCallState() -> String {
  517. self.eventLoop.preconditionInEventLoop()
  518. switch self.state {
  519. case .buffering:
  520. return "waiting for connection; \(self.requestBuffer.count) request part(s) buffered"
  521. case .active:
  522. return "active"
  523. case .closed:
  524. return "closed"
  525. }
  526. }
  527. private func startTimer() {
  528. assert(self.stopwatch == nil)
  529. self.stopwatch = Stopwatch()
  530. self.logger.debug("starting rpc")
  531. }
  532. private func stopTimer(status: GRPCStatus) {
  533. self.eventLoop.preconditionInEventLoop()
  534. if let stopwatch = self.stopwatch {
  535. let millis = stopwatch.elapsedMillis()
  536. self.logger.debug("rpc call finished", metadata: [
  537. "duration_ms": "\(millis)",
  538. "status_code": "\(status.code.rawValue)",
  539. "status_message": "\(status.message ?? "nil")"
  540. ])
  541. self.stopwatch = nil
  542. }
  543. }
  544. /// Sets a time limit for the RPC.
  545. private func setUpTimeLimit(_ timeLimit: TimeLimit) {
  546. let deadline = timeLimit.makeDeadline()
  547. guard deadline != .distantFuture else {
  548. // This is too distant to worry about.
  549. return
  550. }
  551. let timedOutTask = {
  552. self.timedOut(after: timeLimit)
  553. }
  554. // 'scheduledTimeout' must only be accessed from the event loop.
  555. if self.eventLoop.inEventLoop {
  556. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  557. } else {
  558. self.eventLoop.execute {
  559. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  560. }
  561. }
  562. }
  563. }
  564. extension _GRPCClientRequestPart {
  565. fileprivate var name: String {
  566. switch self {
  567. case .head:
  568. return "head"
  569. case .message:
  570. return "message"
  571. case .end:
  572. return "end"
  573. }
  574. }
  575. }
  576. extension _GRPCClientResponsePart {
  577. fileprivate var name: String {
  578. switch self {
  579. case .initialMetadata:
  580. return "initial metadata"
  581. case .message:
  582. return "message"
  583. case .trailingMetadata:
  584. return "trailing metadata"
  585. case .status:
  586. return "status"
  587. }
  588. }
  589. }