ClientTransport.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Logging
  17. import NIOCore
  18. import NIOHPACK
  19. import NIOHTTP2
  20. /// This class is the glue between a `NIO.Channel` and the `ClientInterceptorPipeline`. In fact
  21. /// this object owns the interceptor pipeline and is also a `ChannelHandler`. The caller has very
  22. /// little API to use on this class: they may configure the transport by adding it to a
  23. /// `NIO.ChannelPipeline` with `configure(_:)`, send request parts via `send(_:promise:)` and
  24. /// attempt to cancel the RPC with `cancel(promise:)`. Response parts – after traversing the
  25. /// interceptor pipeline – are emitted to the `onResponsePart` callback supplied to the initializer.
  26. ///
  27. /// In most instances the glue code is simple: transformations are applied to the request and
  28. /// response types used by the interceptor pipeline and the `NIO.Channel`. In addition, the
  29. /// transport keeps track of the state of the call and the `Channel`, taking appropriate action
  30. /// when these change. This includes buffering request parts from the interceptor pipeline until
  31. /// the `NIO.Channel` becomes active.
  32. ///
  33. /// ### Thread Safety
  34. ///
  35. /// This class is not thread safe. All methods **must** be executed on the transport's `callEventLoop`.
  36. @usableFromInline
  37. internal final class ClientTransport<Request, Response> {
  38. /// The `EventLoop` the call is running on. State must be accessed from this event loop.
  39. @usableFromInline
  40. internal let callEventLoop: EventLoop
  41. /// The current state of the transport.
  42. private var state: ClientTransportState = .idle
  43. /// A promise for the underlying `Channel`. We'll succeed this when we transition to `active`
  44. /// and fail it when we transition to `closed`.
  45. private var channelPromise: EventLoopPromise<Channel>?
  46. // Note: initial capacity is 4 because it's a power of 2 and most calls are unary so will
  47. // have 3 parts.
  48. /// A buffer to store request parts and promises in before the channel has become active.
  49. private var writeBuffer = MarkedCircularBuffer<RequestAndPromise>(initialCapacity: 4)
  50. /// The request serializer.
  51. private let serializer: AnySerializer<Request>
  52. /// The response deserializer.
  53. private let deserializer: AnyDeserializer<Response>
  54. /// A request part and a promise.
  55. private struct RequestAndPromise {
  56. var request: GRPCClientRequestPart<Request>
  57. var promise: EventLoopPromise<Void>?
  58. }
  59. /// Details about the call.
  60. internal let callDetails: CallDetails
  61. /// A logger.
  62. internal var logger: GRPCLogger
  63. /// Is the call streaming requests?
  64. private var isStreamingRequests: Bool {
  65. switch self.callDetails.type {
  66. case .unary, .serverStreaming:
  67. return false
  68. case .clientStreaming, .bidirectionalStreaming:
  69. return true
  70. }
  71. }
  72. // Our `NIO.Channel` will fire trailers and the `GRPCStatus` to us separately. It's more
  73. // convenient to have both at the same time when intercepting response parts. We'll hold on to the
  74. // trailers here and only forward them when we receive the status.
  75. private var trailers: HPACKHeaders?
  76. /// The interceptor pipeline connected to this transport. The pipeline also holds references
  77. /// to `self` which are dropped when the interceptor pipeline is closed.
  78. @usableFromInline
  79. internal var _pipeline: ClientInterceptorPipeline<Request, Response>?
  80. /// The `NIO.Channel` used by the transport, if it is available.
  81. private var channel: Channel?
  82. /// A callback which is invoked once when the stream channel becomes active.
  83. private var onStart: (() -> Void)?
  84. /// Our current state as logging metadata.
  85. private var stateForLogging: Logger.MetadataValue {
  86. if self.state.mayBuffer {
  87. return "\(self.state) (\(self.writeBuffer.count) parts buffered)"
  88. } else {
  89. return "\(self.state)"
  90. }
  91. }
  92. internal init(
  93. details: CallDetails,
  94. eventLoop: EventLoop,
  95. interceptors: [ClientInterceptor<Request, Response>],
  96. serializer: AnySerializer<Request>,
  97. deserializer: AnyDeserializer<Response>,
  98. errorDelegate: ClientErrorDelegate?,
  99. onStart: @escaping () -> Void,
  100. onError: @escaping (Error) -> Void,
  101. onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
  102. ) {
  103. self.callEventLoop = eventLoop
  104. self.callDetails = details
  105. self.onStart = onStart
  106. let logger = GRPCLogger(wrapping: details.options.logger)
  107. self.logger = logger
  108. self.serializer = serializer
  109. self.deserializer = deserializer
  110. // The references to self held by the pipeline are dropped when it is closed.
  111. self._pipeline = ClientInterceptorPipeline(
  112. eventLoop: eventLoop,
  113. details: details,
  114. logger: logger,
  115. interceptors: interceptors,
  116. errorDelegate: errorDelegate,
  117. onError: onError,
  118. onCancel: self.cancelFromPipeline(promise:),
  119. onRequestPart: self.sendFromPipeline(_:promise:),
  120. onResponsePart: onResponsePart
  121. )
  122. }
  123. // MARK: - Call Object API
  124. /// Configure the transport to communicate with the server.
  125. /// - Parameter configurator: A callback to invoke in order to configure this transport.
  126. /// - Important: This *must* to be called from the `callEventLoop`.
  127. internal func configure(_ configurator: @escaping (ChannelHandler) -> EventLoopFuture<Void>) {
  128. self.callEventLoop.assertInEventLoop()
  129. if self.state.configureTransport() {
  130. self.configure(using: configurator)
  131. }
  132. }
  133. /// Send a request part – via the interceptor pipeline – to the server.
  134. /// - Parameters:
  135. /// - part: The part to send.
  136. /// - promise: A promise which will be completed when the request part has been handled.
  137. /// - Important: This *must* to be called from the `callEventLoop`.
  138. @inlinable
  139. internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  140. self.callEventLoop.assertInEventLoop()
  141. if let pipeline = self._pipeline {
  142. pipeline.send(part, promise: promise)
  143. } else {
  144. promise?.fail(GRPCError.AlreadyComplete())
  145. }
  146. }
  147. /// Attempt to cancel the RPC notifying any interceptors.
  148. /// - Parameter promise: A promise which will be completed when the cancellation attempt has
  149. /// been handled.
  150. internal func cancel(promise: EventLoopPromise<Void>?) {
  151. self.callEventLoop.assertInEventLoop()
  152. if let pipeline = self._pipeline {
  153. pipeline.cancel(promise: promise)
  154. } else {
  155. promise?.fail(GRPCError.AlreadyComplete())
  156. }
  157. }
  158. /// A request for the underlying `Channel`.
  159. internal func getChannel() -> EventLoopFuture<Channel> {
  160. self.callEventLoop.assertInEventLoop()
  161. // Do we already have a promise?
  162. if let promise = self.channelPromise {
  163. return promise.futureResult
  164. } else {
  165. // Make and store the promise.
  166. let promise = self.callEventLoop.makePromise(of: Channel.self)
  167. self.channelPromise = promise
  168. // Ask the state machine if we can have it.
  169. switch self.state.getChannel() {
  170. case .succeed:
  171. if let channel = self.channel {
  172. promise.succeed(channel)
  173. }
  174. case .fail:
  175. promise.fail(GRPCError.AlreadyComplete())
  176. case .doNothing:
  177. ()
  178. }
  179. return promise.futureResult
  180. }
  181. }
  182. }
  183. // MARK: - Pipeline API
  184. extension ClientTransport {
  185. /// Sends a request part on the transport. Should only be called from the interceptor pipeline.
  186. /// - Parameters:
  187. /// - part: The request part to send.
  188. /// - promise: A promise which will be completed when the part has been handled.
  189. /// - Important: This *must* to be called from the `callEventLoop`.
  190. private func sendFromPipeline(
  191. _ part: GRPCClientRequestPart<Request>,
  192. promise: EventLoopPromise<Void>?
  193. ) {
  194. self.callEventLoop.assertInEventLoop()
  195. switch self.state.send() {
  196. case .writeToBuffer:
  197. self.buffer(part, promise: promise)
  198. case .writeToChannel:
  199. // Banging the channel is okay here: we'll only be told to 'writeToChannel' if we're in the
  200. // correct state, the requirements of that state are having an active `Channel`.
  201. self.writeToChannel(
  202. self.channel!,
  203. part: part,
  204. promise: promise,
  205. flush: self.shouldFlush(after: part)
  206. )
  207. case .alreadyComplete:
  208. promise?.fail(GRPCError.AlreadyComplete())
  209. }
  210. }
  211. /// Attempt to cancel the RPC. Should only be called from the interceptor pipeline.
  212. /// - Parameter promise: A promise which will be completed when the cancellation has been handled.
  213. /// - Important: This *must* to be called from the `callEventLoop`.
  214. private func cancelFromPipeline(promise: EventLoopPromise<Void>?) {
  215. self.callEventLoop.assertInEventLoop()
  216. if self.state.cancel() {
  217. let error = GRPCError.RPCCancelledByClient()
  218. let status = error.makeGRPCStatus()
  219. self.forwardToInterceptors(.end(status, [:]))
  220. self.failBufferedWrites(with: error)
  221. self.channel?.close(mode: .all, promise: nil)
  222. self.channelPromise?.fail(error)
  223. promise?.succeed(())
  224. } else {
  225. promise?.succeed(())
  226. }
  227. }
  228. }
  229. // MARK: - ChannelHandler API
  230. extension ClientTransport: ChannelInboundHandler {
  231. @usableFromInline
  232. typealias InboundIn = _RawGRPCClientResponsePart
  233. @usableFromInline
  234. typealias OutboundOut = _RawGRPCClientRequestPart
  235. @usableFromInline
  236. internal func handlerRemoved(context: ChannelHandlerContext) {
  237. self.dropReferences()
  238. }
  239. @usableFromInline
  240. internal func handlerAdded(context: ChannelHandlerContext) {
  241. if context.channel.isActive {
  242. self.transportActivated(channel: context.channel)
  243. }
  244. }
  245. @usableFromInline
  246. internal func errorCaught(context: ChannelHandlerContext, error: Error) {
  247. self.handleError(error)
  248. }
  249. @usableFromInline
  250. internal func channelActive(context: ChannelHandlerContext) {
  251. self.transportActivated(channel: context.channel)
  252. }
  253. @usableFromInline
  254. internal func channelInactive(context: ChannelHandlerContext) {
  255. self.transportDeactivated()
  256. }
  257. @usableFromInline
  258. internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  259. switch self.unwrapInboundIn(data) {
  260. case let .initialMetadata(headers):
  261. self.receiveFromChannel(initialMetadata: headers)
  262. case let .message(box):
  263. self.receiveFromChannel(message: box.message)
  264. case let .trailingMetadata(trailers):
  265. self.receiveFromChannel(trailingMetadata: trailers)
  266. case let .status(status):
  267. self.receiveFromChannel(status: status)
  268. }
  269. // (We're the end of the channel. No need to forward anything.)
  270. }
  271. }
  272. extension ClientTransport {
  273. /// The `Channel` became active. Send out any buffered requests.
  274. private func transportActivated(channel: Channel) {
  275. if self.callEventLoop.inEventLoop {
  276. self._transportActivated(channel: channel)
  277. } else {
  278. self.callEventLoop.execute {
  279. self._transportActivated(channel: channel)
  280. }
  281. }
  282. }
  283. /// On-loop implementation of `transportActivated(channel:)`.
  284. private func _transportActivated(channel: Channel) {
  285. self.callEventLoop.assertInEventLoop()
  286. switch self.state.activate() {
  287. case .unbuffer:
  288. self.logger.addIPAddressMetadata(local: channel.localAddress, remote: channel.remoteAddress)
  289. self._pipeline?.logger = self.logger
  290. self.logger.debug("activated stream channel")
  291. self.channel = channel
  292. self.unbuffer()
  293. case .close:
  294. channel.close(mode: .all, promise: nil)
  295. case .doNothing:
  296. ()
  297. }
  298. }
  299. /// The `Channel` became inactive. Fail any buffered writes and forward an error to the
  300. /// interceptor pipeline if necessary.
  301. private func transportDeactivated() {
  302. if self.callEventLoop.inEventLoop {
  303. self._transportDeactivated()
  304. } else {
  305. self.callEventLoop.execute {
  306. self._transportDeactivated()
  307. }
  308. }
  309. }
  310. /// On-loop implementation of `transportDeactivated()`.
  311. private func _transportDeactivated() {
  312. self.callEventLoop.assertInEventLoop()
  313. switch self.state.deactivate() {
  314. case .doNothing:
  315. ()
  316. case .tearDown:
  317. let status = GRPCStatus(code: .unavailable, message: "Transport became inactive")
  318. self.forwardErrorToInterceptors(status)
  319. self.failBufferedWrites(with: status)
  320. self.channelPromise?.fail(status)
  321. case .failChannelPromise:
  322. self.channelPromise?.fail(GRPCError.AlreadyComplete())
  323. }
  324. }
  325. /// Drops any references to the `Channel` and interceptor pipeline.
  326. private func dropReferences() {
  327. if self.callEventLoop.inEventLoop {
  328. self.channel = nil
  329. } else {
  330. self.callEventLoop.execute {
  331. self.channel = nil
  332. }
  333. }
  334. }
  335. /// Handles an error caught in the pipeline or from elsewhere. The error may be forwarded to the
  336. /// interceptor pipeline and any buffered writes will be failed. Any underlying `Channel` will
  337. /// also be closed.
  338. internal func handleError(_ error: Error) {
  339. if self.callEventLoop.inEventLoop {
  340. self._handleError(error)
  341. } else {
  342. self.callEventLoop.execute {
  343. self._handleError(error)
  344. }
  345. }
  346. }
  347. /// On-loop implementation of `handleError(_:)`.
  348. private func _handleError(_ error: Error) {
  349. self.callEventLoop.assertInEventLoop()
  350. switch self.state.handleError() {
  351. case .doNothing:
  352. ()
  353. case .propagateError:
  354. self.forwardErrorToInterceptors(error)
  355. self.failBufferedWrites(with: error)
  356. case .propagateErrorAndClose:
  357. self.forwardErrorToInterceptors(error)
  358. self.failBufferedWrites(with: error)
  359. self.channel?.close(mode: .all, promise: nil)
  360. }
  361. }
  362. /// Receive initial metadata from the `Channel`.
  363. private func receiveFromChannel(initialMetadata headers: HPACKHeaders) {
  364. if self.callEventLoop.inEventLoop {
  365. self._receiveFromChannel(initialMetadata: headers)
  366. } else {
  367. self.callEventLoop.execute {
  368. self._receiveFromChannel(initialMetadata: headers)
  369. }
  370. }
  371. }
  372. /// On-loop implementation of `receiveFromChannel(initialMetadata:)`.
  373. private func _receiveFromChannel(initialMetadata headers: HPACKHeaders) {
  374. self.callEventLoop.assertInEventLoop()
  375. if self.state.channelRead(isEnd: false) {
  376. self.forwardToInterceptors(.metadata(headers))
  377. }
  378. }
  379. /// Receive response message bytes from the `Channel`.
  380. private func receiveFromChannel(message buffer: ByteBuffer) {
  381. if self.callEventLoop.inEventLoop {
  382. self._receiveFromChannel(message: buffer)
  383. } else {
  384. self.callEventLoop.execute {
  385. self._receiveFromChannel(message: buffer)
  386. }
  387. }
  388. }
  389. /// On-loop implementation of `receiveFromChannel(message:)`.
  390. private func _receiveFromChannel(message buffer: ByteBuffer) {
  391. self.callEventLoop.assertInEventLoop()
  392. do {
  393. let message = try self.deserializer.deserialize(byteBuffer: buffer)
  394. if self.state.channelRead(isEnd: false) {
  395. self.forwardToInterceptors(.message(message))
  396. }
  397. } catch {
  398. self.handleError(error)
  399. }
  400. }
  401. /// Receive trailing metadata from the `Channel`.
  402. private func receiveFromChannel(trailingMetadata trailers: HPACKHeaders) {
  403. // The `Channel` delivers trailers and `GRPCStatus` separately, we want to emit them together
  404. // in the interceptor pipeline.
  405. if self.callEventLoop.inEventLoop {
  406. self.trailers = trailers
  407. } else {
  408. self.callEventLoop.execute {
  409. self.trailers = trailers
  410. }
  411. }
  412. }
  413. /// Receive the final status from the `Channel`.
  414. private func receiveFromChannel(status: GRPCStatus) {
  415. if self.callEventLoop.inEventLoop {
  416. self._receiveFromChannel(status: status)
  417. } else {
  418. self.callEventLoop.execute {
  419. self._receiveFromChannel(status: status)
  420. }
  421. }
  422. }
  423. /// On-loop implementation of `receiveFromChannel(status:)`.
  424. private func _receiveFromChannel(status: GRPCStatus) {
  425. self.callEventLoop.assertInEventLoop()
  426. if self.state.channelRead(isEnd: true) {
  427. self.forwardToInterceptors(.end(status, self.trailers ?? [:]))
  428. self.trailers = nil
  429. }
  430. }
  431. }
  432. // MARK: - State Handling
  433. private enum ClientTransportState {
  434. /// Idle. We're waiting for the RPC to be configured.
  435. ///
  436. /// Valid transitions:
  437. /// - `awaitingTransport` (the transport is being configured)
  438. /// - `closed` (the RPC cancels)
  439. case idle
  440. /// Awaiting transport. The RPC has requested transport and we're waiting for that transport to
  441. /// activate. We'll buffer any outbound messages from this state. Receiving messages from the
  442. /// transport in this state is an error.
  443. ///
  444. /// Valid transitions:
  445. /// - `activatingTransport` (the channel becomes active)
  446. /// - `closing` (the RPC cancels)
  447. /// - `closed` (the channel fails to become active)
  448. case awaitingTransport
  449. /// The transport is active but we're unbuffering any requests to write on that transport.
  450. /// We'll continue buffering in this state. Receiving messages from the transport in this state
  451. /// is okay.
  452. ///
  453. /// Valid transitions:
  454. /// - `active` (we finish unbuffering)
  455. /// - `closing` (the RPC cancels, the channel encounters an error)
  456. /// - `closed` (the channel becomes inactive)
  457. case activatingTransport
  458. /// Fully active. An RPC is in progress and is communicating over an active transport.
  459. ///
  460. /// Valid transitions:
  461. /// - `closing` (the RPC cancels, the channel encounters an error)
  462. /// - `closed` (the channel becomes inactive)
  463. case active
  464. /// Closing. Either the RPC was cancelled or any `Channel` associated with the transport hasn't
  465. /// become inactive yet.
  466. ///
  467. /// Valid transitions:
  468. /// - `closed` (the channel becomes inactive)
  469. case closing
  470. /// We're closed. Any writes from the RPC will be failed. Any responses from the transport will
  471. /// be ignored.
  472. ///
  473. /// Valid transitions:
  474. /// - none: this state is terminal.
  475. case closed
  476. /// Whether writes may be unbuffered in this state.
  477. internal var isUnbuffering: Bool {
  478. switch self {
  479. case .activatingTransport:
  480. return true
  481. case .idle, .awaitingTransport, .active, .closing, .closed:
  482. return false
  483. }
  484. }
  485. /// Whether this state allows writes to be buffered. (This is useful only to inform logging.)
  486. internal var mayBuffer: Bool {
  487. switch self {
  488. case .idle, .activatingTransport, .awaitingTransport:
  489. return true
  490. case .active, .closing, .closed:
  491. return false
  492. }
  493. }
  494. }
  495. extension ClientTransportState {
  496. /// The caller would like to configure the transport. Returns a boolean indicating whether we
  497. /// should configure it or not.
  498. mutating func configureTransport() -> Bool {
  499. switch self {
  500. // We're idle until we configure. Anything else is just a repeat request to configure.
  501. case .idle:
  502. self = .awaitingTransport
  503. return true
  504. case .awaitingTransport, .activatingTransport, .active, .closing, .closed:
  505. return false
  506. }
  507. }
  508. enum SendAction {
  509. /// Write the request into the buffer.
  510. case writeToBuffer
  511. /// Write the request into the channel.
  512. case writeToChannel
  513. /// The RPC has already completed, fail any promise associated with the write.
  514. case alreadyComplete
  515. }
  516. /// The pipeline would like to send a request part to the transport.
  517. mutating func send() -> SendAction {
  518. switch self {
  519. // We don't have any transport yet, just buffer the part.
  520. case .idle, .awaitingTransport, .activatingTransport:
  521. return .writeToBuffer
  522. // We have a `Channel`, we can pipe the write straight through.
  523. case .active:
  524. return .writeToChannel
  525. // The transport is going or has gone away. Fail the promise.
  526. case .closing, .closed:
  527. return .alreadyComplete
  528. }
  529. }
  530. enum UnbufferedAction {
  531. /// Nothing needs to be done.
  532. case doNothing
  533. /// Succeed the channel promise associated with the transport.
  534. case succeedChannelPromise
  535. }
  536. /// We finished dealing with the buffered writes.
  537. mutating func unbuffered() -> UnbufferedAction {
  538. switch self {
  539. // These can't happen since we only begin unbuffering when we transition to
  540. // '.activatingTransport', which must come after these two states..
  541. case .idle, .awaitingTransport:
  542. preconditionFailure("Requests can't be unbuffered before the transport is activated")
  543. // We dealt with any buffered writes. We can become active now. This is the only way to become
  544. // active.
  545. case .activatingTransport:
  546. self = .active
  547. return .succeedChannelPromise
  548. case .active:
  549. preconditionFailure("Unbuffering completed but the transport is already active")
  550. // Something caused us to close while unbuffering, that's okay, we won't take any further
  551. // action.
  552. case .closing, .closed:
  553. return .doNothing
  554. }
  555. }
  556. /// Cancel the RPC and associated `Channel`, if possible. Returns a boolean indicated whether
  557. /// cancellation can go ahead (and also whether the channel should be torn down).
  558. mutating func cancel() -> Bool {
  559. switch self {
  560. case .idle:
  561. // No RPC has been started and we don't have a `Channel`. We need to tell the interceptor
  562. // we're done, fail any writes, and then deal with the cancellation promise.
  563. self = .closed
  564. return true
  565. case .awaitingTransport:
  566. // An RPC has started and we're waiting for the `Channel` to activate. We'll mark ourselves as
  567. // closing. We don't need to explicitly close the `Channel`, this will happen as a result of
  568. // the `Channel` becoming active (see `channelActive(context:)`).
  569. self = .closing
  570. return true
  571. case .activatingTransport:
  572. // The RPC has started, the `Channel` is active and we're emptying our write buffer. We'll
  573. // mark ourselves as closing: we'll error the interceptor pipeline, close the channel, fail
  574. // any buffered writes and then complete the cancellation promise.
  575. self = .closing
  576. return true
  577. case .active:
  578. // The RPC and channel are up and running. We'll fail the RPC and close the channel.
  579. self = .closing
  580. return true
  581. case .closing, .closed:
  582. // We're already closing or closing. The cancellation is too late.
  583. return false
  584. }
  585. }
  586. enum ActivateAction {
  587. case unbuffer
  588. case close
  589. case doNothing
  590. }
  591. /// `channelActive` was invoked on the transport by the `Channel`.
  592. mutating func activate() -> ActivateAction {
  593. // The channel has become active: what now?
  594. switch self {
  595. case .idle:
  596. preconditionFailure("Can't activate an idle transport")
  597. case .awaitingTransport:
  598. self = .activatingTransport
  599. return .unbuffer
  600. case .activatingTransport, .active:
  601. // Already activated.
  602. return .doNothing
  603. case .closing:
  604. // We remain in closing: we only transition to closed on 'channelInactive'.
  605. return .close
  606. case .closed:
  607. preconditionFailure("Invalid state: stream is already inactive")
  608. }
  609. }
  610. enum ChannelInactiveAction {
  611. /// Tear down the transport; forward an error to the interceptors and fail any buffered writes.
  612. case tearDown
  613. /// Fail the 'Channel' promise, if one exists; the RPC is already complete.
  614. case failChannelPromise
  615. /// Do nothing.
  616. case doNothing
  617. }
  618. /// `channelInactive` was invoked on the transport by the `Channel`.
  619. mutating func deactivate() -> ChannelInactiveAction {
  620. switch self {
  621. case .idle:
  622. // We can't become inactive before we've requested a `Channel`.
  623. preconditionFailure("Can't deactivate an idle transport")
  624. case .awaitingTransport, .activatingTransport, .active:
  625. // We're activating the transport - i.e. offloading any buffered requests - and the channel
  626. // became inactive. We haven't received an error (otherwise we'd be `closing`) so we should
  627. // synthesize an error status to fail the RPC with.
  628. self = .closed
  629. return .tearDown
  630. case .closing:
  631. // We were already closing, now we're fully closed.
  632. self = .closed
  633. return .failChannelPromise
  634. case .closed:
  635. // We're already closed.
  636. return .doNothing
  637. }
  638. }
  639. /// `channelRead` was invoked on the transport by the `Channel`. Returns a boolean value
  640. /// indicating whether the part that was read should be forwarded to the interceptor pipeline.
  641. mutating func channelRead(isEnd: Bool) -> Bool {
  642. switch self {
  643. case .idle, .awaitingTransport:
  644. // If there's no `Channel` or the `Channel` isn't active, then we can't read anything.
  645. preconditionFailure("Can't receive response part on idle transport")
  646. case .activatingTransport, .active:
  647. // We have an active `Channel`, we can forward the request part but we may need to start
  648. // closing if we see the status, since it indicates the call is terminating.
  649. if isEnd {
  650. self = .closing
  651. }
  652. return true
  653. case .closing, .closed:
  654. // We closed early, ignore any reads.
  655. return false
  656. }
  657. }
  658. enum HandleErrorAction {
  659. /// Propagate the error to the interceptor pipeline and fail any buffered writes.
  660. case propagateError
  661. /// As above, but close the 'Channel' as well.
  662. case propagateErrorAndClose
  663. /// No action is required.
  664. case doNothing
  665. }
  666. /// An error was caught.
  667. mutating func handleError() -> HandleErrorAction {
  668. switch self {
  669. case .idle:
  670. // The `Channel` can't error if it doesn't exist.
  671. preconditionFailure("Can't catch error on idle transport")
  672. case .awaitingTransport:
  673. // We're waiting for the `Channel` to become active. We're toast now, so close, failing any
  674. // buffered writes along the way.
  675. self = .closing
  676. return .propagateError
  677. case .activatingTransport,
  678. .active:
  679. // We're either fully active or unbuffering. Forward an error, fail any writes and then close.
  680. self = .closing
  681. return .propagateErrorAndClose
  682. case .closing, .closed:
  683. // We're already closing/closed, we can ignore this.
  684. return .doNothing
  685. }
  686. }
  687. enum GetChannelAction {
  688. /// No action is required.
  689. case doNothing
  690. /// Succeed the Channel promise.
  691. case succeed
  692. /// Fail the 'Channel' promise, the RPC is already complete.
  693. case fail
  694. }
  695. /// The caller has asked for the underlying `Channel`.
  696. mutating func getChannel() -> GetChannelAction {
  697. switch self {
  698. case .idle, .awaitingTransport, .activatingTransport:
  699. // Do nothing, we'll complete the promise when we become active or closed.
  700. return .doNothing
  701. case .active:
  702. // We're already active, so there was no promise to succeed when we made this transition. We
  703. // can complete it now.
  704. return .succeed
  705. case .closing:
  706. // We'll complete the promise when we transition to closed.
  707. return .doNothing
  708. case .closed:
  709. // We're already closed; there was no promise to fail when we made this transition. We can go
  710. // ahead and fail it now though.
  711. return .fail
  712. }
  713. }
  714. }
  715. // MARK: - State Actions
  716. extension ClientTransport {
  717. /// Configures this transport with the `configurator`.
  718. private func configure(using configurator: (ChannelHandler) -> EventLoopFuture<Void>) {
  719. configurator(self).whenFailure { error in
  720. // We might be on a different EL, but `handleError` will sort that out for us, so no need to
  721. // hop.
  722. if error is GRPCStatus || error is GRPCStatusTransformable {
  723. self.handleError(error)
  724. } else {
  725. // Fallback to something which will mark the RPC as 'unavailable'.
  726. self.handleError(ConnectionFailure(reason: error))
  727. }
  728. }
  729. }
  730. /// Append a request part to the write buffer.
  731. /// - Parameters:
  732. /// - part: The request part to buffer.
  733. /// - promise: A promise to complete when the request part has been sent.
  734. private func buffer(
  735. _ part: GRPCClientRequestPart<Request>,
  736. promise: EventLoopPromise<Void>?
  737. ) {
  738. self.callEventLoop.assertInEventLoop()
  739. self.logger.trace(
  740. "buffering request part",
  741. metadata: [
  742. "request_part": "\(part.name)",
  743. "call_state": self.stateForLogging,
  744. ]
  745. )
  746. self.writeBuffer.append(.init(request: part, promise: promise))
  747. }
  748. /// Writes any buffered request parts to the `Channel`.
  749. private func unbuffer() {
  750. self.callEventLoop.assertInEventLoop()
  751. guard let channel = self.channel else {
  752. return
  753. }
  754. // Save any flushing until we're done writing.
  755. var shouldFlush = false
  756. self.logger.trace(
  757. "unbuffering request parts",
  758. metadata: [
  759. "request_parts": "\(self.writeBuffer.count)"
  760. ]
  761. )
  762. // Why the double loop? A promise completed as a result of the flush may enqueue more writes,
  763. // or causes us to change state (i.e. we may have to close). If we didn't loop around then we
  764. // may miss more buffered writes.
  765. while self.state.isUnbuffering, !self.writeBuffer.isEmpty {
  766. // Pull out as many writes as possible.
  767. while let write = self.writeBuffer.popFirst() {
  768. self.logger.trace(
  769. "unbuffering request part",
  770. metadata: [
  771. "request_part": "\(write.request.name)"
  772. ]
  773. )
  774. if !shouldFlush {
  775. shouldFlush = self.shouldFlush(after: write.request)
  776. }
  777. self.writeToChannel(channel, part: write.request, promise: write.promise, flush: false)
  778. }
  779. // Okay, flush now.
  780. if shouldFlush {
  781. shouldFlush = false
  782. channel.flush()
  783. }
  784. }
  785. if self.writeBuffer.isEmpty {
  786. self.logger.trace("request buffer drained")
  787. } else {
  788. self.logger.notice("unbuffering aborted", metadata: ["call_state": self.stateForLogging])
  789. }
  790. // We're unbuffered. What now?
  791. switch self.state.unbuffered() {
  792. case .doNothing:
  793. ()
  794. case .succeedChannelPromise:
  795. self.channelPromise?.succeed(channel)
  796. }
  797. }
  798. /// Fails any promises that come with buffered writes with `error`.
  799. /// - Parameter error: The `Error` to fail promises with.
  800. private func failBufferedWrites(with error: Error) {
  801. self.logger.trace("failing buffered writes", metadata: ["call_state": self.stateForLogging])
  802. while let write = self.writeBuffer.popFirst() {
  803. write.promise?.fail(error)
  804. }
  805. }
  806. /// Write a request part to the `Channel`.
  807. /// - Parameters:
  808. /// - channel: The `Channel` to write `part` to.
  809. /// - part: The request part to write.
  810. /// - promise: A promise to complete once the write has been completed.
  811. /// - flush: Whether to flush the `Channel` after writing.
  812. private func writeToChannel(
  813. _ channel: Channel,
  814. part: GRPCClientRequestPart<Request>,
  815. promise: EventLoopPromise<Void>?,
  816. flush: Bool
  817. ) {
  818. switch part {
  819. case let .metadata(headers):
  820. let head = self.makeRequestHead(with: headers)
  821. channel.write(self.wrapOutboundOut(.head(head)), promise: promise)
  822. // Messages are buffered by this class and in the async writer for async calls. Initially the
  823. // async writer is not allowed to emit messages; the call to 'onStart()' signals that messages
  824. // may be emitted. We call it here to avoid races between writing headers and messages.
  825. self.onStart?()
  826. self.onStart = nil
  827. case let .message(request, metadata):
  828. do {
  829. let bytes = try self.serializer.serialize(request, allocator: channel.allocator)
  830. let message = _MessageContext<ByteBuffer>(bytes, compressed: metadata.compress)
  831. channel.write(self.wrapOutboundOut(.message(message)), promise: promise)
  832. } catch {
  833. self.handleError(error)
  834. }
  835. case .end:
  836. channel.write(self.wrapOutboundOut(.end), promise: promise)
  837. }
  838. if flush {
  839. channel.flush()
  840. }
  841. }
  842. /// Forward the response part to the interceptor pipeline.
  843. /// - Parameter part: The response part to forward.
  844. private func forwardToInterceptors(_ part: GRPCClientResponsePart<Response>) {
  845. self.callEventLoop.assertInEventLoop()
  846. self._pipeline?.receive(part)
  847. }
  848. /// Forward the error to the interceptor pipeline.
  849. /// - Parameter error: The error to forward.
  850. private func forwardErrorToInterceptors(_ error: Error) {
  851. self.callEventLoop.assertInEventLoop()
  852. self._pipeline?.errorCaught(error)
  853. }
  854. }
  855. // MARK: - Helpers
  856. extension ClientTransport {
  857. /// Returns whether the `Channel` should be flushed after writing the given part to it.
  858. private func shouldFlush(after part: GRPCClientRequestPart<Request>) -> Bool {
  859. switch part {
  860. case .metadata:
  861. // If we're not streaming requests then we hold off on the flush until we see end.
  862. return self.isStreamingRequests
  863. case let .message(_, metadata):
  864. // Message flushing is determined by caller preference.
  865. return metadata.flush
  866. case .end:
  867. // Always flush at the end of the request stream.
  868. return true
  869. }
  870. }
  871. /// Make a `_GRPCRequestHead` with the provided metadata.
  872. private func makeRequestHead(with metadata: HPACKHeaders) -> _GRPCRequestHead {
  873. return _GRPCRequestHead(
  874. method: self.callDetails.options.cacheable ? "GET" : "POST",
  875. scheme: self.callDetails.scheme,
  876. path: self.callDetails.path,
  877. host: self.callDetails.authority,
  878. deadline: self.callDetails.options.timeLimit.makeDeadline(),
  879. customMetadata: metadata,
  880. encoding: self.callDetails.options.messageEncoding
  881. )
  882. }
  883. }
  884. extension GRPCClientRequestPart {
  885. /// The name of the request part, used for logging.
  886. fileprivate var name: String {
  887. switch self {
  888. case .metadata:
  889. return "metadata"
  890. case .message:
  891. return "message"
  892. case .end:
  893. return "end"
  894. }
  895. }
  896. }
  897. // A wrapper for connection errors: we need to be able to preserve the underlying error as
  898. // well as extract a 'GRPCStatus' with code '.unavailable'.
  899. internal struct ConnectionFailure: Error, GRPCStatusTransformable, CustomStringConvertible {
  900. /// The reason the connection failed.
  901. var reason: Error
  902. init(reason: Error) {
  903. self.reason = reason
  904. }
  905. var description: String {
  906. return String(describing: self.reason)
  907. }
  908. func makeGRPCStatus() -> GRPCStatus {
  909. return GRPCStatus(
  910. code: .unavailable,
  911. message: String(describing: self.reason),
  912. cause: self.reason
  913. )
  914. }
  915. }