2
0

ClientTransport.swift 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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.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("buffering request part", metadata: [
  740. "request_part": "\(part.name)",
  741. "call_state": self.stateForLogging,
  742. ])
  743. self.writeBuffer.append(.init(request: part, promise: promise))
  744. }
  745. /// Writes any buffered request parts to the `Channel`.
  746. private func unbuffer() {
  747. self.callEventLoop.assertInEventLoop()
  748. guard let channel = self.channel else {
  749. return
  750. }
  751. // Save any flushing until we're done writing.
  752. var shouldFlush = false
  753. self.logger.trace("unbuffering request parts", metadata: [
  754. "request_parts": "\(self.writeBuffer.count)",
  755. ])
  756. // Why the double loop? A promise completed as a result of the flush may enqueue more writes,
  757. // or causes us to change state (i.e. we may have to close). If we didn't loop around then we
  758. // may miss more buffered writes.
  759. while self.state.isUnbuffering, !self.writeBuffer.isEmpty {
  760. // Pull out as many writes as possible.
  761. while let write = self.writeBuffer.popFirst() {
  762. self.logger.trace("unbuffering request part", metadata: [
  763. "request_part": "\(write.request.name)",
  764. ])
  765. if !shouldFlush {
  766. shouldFlush = self.shouldFlush(after: write.request)
  767. }
  768. self.writeToChannel(channel, part: write.request, promise: write.promise, flush: false)
  769. }
  770. // Okay, flush now.
  771. if shouldFlush {
  772. shouldFlush = false
  773. channel.flush()
  774. }
  775. }
  776. if self.writeBuffer.isEmpty {
  777. self.logger.trace("request buffer drained")
  778. } else {
  779. self.logger.notice("unbuffering aborted", metadata: ["call_state": self.stateForLogging])
  780. }
  781. // We're unbuffered. What now?
  782. switch self.state.unbuffered() {
  783. case .doNothing:
  784. ()
  785. case .succeedChannelPromise:
  786. self.channelPromise?.succeed(channel)
  787. }
  788. }
  789. /// Fails any promises that come with buffered writes with `error`.
  790. /// - Parameter error: The `Error` to fail promises with.
  791. private func failBufferedWrites(with error: Error) {
  792. self.logger.trace("failing buffered writes", metadata: ["call_state": self.stateForLogging])
  793. while let write = self.writeBuffer.popFirst() {
  794. write.promise?.fail(error)
  795. }
  796. }
  797. /// Write a request part to the `Channel`.
  798. /// - Parameters:
  799. /// - channel: The `Channel` to write `part` to.
  800. /// - part: The request part to write.
  801. /// - promise: A promise to complete once the write has been completed.
  802. /// - flush: Whether to flush the `Channel` after writing.
  803. private func writeToChannel(
  804. _ channel: Channel,
  805. part: GRPCClientRequestPart<Request>,
  806. promise: EventLoopPromise<Void>?,
  807. flush: Bool
  808. ) {
  809. switch part {
  810. case let .metadata(headers):
  811. let head = self.makeRequestHead(with: headers)
  812. channel.write(self.wrapOutboundOut(.head(head)), promise: promise)
  813. // Messages are buffered by this class and in the async writer for async calls. Initially the
  814. // async writer is not allowed to emit messages; the call to 'onStart()' signals that messages
  815. // may be emitted. We call it here to avoid races between writing headers and messages.
  816. self.onStart()
  817. case let .message(request, metadata):
  818. do {
  819. let bytes = try self.serializer.serialize(request, allocator: channel.allocator)
  820. let message = _MessageContext<ByteBuffer>(bytes, compressed: metadata.compress)
  821. channel.write(self.wrapOutboundOut(.message(message)), promise: promise)
  822. } catch {
  823. self.handleError(error)
  824. }
  825. case .end:
  826. channel.write(self.wrapOutboundOut(.end), promise: promise)
  827. }
  828. if flush {
  829. channel.flush()
  830. }
  831. }
  832. /// Forward the response part to the interceptor pipeline.
  833. /// - Parameter part: The response part to forward.
  834. private func forwardToInterceptors(_ part: GRPCClientResponsePart<Response>) {
  835. self.callEventLoop.assertInEventLoop()
  836. self._pipeline?.receive(part)
  837. }
  838. /// Forward the error to the interceptor pipeline.
  839. /// - Parameter error: The error to forward.
  840. private func forwardErrorToInterceptors(_ error: Error) {
  841. self.callEventLoop.assertInEventLoop()
  842. self._pipeline?.errorCaught(error)
  843. }
  844. }
  845. // MARK: - Helpers
  846. extension ClientTransport {
  847. /// Returns whether the `Channel` should be flushed after writing the given part to it.
  848. private func shouldFlush(after part: GRPCClientRequestPart<Request>) -> Bool {
  849. switch part {
  850. case .metadata:
  851. // If we're not streaming requests then we hold off on the flush until we see end.
  852. return self.isStreamingRequests
  853. case let .message(_, metadata):
  854. // Message flushing is determined by caller preference.
  855. return metadata.flush
  856. case .end:
  857. // Always flush at the end of the request stream.
  858. return true
  859. }
  860. }
  861. /// Make a `_GRPCRequestHead` with the provided metadata.
  862. private func makeRequestHead(with metadata: HPACKHeaders) -> _GRPCRequestHead {
  863. return _GRPCRequestHead(
  864. method: self.callDetails.options.cacheable ? "GET" : "POST",
  865. scheme: self.callDetails.scheme,
  866. path: self.callDetails.path,
  867. host: self.callDetails.authority,
  868. deadline: self.callDetails.options.timeLimit.makeDeadline(),
  869. customMetadata: metadata,
  870. encoding: self.callDetails.options.messageEncoding
  871. )
  872. }
  873. }
  874. extension GRPCClientRequestPart {
  875. /// The name of the request part, used for logging.
  876. fileprivate var name: String {
  877. switch self {
  878. case .metadata:
  879. return "metadata"
  880. case .message:
  881. return "message"
  882. case .end:
  883. return "end"
  884. }
  885. }
  886. }
  887. // A wrapper for connection errors: we need to be able to preserve the underlying error as
  888. // well as extract a 'GRPCStatus' with code '.unavailable'.
  889. internal struct ConnectionFailure: Error, GRPCStatusTransformable, CustomStringConvertible {
  890. /// The reason the connection failed.
  891. var reason: Error
  892. init(reason: Error) {
  893. self.reason = reason
  894. }
  895. var description: String {
  896. return String(describing: self.reason)
  897. }
  898. func makeGRPCStatus() -> GRPCStatus {
  899. return GRPCStatus(
  900. code: .unavailable,
  901. message: String(describing: self.reason),
  902. cause: self.reason
  903. )
  904. }
  905. }