ClientCallTransport.swift 22 KB

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