ClientCallTransport.swift 21 KB

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