ClientTransport.swift 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 let 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.onStart()
  293. self.unbuffer()
  294. case .close:
  295. channel.close(mode: .all, promise: nil)
  296. case .doNothing:
  297. ()
  298. }
  299. }
  300. /// The `Channel` became inactive. Fail any buffered writes and forward an error to the
  301. /// interceptor pipeline if necessary.
  302. private func transportDeactivated() {
  303. if self.callEventLoop.inEventLoop {
  304. self._transportDeactivated()
  305. } else {
  306. self.callEventLoop.execute {
  307. self._transportDeactivated()
  308. }
  309. }
  310. }
  311. /// On-loop implementation of `transportDeactivated()`.
  312. private func _transportDeactivated() {
  313. self.callEventLoop.assertInEventLoop()
  314. switch self.state.deactivate() {
  315. case .doNothing:
  316. ()
  317. case .tearDown:
  318. let status = GRPCStatus(code: .unavailable, message: "Transport became inactive")
  319. self.forwardErrorToInterceptors(status)
  320. self.failBufferedWrites(with: status)
  321. self.channelPromise?.fail(status)
  322. case .failChannelPromise:
  323. self.channelPromise?.fail(GRPCError.AlreadyComplete())
  324. }
  325. }
  326. /// Drops any references to the `Channel` and interceptor pipeline.
  327. private func dropReferences() {
  328. if self.callEventLoop.inEventLoop {
  329. self.channel = nil
  330. } else {
  331. self.callEventLoop.execute {
  332. self.channel = nil
  333. }
  334. }
  335. }
  336. /// Handles an error caught in the pipeline or from elsewhere. The error may be forwarded to the
  337. /// interceptor pipeline and any buffered writes will be failed. Any underlying `Channel` will
  338. /// also be closed.
  339. internal func handleError(_ error: Error) {
  340. if self.callEventLoop.inEventLoop {
  341. self._handleError(error)
  342. } else {
  343. self.callEventLoop.execute {
  344. self._handleError(error)
  345. }
  346. }
  347. }
  348. /// On-loop implementation of `handleError(_:)`.
  349. private func _handleError(_ error: Error) {
  350. self.callEventLoop.assertInEventLoop()
  351. switch self.state.handleError() {
  352. case .doNothing:
  353. ()
  354. case .propagateError:
  355. self.forwardErrorToInterceptors(error)
  356. self.failBufferedWrites(with: error)
  357. case .propagateErrorAndClose:
  358. self.forwardErrorToInterceptors(error)
  359. self.failBufferedWrites(with: error)
  360. self.channel?.close(mode: .all, promise: nil)
  361. }
  362. }
  363. /// Receive initial metadata from the `Channel`.
  364. private func receiveFromChannel(initialMetadata headers: HPACKHeaders) {
  365. if self.callEventLoop.inEventLoop {
  366. self._receiveFromChannel(initialMetadata: headers)
  367. } else {
  368. self.callEventLoop.execute {
  369. self._receiveFromChannel(initialMetadata: headers)
  370. }
  371. }
  372. }
  373. /// On-loop implementation of `receiveFromChannel(initialMetadata:)`.
  374. private func _receiveFromChannel(initialMetadata headers: HPACKHeaders) {
  375. self.callEventLoop.assertInEventLoop()
  376. if self.state.channelRead(isEnd: false) {
  377. self.forwardToInterceptors(.metadata(headers))
  378. }
  379. }
  380. /// Receive response message bytes from the `Channel`.
  381. private func receiveFromChannel(message buffer: ByteBuffer) {
  382. if self.callEventLoop.inEventLoop {
  383. self._receiveFromChannel(message: buffer)
  384. } else {
  385. self.callEventLoop.execute {
  386. self._receiveFromChannel(message: buffer)
  387. }
  388. }
  389. }
  390. /// On-loop implementation of `receiveFromChannel(message:)`.
  391. private func _receiveFromChannel(message buffer: ByteBuffer) {
  392. self.callEventLoop.assertInEventLoop()
  393. do {
  394. let message = try self.deserializer.deserialize(byteBuffer: buffer)
  395. if self.state.channelRead(isEnd: false) {
  396. self.forwardToInterceptors(.message(message))
  397. }
  398. } catch {
  399. self.handleError(error)
  400. }
  401. }
  402. /// Receive trailing metadata from the `Channel`.
  403. private func receiveFromChannel(trailingMetadata trailers: HPACKHeaders) {
  404. // The `Channel` delivers trailers and `GRPCStatus` separately, we want to emit them together
  405. // in the interceptor pipeline.
  406. if self.callEventLoop.inEventLoop {
  407. self.trailers = trailers
  408. } else {
  409. self.callEventLoop.execute {
  410. self.trailers = trailers
  411. }
  412. }
  413. }
  414. /// Receive the final status from the `Channel`.
  415. private func receiveFromChannel(status: GRPCStatus) {
  416. if self.callEventLoop.inEventLoop {
  417. self._receiveFromChannel(status: status)
  418. } else {
  419. self.callEventLoop.execute {
  420. self._receiveFromChannel(status: status)
  421. }
  422. }
  423. }
  424. /// On-loop implementation of `receiveFromChannel(status:)`.
  425. private func _receiveFromChannel(status: GRPCStatus) {
  426. self.callEventLoop.assertInEventLoop()
  427. if self.state.channelRead(isEnd: true) {
  428. self.forwardToInterceptors(.end(status, self.trailers ?? [:]))
  429. self.trailers = nil
  430. }
  431. }
  432. }
  433. // MARK: - State Handling
  434. private enum ClientTransportState {
  435. /// Idle. We're waiting for the RPC to be configured.
  436. ///
  437. /// Valid transitions:
  438. /// - `awaitingTransport` (the transport is being configured)
  439. /// - `closed` (the RPC cancels)
  440. case idle
  441. /// Awaiting transport. The RPC has requested transport and we're waiting for that transport to
  442. /// activate. We'll buffer any outbound messages from this state. Receiving messages from the
  443. /// transport in this state is an error.
  444. ///
  445. /// Valid transitions:
  446. /// - `activatingTransport` (the channel becomes active)
  447. /// - `closing` (the RPC cancels)
  448. /// - `closed` (the channel fails to become active)
  449. case awaitingTransport
  450. /// The transport is active but we're unbuffering any requests to write on that transport.
  451. /// We'll continue buffering in this state. Receiving messages from the transport in this state
  452. /// is okay.
  453. ///
  454. /// Valid transitions:
  455. /// - `active` (we finish unbuffering)
  456. /// - `closing` (the RPC cancels, the channel encounters an error)
  457. /// - `closed` (the channel becomes inactive)
  458. case activatingTransport
  459. /// Fully active. An RPC is in progress and is communicating over an active transport.
  460. ///
  461. /// Valid transitions:
  462. /// - `closing` (the RPC cancels, the channel encounters an error)
  463. /// - `closed` (the channel becomes inactive)
  464. case active
  465. /// Closing. Either the RPC was cancelled or any `Channel` associated with the transport hasn't
  466. /// become inactive yet.
  467. ///
  468. /// Valid transitions:
  469. /// - `closed` (the channel becomes inactive)
  470. case closing
  471. /// We're closed. Any writes from the RPC will be failed. Any responses from the transport will
  472. /// be ignored.
  473. ///
  474. /// Valid transitions:
  475. /// - none: this state is terminal.
  476. case closed
  477. /// Whether writes may be unbuffered in this state.
  478. internal var isUnbuffering: Bool {
  479. switch self {
  480. case .activatingTransport:
  481. return true
  482. case .idle, .awaitingTransport, .active, .closing, .closed:
  483. return false
  484. }
  485. }
  486. /// Whether this state allows writes to be buffered. (This is useful only to inform logging.)
  487. internal var mayBuffer: Bool {
  488. switch self {
  489. case .idle, .activatingTransport, .awaitingTransport:
  490. return true
  491. case .active, .closing, .closed:
  492. return false
  493. }
  494. }
  495. }
  496. extension ClientTransportState {
  497. /// The caller would like to configure the transport. Returns a boolean indicating whether we
  498. /// should configure it or not.
  499. mutating func configureTransport() -> Bool {
  500. switch self {
  501. // We're idle until we configure. Anything else is just a repeat request to configure.
  502. case .idle:
  503. self = .awaitingTransport
  504. return true
  505. case .awaitingTransport, .activatingTransport, .active, .closing, .closed:
  506. return false
  507. }
  508. }
  509. enum SendAction {
  510. /// Write the request into the buffer.
  511. case writeToBuffer
  512. /// Write the request into the channel.
  513. case writeToChannel
  514. /// The RPC has already completed, fail any promise associated with the write.
  515. case alreadyComplete
  516. }
  517. /// The pipeline would like to send a request part to the transport.
  518. mutating func send() -> SendAction {
  519. switch self {
  520. // We don't have any transport yet, just buffer the part.
  521. case .idle, .awaitingTransport, .activatingTransport:
  522. return .writeToBuffer
  523. // We have a `Channel`, we can pipe the write straight through.
  524. case .active:
  525. return .writeToChannel
  526. // The transport is going or has gone away. Fail the promise.
  527. case .closing, .closed:
  528. return .alreadyComplete
  529. }
  530. }
  531. enum UnbufferedAction {
  532. /// Nothing needs to be done.
  533. case doNothing
  534. /// Succeed the channel promise associated with the transport.
  535. case succeedChannelPromise
  536. }
  537. /// We finished dealing with the buffered writes.
  538. mutating func unbuffered() -> UnbufferedAction {
  539. switch self {
  540. // These can't happen since we only begin unbuffering when we transition to
  541. // '.activatingTransport', which must come after these two states..
  542. case .idle, .awaitingTransport:
  543. preconditionFailure("Requests can't be unbuffered before the transport is activated")
  544. // We dealt with any buffered writes. We can become active now. This is the only way to become
  545. // active.
  546. case .activatingTransport:
  547. self = .active
  548. return .succeedChannelPromise
  549. case .active:
  550. preconditionFailure("Unbuffering completed but the transport is already active")
  551. // Something caused us to close while unbuffering, that's okay, we won't take any further
  552. // action.
  553. case .closing, .closed:
  554. return .doNothing
  555. }
  556. }
  557. /// Cancel the RPC and associated `Channel`, if possible. Returns a boolean indicated whether
  558. /// cancellation can go ahead (and also whether the channel should be torn down).
  559. mutating func cancel() -> Bool {
  560. switch self {
  561. case .idle:
  562. // No RPC has been started and we don't have a `Channel`. We need to tell the interceptor
  563. // we're done, fail any writes, and then deal with the cancellation promise.
  564. self = .closed
  565. return true
  566. case .awaitingTransport:
  567. // An RPC has started and we're waiting for the `Channel` to activate. We'll mark ourselves as
  568. // closing. We don't need to explicitly close the `Channel`, this will happen as a result of
  569. // the `Channel` becoming active (see `channelActive(context:)`).
  570. self = .closing
  571. return true
  572. case .activatingTransport:
  573. // The RPC has started, the `Channel` is active and we're emptying our write buffer. We'll
  574. // mark ourselves as closing: we'll error the interceptor pipeline, close the channel, fail
  575. // any buffered writes and then complete the cancellation promise.
  576. self = .closing
  577. return true
  578. case .active:
  579. // The RPC and channel are up and running. We'll fail the RPC and close the channel.
  580. self = .closing
  581. return true
  582. case .closing, .closed:
  583. // We're already closing or closing. The cancellation is too late.
  584. return false
  585. }
  586. }
  587. enum ActivateAction {
  588. case unbuffer
  589. case close
  590. case doNothing
  591. }
  592. /// `channelActive` was invoked on the transport by the `Channel`.
  593. mutating func activate() -> ActivateAction {
  594. // The channel has become active: what now?
  595. switch self {
  596. case .idle:
  597. preconditionFailure("Can't activate an idle transport")
  598. case .awaitingTransport:
  599. self = .activatingTransport
  600. return .unbuffer
  601. case .activatingTransport, .active:
  602. // Already activated.
  603. return .doNothing
  604. case .closing:
  605. // We remain in closing: we only transition to closed on 'channelInactive'.
  606. return .close
  607. case .closed:
  608. preconditionFailure("Invalid state: stream is already inactive")
  609. }
  610. }
  611. enum ChannelInactiveAction {
  612. /// Tear down the transport; forward an error to the interceptors and fail any buffered writes.
  613. case tearDown
  614. /// Fail the 'Channel' promise, if one exists; the RPC is already complete.
  615. case failChannelPromise
  616. /// Do nothing.
  617. case doNothing
  618. }
  619. /// `channelInactive` was invoked on the transport by the `Channel`.
  620. mutating func deactivate() -> ChannelInactiveAction {
  621. switch self {
  622. case .idle:
  623. // We can't become inactive before we've requested a `Channel`.
  624. preconditionFailure("Can't deactivate an idle transport")
  625. case .awaitingTransport, .activatingTransport, .active:
  626. // We're activating the transport - i.e. offloading any buffered requests - and the channel
  627. // became inactive. We haven't received an error (otherwise we'd be `closing`) so we should
  628. // synthesize an error status to fail the RPC with.
  629. self = .closed
  630. return .tearDown
  631. case .closing:
  632. // We were already closing, now we're fully closed.
  633. self = .closed
  634. return .failChannelPromise
  635. case .closed:
  636. // We're already closed.
  637. return .doNothing
  638. }
  639. }
  640. /// `channelRead` was invoked on the transport by the `Channel`. Returns a boolean value
  641. /// indicating whether the part that was read should be forwarded to the interceptor pipeline.
  642. mutating func channelRead(isEnd: Bool) -> Bool {
  643. switch self {
  644. case .idle, .awaitingTransport:
  645. // If there's no `Channel` or the `Channel` isn't active, then we can't read anything.
  646. preconditionFailure("Can't receive response part on idle transport")
  647. case .activatingTransport, .active:
  648. // We have an active `Channel`, we can forward the request part but we may need to start
  649. // closing if we see the status, since it indicates the call is terminating.
  650. if isEnd {
  651. self = .closing
  652. }
  653. return true
  654. case .closing, .closed:
  655. // We closed early, ignore any reads.
  656. return false
  657. }
  658. }
  659. enum HandleErrorAction {
  660. /// Propagate the error to the interceptor pipeline and fail any buffered writes.
  661. case propagateError
  662. /// As above, but close the 'Channel' as well.
  663. case propagateErrorAndClose
  664. /// No action is required.
  665. case doNothing
  666. }
  667. /// An error was caught.
  668. mutating func handleError() -> HandleErrorAction {
  669. switch self {
  670. case .idle:
  671. // The `Channel` can't error if it doesn't exist.
  672. preconditionFailure("Can't catch error on idle transport")
  673. case .awaitingTransport:
  674. // We're waiting for the `Channel` to become active. We're toast now, so close, failing any
  675. // buffered writes along the way.
  676. self = .closing
  677. return .propagateError
  678. case .activatingTransport,
  679. .active:
  680. // We're either fully active or unbuffering. Forward an error, fail any writes and then close.
  681. self = .closing
  682. return .propagateErrorAndClose
  683. case .closing, .closed:
  684. // We're already closing/closed, we can ignore this.
  685. return .doNothing
  686. }
  687. }
  688. enum GetChannelAction {
  689. /// No action is required.
  690. case doNothing
  691. /// Succeed the Channel promise.
  692. case succeed
  693. /// Fail the 'Channel' promise, the RPC is already complete.
  694. case fail
  695. }
  696. /// The caller has asked for the underlying `Channel`.
  697. mutating func getChannel() -> GetChannelAction {
  698. switch self {
  699. case .idle, .awaitingTransport, .activatingTransport:
  700. // Do nothing, we'll complete the promise when we become active or closed.
  701. return .doNothing
  702. case .active:
  703. // We're already active, so there was no promise to succeed when we made this transition. We
  704. // can complete it now.
  705. return .succeed
  706. case .closing:
  707. // We'll complete the promise when we transition to closed.
  708. return .doNothing
  709. case .closed:
  710. // We're already closed; there was no promise to fail when we made this transition. We can go
  711. // ahead and fail it now though.
  712. return .fail
  713. }
  714. }
  715. }
  716. // MARK: - State Actions
  717. extension ClientTransport {
  718. /// Configures this transport with the `configurator`.
  719. private func configure(using configurator: (ChannelHandler) -> EventLoopFuture<Void>) {
  720. configurator(self).whenFailure { error in
  721. // We might be on a different EL, but `handleError` will sort that out for us, so no need to
  722. // hop.
  723. if error is GRPCStatus || error is GRPCStatusTransformable {
  724. self.handleError(error)
  725. } else {
  726. // Fallback to something which will mark the RPC as 'unavailable'.
  727. self.handleError(ConnectionFailure(reason: error))
  728. }
  729. }
  730. }
  731. /// Append a request part to the write buffer.
  732. /// - Parameters:
  733. /// - part: The request part to buffer.
  734. /// - promise: A promise to complete when the request part has been sent.
  735. private func buffer(
  736. _ part: GRPCClientRequestPart<Request>,
  737. promise: EventLoopPromise<Void>?
  738. ) {
  739. self.callEventLoop.assertInEventLoop()
  740. self.logger.trace("buffering request part", metadata: [
  741. "request_part": "\(part.name)",
  742. "call_state": self.stateForLogging,
  743. ])
  744. self.writeBuffer.append(.init(request: part, promise: promise))
  745. }
  746. /// Writes any buffered request parts to the `Channel`.
  747. private func unbuffer() {
  748. self.callEventLoop.assertInEventLoop()
  749. guard let channel = self.channel else {
  750. return
  751. }
  752. // Save any flushing until we're done writing.
  753. var shouldFlush = false
  754. self.logger.trace("unbuffering request parts", metadata: [
  755. "request_parts": "\(self.writeBuffer.count)",
  756. ])
  757. // Why the double loop? A promise completed as a result of the flush may enqueue more writes,
  758. // or causes us to change state (i.e. we may have to close). If we didn't loop around then we
  759. // may miss more buffered writes.
  760. while self.state.isUnbuffering, !self.writeBuffer.isEmpty {
  761. // Pull out as many writes as possible.
  762. while let write = self.writeBuffer.popFirst() {
  763. self.logger.trace("unbuffering request part", metadata: [
  764. "request_part": "\(write.request.name)",
  765. ])
  766. if !shouldFlush {
  767. shouldFlush = self.shouldFlush(after: write.request)
  768. }
  769. self.writeToChannel(channel, part: write.request, promise: write.promise, flush: false)
  770. }
  771. // Okay, flush now.
  772. if shouldFlush {
  773. shouldFlush = false
  774. channel.flush()
  775. }
  776. }
  777. if self.writeBuffer.isEmpty {
  778. self.logger.trace("request buffer drained")
  779. } else {
  780. self.logger.notice("unbuffering aborted", metadata: ["call_state": self.stateForLogging])
  781. }
  782. // We're unbuffered. What now?
  783. switch self.state.unbuffered() {
  784. case .doNothing:
  785. ()
  786. case .succeedChannelPromise:
  787. self.channelPromise?.succeed(channel)
  788. }
  789. }
  790. /// Fails any promises that come with buffered writes with `error`.
  791. /// - Parameter error: The `Error` to fail promises with.
  792. private func failBufferedWrites(with error: Error) {
  793. self.logger.trace("failing buffered writes", metadata: ["call_state": self.stateForLogging])
  794. while let write = self.writeBuffer.popFirst() {
  795. write.promise?.fail(error)
  796. }
  797. }
  798. /// Write a request part to the `Channel`.
  799. /// - Parameters:
  800. /// - channel: The `Channel` to write `part` to.
  801. /// - part: The request part to write.
  802. /// - promise: A promise to complete once the write has been completed.
  803. /// - flush: Whether to flush the `Channel` after writing.
  804. private func writeToChannel(
  805. _ channel: Channel,
  806. part: GRPCClientRequestPart<Request>,
  807. promise: EventLoopPromise<Void>?,
  808. flush: Bool
  809. ) {
  810. switch part {
  811. case let .metadata(headers):
  812. let head = self.makeRequestHead(with: headers)
  813. channel.write(self.wrapOutboundOut(.head(head)), promise: promise)
  814. case let .message(request, metadata):
  815. do {
  816. let bytes = try self.serializer.serialize(request, allocator: channel.allocator)
  817. let message = _MessageContext<ByteBuffer>(bytes, compressed: metadata.compress)
  818. channel.write(self.wrapOutboundOut(.message(message)), promise: promise)
  819. } catch {
  820. self.handleError(error)
  821. }
  822. case .end:
  823. channel.write(self.wrapOutboundOut(.end), promise: promise)
  824. }
  825. if flush {
  826. channel.flush()
  827. }
  828. }
  829. /// Forward the response part to the interceptor pipeline.
  830. /// - Parameter part: The response part to forward.
  831. private func forwardToInterceptors(_ part: GRPCClientResponsePart<Response>) {
  832. self.callEventLoop.assertInEventLoop()
  833. self._pipeline?.receive(part)
  834. }
  835. /// Forward the error to the interceptor pipeline.
  836. /// - Parameter error: The error to forward.
  837. private func forwardErrorToInterceptors(_ error: Error) {
  838. self.callEventLoop.assertInEventLoop()
  839. self._pipeline?.errorCaught(error)
  840. }
  841. }
  842. // MARK: - Helpers
  843. extension ClientTransport {
  844. /// Returns whether the `Channel` should be flushed after writing the given part to it.
  845. private func shouldFlush(after part: GRPCClientRequestPart<Request>) -> Bool {
  846. switch part {
  847. case .metadata:
  848. // If we're not streaming requests then we hold off on the flush until we see end.
  849. return self.isStreamingRequests
  850. case let .message(_, metadata):
  851. // Message flushing is determined by caller preference.
  852. return metadata.flush
  853. case .end:
  854. // Always flush at the end of the request stream.
  855. return true
  856. }
  857. }
  858. /// Make a `_GRPCRequestHead` with the provided metadata.
  859. private func makeRequestHead(with metadata: HPACKHeaders) -> _GRPCRequestHead {
  860. return _GRPCRequestHead(
  861. method: self.callDetails.options.cacheable ? "GET" : "POST",
  862. scheme: self.callDetails.scheme,
  863. path: self.callDetails.path,
  864. host: self.callDetails.authority,
  865. deadline: self.callDetails.options.timeLimit.makeDeadline(),
  866. customMetadata: metadata,
  867. encoding: self.callDetails.options.messageEncoding
  868. )
  869. }
  870. }
  871. extension GRPCClientRequestPart {
  872. /// The name of the request part, used for logging.
  873. fileprivate var name: String {
  874. switch self {
  875. case .metadata:
  876. return "metadata"
  877. case .message:
  878. return "message"
  879. case .end:
  880. return "end"
  881. }
  882. }
  883. }
  884. // A wrapper for connection errors: we need to be able to preserve the underlying error as
  885. // well as extract a 'GRPCStatus' with code '.unavailable'.
  886. internal struct ConnectionFailure: Error, GRPCStatusTransformable, CustomStringConvertible {
  887. /// The reason the connection failed.
  888. var reason: Error
  889. init(reason: Error) {
  890. self.reason = reason
  891. }
  892. var description: String {
  893. return String(describing: self.reason)
  894. }
  895. func makeGRPCStatus() -> GRPCStatus {
  896. return GRPCStatus(
  897. code: .unavailable,
  898. message: String(describing: self.reason),
  899. cause: self.reason
  900. )
  901. }
  902. }