2
0

ClientCallTransport.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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: GRPCPayload, Response: GRPCPayload> {
  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(
  130. multiplexer: EventLoopFuture<HTTP2StreamMultiplexer>,
  131. responseContainer: ResponsePartContainer<Response>,
  132. callType: GRPCCallType,
  133. timeLimit: TimeLimit,
  134. errorDelegate: ClientErrorDelegate?,
  135. logger: Logger
  136. ) {
  137. self.init(
  138. eventLoop: multiplexer.eventLoop,
  139. responseContainer: responseContainer,
  140. timeLimit: timeLimit,
  141. errorDelegate: errorDelegate,
  142. logger: logger
  143. ) { call, streamPromise in
  144. multiplexer.whenComplete { result in
  145. switch result {
  146. case .success(let mux):
  147. mux.createStreamChannel(promise: streamPromise) { stream, streamID in
  148. stream.pipeline.addHandlers([
  149. _GRPCClientChannelHandler<Request, Response>(streamID: streamID, callType: callType, logger: logger),
  150. GRPCClientCallHandler(call: call)
  151. ])
  152. }
  153. case .failure(let error):
  154. streamPromise.fail(error)
  155. }
  156. }
  157. }
  158. }
  159. internal convenience init(
  160. fakeResponse: _FakeResponseStream<Request, Response>,
  161. responseContainer: ResponsePartContainer<Response>,
  162. timeLimit: TimeLimit,
  163. logger: Logger
  164. ) {
  165. self.init(
  166. eventLoop: fakeResponse.channel.eventLoop,
  167. responseContainer: responseContainer,
  168. timeLimit: timeLimit,
  169. errorDelegate: nil,
  170. logger: logger
  171. ) { call, streamPromise in
  172. fakeResponse.channel.pipeline.addHandler(GRPCClientCallHandler(call: call)).map {
  173. fakeResponse.channel
  174. }.cascade(to: streamPromise)
  175. }
  176. }
  177. /// Makes a transport whose channel promise is failed immediately.
  178. internal static func makeTransportForMissingFakeResponse(
  179. eventLoop: EventLoop,
  180. responseContainer: ResponsePartContainer<Response>,
  181. logger: Logger
  182. ) -> ChannelTransport<Request, Response> {
  183. return .init(
  184. eventLoop: eventLoop,
  185. responseContainer: responseContainer,
  186. timeLimit: .none,
  187. errorDelegate: nil,
  188. logger: logger
  189. ) { call, promise in
  190. let error = GRPCStatus(
  191. code: .unavailable,
  192. message: "No fake response was registered before starting an RPC."
  193. )
  194. promise.fail(error)
  195. }
  196. }
  197. }
  198. // MARK: - Call API (i.e. called from {Unary,ClientStreaming,...}Call)
  199. extension ChannelTransport: ClientCallOutbound {
  200. /// Send a request part.
  201. ///
  202. /// Does not have to be called from the event loop.
  203. internal func sendRequest(_ part: RequestPart, promise: EventLoopPromise<Void>?) {
  204. if self.eventLoop.inEventLoop {
  205. self.writePart(part, flush: true, promise: promise)
  206. } else {
  207. self.eventLoop.execute {
  208. self.writePart(part, flush: true, promise: promise)
  209. }
  210. }
  211. }
  212. /// Send multiple request parts.
  213. ///
  214. /// Does not have to be called from the event loop.
  215. internal func sendRequests<S>(
  216. _ parts: S,
  217. promise: EventLoopPromise<Void>?
  218. ) where S: Sequence, S.Element == RequestPart {
  219. if self.eventLoop.inEventLoop {
  220. self._sendRequests(parts, promise: promise)
  221. } else {
  222. self.eventLoop.execute {
  223. self._sendRequests(parts, promise: promise)
  224. }
  225. }
  226. }
  227. /// Request that the RPC is cancelled.
  228. ///
  229. /// Does not have to be called from the event loop.
  230. internal func cancel(promise: EventLoopPromise<Void>?) {
  231. self.logger.info("rpc cancellation requested")
  232. if self.eventLoop.inEventLoop {
  233. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  234. } else {
  235. self.eventLoop.execute {
  236. self.handleError(GRPCError.RPCCancelledByClient().captureContext(), promise: promise)
  237. }
  238. }
  239. }
  240. /// Returns the `Channel` for the HTTP/2 stream that this RPC is using.
  241. internal func streamChannel() -> EventLoopFuture<Channel> {
  242. if self.eventLoop.inEventLoop {
  243. return self.getStreamChannel()
  244. } else {
  245. return self.eventLoop.flatSubmit {
  246. self.getStreamChannel()
  247. }
  248. }
  249. }
  250. }
  251. extension ChannelTransport {
  252. /// Return a future for the stream channel.
  253. ///
  254. /// Must be called from the event loop.
  255. private func getStreamChannel() -> EventLoopFuture<Channel> {
  256. self.eventLoop.preconditionInEventLoop()
  257. switch self.state {
  258. case .buffering(let future):
  259. return future
  260. case .active(let channel):
  261. return self.eventLoop.makeSucceededFuture(channel)
  262. case .closed:
  263. return self.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)
  264. }
  265. }
  266. /// Send many requests.
  267. ///
  268. /// Must be called from the event loop.
  269. private func _sendRequests<S>(
  270. _ parts: S,
  271. promise: EventLoopPromise<Void>?
  272. ) where S: Sequence, S.Element == RequestPart {
  273. self.eventLoop.preconditionInEventLoop()
  274. // We have a promise: create one for each request part and cascade the overall result to it.
  275. // If we're flushing we'll do it at the end.
  276. if let promise = promise {
  277. let loop = promise.futureResult.eventLoop
  278. let futures: [EventLoopFuture<Void>] = parts.map { part in
  279. let partPromise = loop.makePromise(of: Void.self)
  280. self.writePart(part, flush: false, promise: partPromise)
  281. return partPromise.futureResult
  282. }
  283. // Cascade the futures to the provided promise.
  284. EventLoopFuture.andAllSucceed(futures, on: loop).cascade(to: promise)
  285. } else {
  286. for part in parts {
  287. self.writePart(part, flush: false, promise: nil)
  288. }
  289. }
  290. // Now flush.
  291. self.flush()
  292. }
  293. /// Buffer or send a flush.
  294. ///
  295. /// Must be called from the event loop.
  296. private func flush() {
  297. self.eventLoop.preconditionInEventLoop()
  298. switch self.state {
  299. case .buffering:
  300. self.requestBuffer.mark()
  301. case .active(let stream):
  302. stream.flush()
  303. case .closed:
  304. ()
  305. }
  306. }
  307. /// Write a request part.
  308. ///
  309. /// Must be called from the event loop.
  310. ///
  311. /// - Parameters:
  312. /// - part: The part to write.
  313. /// - flush: Whether we should flush the channel after this write.
  314. /// - promise: A promise to fulfill when the part has been written.
  315. private func writePart(_ part: RequestPart, flush: Bool, promise: EventLoopPromise<Void>?) {
  316. self.eventLoop.assertInEventLoop()
  317. switch self.state {
  318. // We're buffering, so buffer the message.
  319. case .buffering:
  320. self.logger.debug("buffering request part", metadata: [
  321. "request_part": "\(part.name)",
  322. "call_state": "\(self.describeCallState())"
  323. ])
  324. self.requestBuffer.append(BufferedRequest(message: part, promise: promise))
  325. if flush {
  326. self.requestBuffer.mark()
  327. }
  328. // We have an active stream, just pass the write and promise through.
  329. case .active(let stream):
  330. self.logger.debug("writing request part", metadata: ["request_part": "\(part.name)"])
  331. stream.write(part, promise: promise)
  332. if flush {
  333. stream.flush()
  334. }
  335. // We're closed: drop the request.
  336. case .closed:
  337. self.logger.debug("dropping request part", metadata: [
  338. "request_part": "\(part.name)",
  339. "call_state": "\(self.describeCallState())"
  340. ])
  341. promise?.fail(ChannelError.ioOnClosedChannel)
  342. }
  343. }
  344. /// The scheduled timeout triggered: timeout the RPC if it's not yet finished.
  345. ///
  346. /// Must be called from the event loop.
  347. private func timedOut(after timeLimit: TimeLimit) {
  348. self.eventLoop.preconditionInEventLoop()
  349. let error = GRPCError.RPCTimedOut(timeLimit).captureContext()
  350. self.handleError(error, promise: nil)
  351. }
  352. /// Handle an error and optionally fail the provided promise with the error.
  353. ///
  354. /// Must be called from the event loop.
  355. private func handleError(_ error: Error, promise: EventLoopPromise<Void>?) {
  356. self.eventLoop.preconditionInEventLoop()
  357. switch self.state {
  358. // We only care about errors if we're not shutdown yet.
  359. case .buffering, .active:
  360. // Add our current state to the logger we provide to the callback.
  361. var loggerWithState = self.logger
  362. loggerWithState[metadataKey: "call_state"] = "\(self.describeCallState())"
  363. let errorStatus: GRPCStatus
  364. let errorWithoutContext: Error
  365. if let errorWithContext = error as? GRPCError.WithContext {
  366. errorStatus = errorWithContext.error.makeGRPCStatus()
  367. errorWithoutContext = errorWithContext.error
  368. self.errorDelegate?.didCatchError(
  369. errorWithContext.error,
  370. logger: loggerWithState,
  371. file: errorWithContext.file,
  372. line: errorWithContext.line
  373. )
  374. } else if let transformable = error as? GRPCStatusTransformable {
  375. errorStatus = transformable.makeGRPCStatus()
  376. errorWithoutContext = error
  377. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  378. } else {
  379. errorStatus = .processingError
  380. errorWithoutContext = error
  381. self.errorDelegate?.didCatchErrorWithoutContext(error, logger: loggerWithState)
  382. }
  383. // Update our state: we're closing.
  384. self.close(error: errorWithoutContext, status: errorStatus)
  385. promise?.fail(errorStatus)
  386. case .closed:
  387. promise?.fail(ChannelError.alreadyClosed)
  388. }
  389. }
  390. /// Close the call, if it's not yet closed with the given status.
  391. ///
  392. /// Must be called from the event loop.
  393. private func close(error: Error, status: GRPCStatus) {
  394. self.eventLoop.preconditionInEventLoop()
  395. switch self.state {
  396. case .buffering(let streamFuture):
  397. // We're closed now.
  398. self.state = .closed
  399. self.stopTimer(status: status)
  400. // We're done; cancel the timeout.
  401. self.scheduledTimeout?.cancel()
  402. self.scheduledTimeout = nil
  403. // Fail any outstanding promises.
  404. self.responseContainer.fail(with: error, status: status)
  405. // Fail any buffered writes.
  406. while !self.requestBuffer.isEmpty {
  407. let write = self.requestBuffer.removeFirst()
  408. write.promise?.fail(status)
  409. }
  410. // Close the channel, if it comes up.
  411. streamFuture.whenSuccess {
  412. $0.close(mode: .all, promise: nil)
  413. }
  414. case .active(let channel):
  415. // We're closed now.
  416. self.state = .closed
  417. self.stopTimer(status: status)
  418. // We're done; cancel the timeout.
  419. self.scheduledTimeout?.cancel()
  420. self.scheduledTimeout = nil
  421. // Fail any outstanding promises.
  422. self.responseContainer.fail(with: error, status: status)
  423. // Close the channel.
  424. channel.close(mode: .all, promise: nil)
  425. case .closed:
  426. ()
  427. }
  428. }
  429. }
  430. // MARK: - Channel Inbound
  431. extension ChannelTransport: ClientCallInbound {
  432. /// Receive an error from the Channel.
  433. ///
  434. /// Must be called on the event loop.
  435. internal func receiveError(_ error: Error) {
  436. self.eventLoop.preconditionInEventLoop()
  437. self.handleError(error, promise: nil)
  438. }
  439. /// Receive a response part from the Channel.
  440. ///
  441. /// Must be called on the event loop.
  442. func receiveResponse(_ part: _GRPCClientResponsePart<Response>) {
  443. self.eventLoop.preconditionInEventLoop()
  444. switch self.state {
  445. case .buffering:
  446. preconditionFailure("Received response part in 'buffering' state")
  447. case .active:
  448. self.logger.debug("received response part", metadata: ["response_part": "\(part.name)"])
  449. switch part {
  450. case .initialMetadata(let metadata):
  451. self.responseContainer.lazyInitialMetadataPromise.completeWith(.success(metadata))
  452. case .message(let messageContext):
  453. switch self.responseContainer.responseHandler {
  454. case .unary(let responsePromise):
  455. responsePromise.succeed(messageContext.message)
  456. case .stream(let handler):
  457. handler(messageContext.message)
  458. }
  459. case .trailingMetadata(let metadata):
  460. self.responseContainer.lazyTrailingMetadataPromise.succeed(metadata)
  461. case .status(let status):
  462. // We're done; cancel the timeout.
  463. self.scheduledTimeout?.cancel()
  464. self.scheduledTimeout = nil
  465. // We're closed now.
  466. self.state = .closed
  467. self.stopTimer(status: status)
  468. // We're not really failing the status here; in some cases the server may fast fail, in which
  469. // case we'll only see trailing metadata and status: we should fail the initial metadata and
  470. // response in that case.
  471. self.responseContainer.fail(with: status, status: status)
  472. }
  473. case .closed:
  474. self.logger.debug("dropping response part", metadata: [
  475. "response_part": "\(part.name)",
  476. "call_state": "\(self.describeCallState())"
  477. ])
  478. }
  479. }
  480. /// The underlying channel become active and can start accepting writes.
  481. ///
  482. /// Must be called on the event loop.
  483. internal func activate(stream: Channel) {
  484. self.eventLoop.preconditionInEventLoop()
  485. // The channel has become active: what now?
  486. switch self.state {
  487. case .buffering:
  488. while !self.requestBuffer.isEmpty {
  489. // Are we marked?
  490. let hadMark = self.requestBuffer.hasMark
  491. let request = self.requestBuffer.removeFirst()
  492. // We became unmarked: we need to flush.
  493. let shouldFlush = hadMark && !self.requestBuffer.hasMark
  494. self.logger.debug("unbuffering request part", metadata: ["request_part": "\(request.message.name)"])
  495. stream.write(request.message, promise: request.promise)
  496. if shouldFlush {
  497. stream.flush()
  498. }
  499. }
  500. self.logger.debug("request buffer drained")
  501. self.state = .active(stream)
  502. case .active:
  503. preconditionFailure("Invalid state: stream is already active")
  504. case .closed:
  505. // The channel became active but we're already closed: we must've timed out waiting for the
  506. // channel to activate so close the channel now.
  507. stream.close(mode: .all, promise: nil)
  508. }
  509. }
  510. }
  511. // MARK: Private Helpers
  512. extension ChannelTransport {
  513. private func describeCallState() -> String {
  514. self.eventLoop.preconditionInEventLoop()
  515. switch self.state {
  516. case .buffering:
  517. return "waiting for connection; \(self.requestBuffer.count) request part(s) buffered"
  518. case .active:
  519. return "active"
  520. case .closed:
  521. return "closed"
  522. }
  523. }
  524. private func startTimer() {
  525. assert(self.stopwatch == nil)
  526. self.stopwatch = Stopwatch()
  527. self.logger.debug("starting rpc")
  528. }
  529. private func stopTimer(status: GRPCStatus) {
  530. self.eventLoop.preconditionInEventLoop()
  531. if let stopwatch = self.stopwatch {
  532. let millis = stopwatch.elapsedMillis()
  533. self.logger.debug("rpc call finished", metadata: [
  534. "duration_ms": "\(millis)",
  535. "status_code": "\(status.code.rawValue)",
  536. "status_message": "\(status.message ?? "nil")"
  537. ])
  538. self.stopwatch = nil
  539. }
  540. }
  541. /// Sets a time limit for the RPC.
  542. private func setUpTimeLimit(_ timeLimit: TimeLimit) {
  543. let deadline = timeLimit.makeDeadline()
  544. guard deadline != .distantFuture else {
  545. // This is too distant to worry about.
  546. return
  547. }
  548. let timedOutTask = {
  549. self.timedOut(after: timeLimit)
  550. }
  551. // 'scheduledTimeout' must only be accessed from the event loop.
  552. if self.eventLoop.inEventLoop {
  553. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  554. } else {
  555. self.eventLoop.execute {
  556. self.scheduledTimeout = self.eventLoop.scheduleTask(deadline: deadline, timedOutTask)
  557. }
  558. }
  559. }
  560. }
  561. extension _GRPCClientRequestPart {
  562. fileprivate var name: String {
  563. switch self {
  564. case .head:
  565. return "head"
  566. case .message:
  567. return "message"
  568. case .end:
  569. return "end"
  570. }
  571. }
  572. }
  573. extension _GRPCClientResponsePart {
  574. fileprivate var name: String {
  575. switch self {
  576. case .initialMetadata:
  577. return "initial metadata"
  578. case .message:
  579. return "message"
  580. case .trailingMetadata:
  581. return "trailing metadata"
  582. case .status:
  583. return "status"
  584. }
  585. }
  586. }