ClientInterceptorPipeline.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. /// A pipeline for intercepting client request and response streams.
  21. ///
  22. /// The interceptor pipeline lies between the call object (`UnaryCall`, `ClientStreamingCall`, etc.)
  23. /// and the transport used to send and receive messages from the server (a `NIO.Channel`). It holds
  24. /// a collection of interceptors which may be used to observe or alter messages as the travel
  25. /// through the pipeline.
  26. ///
  27. /// ```
  28. /// ┌───────────────────────────────────────────────────────────────────┐
  29. /// │ Call │
  30. /// └────────────────────────────────────────────────────────┬──────────┘
  31. /// │ send(_:promise) /
  32. /// │ cancel(promise:)
  33. /// ┌────────────────────────────────────────────────────────▼──────────┐
  34. /// │ InterceptorPipeline ╎ │
  35. /// │ ╎ │
  36. /// │ ┌──────────────────────────────────────────────────────▼────────┐ │
  37. /// │ │ Tail Interceptor (hands response parts to a callback) │ │
  38. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  39. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  40. /// │ │ Interceptor 1 │ │
  41. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  42. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  43. /// │ │ Interceptor 2 │ │
  44. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  45. /// │ ╎ ╎ │
  46. /// │ ╎ (More interceptors) ╎ │
  47. /// │ ╎ ╎ │
  48. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  49. /// │ │ Head Interceptor (interacts with transport) │ │
  50. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  51. /// │ ╎ receive(_:) │ │
  52. /// └──────────▲─────────────────────────────────────────────┼──────────┘
  53. /// │ receive(_:) │ send(_:promise:) /
  54. /// │ │ cancel(promise:)
  55. /// ┌──────────┴─────────────────────────────────────────────▼──────────┐
  56. /// │ ClientTransport │
  57. /// │ (a NIO.ChannelHandler) │
  58. /// ```
  59. @usableFromInline
  60. internal final class ClientInterceptorPipeline<Request, Response> {
  61. /// A logger.
  62. @usableFromInline
  63. internal var logger: Logger
  64. /// The `EventLoop` this RPC is being executed on.
  65. @usableFromInline
  66. internal let eventLoop: EventLoop
  67. /// The details of the call.
  68. @usableFromInline
  69. internal let details: CallDetails
  70. /// A task for closing the RPC in case of a timeout.
  71. @usableFromInline
  72. internal var _scheduledClose: Scheduled<Void>?
  73. @usableFromInline
  74. internal let _errorDelegate: ClientErrorDelegate?
  75. @usableFromInline
  76. internal private(set) var _onError: ((Error) -> Void)?
  77. @usableFromInline
  78. internal private(set) var _onCancel: ((EventLoopPromise<Void>?) -> Void)?
  79. @usableFromInline
  80. internal private(set) var _onRequestPart:
  81. ((GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void)?
  82. @usableFromInline
  83. internal private(set) var _onResponsePart: ((GRPCClientResponsePart<Response>) -> Void)?
  84. /// The index after the last user interceptor context index. (i.e. `_userContexts.endIndex`).
  85. @usableFromInline
  86. internal let _headIndex: Int
  87. /// The index before the first user interceptor context index (always -1).
  88. @usableFromInline
  89. internal let _tailIndex: Int
  90. @usableFromInline
  91. internal var _userContexts: [ClientInterceptorContext<Request, Response>]
  92. /// Whether the interceptor pipeline is still open. It becomes closed after an 'end' response
  93. /// part has traversed the pipeline.
  94. @usableFromInline
  95. internal var _isOpen = true
  96. /// The index of the next context on the inbound side of the context at the given index.
  97. @inlinable
  98. internal func _nextInboundIndex(after index: Int) -> Int {
  99. // Unchecked arithmetic is okay here: our smallest inbound index is '_tailIndex' but we will
  100. // never ask for the inbound index after the tail.
  101. assert(self._indexIsValid(index))
  102. return index &- 1
  103. }
  104. /// The index of the next context on the outbound side of the context at the given index.
  105. @inlinable
  106. internal func _nextOutboundIndex(after index: Int) -> Int {
  107. // Unchecked arithmetic is okay here: our greatest outbound index is '_headIndex' but we will
  108. // never ask for the outbound index after the head.
  109. assert(self._indexIsValid(index))
  110. return index &+ 1
  111. }
  112. /// Returns true of the index is in the range `_tailIndex ... _headIndex`.
  113. @inlinable
  114. internal func _indexIsValid(_ index: Int) -> Bool {
  115. return index >= self._tailIndex && index <= self._headIndex
  116. }
  117. @inlinable
  118. internal init(
  119. eventLoop: EventLoop,
  120. details: CallDetails,
  121. logger: Logger,
  122. interceptors: [ClientInterceptor<Request, Response>],
  123. errorDelegate: ClientErrorDelegate?,
  124. onError: @escaping (Error) -> Void,
  125. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  126. onRequestPart: @escaping (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
  127. onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
  128. ) {
  129. self.eventLoop = eventLoop
  130. self.details = details
  131. self.logger = logger
  132. self._errorDelegate = errorDelegate
  133. self._onError = onError
  134. self._onCancel = onCancel
  135. self._onRequestPart = onRequestPart
  136. self._onResponsePart = onResponsePart
  137. // The tail is before the interceptors.
  138. self._tailIndex = -1
  139. // The head is after the interceptors.
  140. self._headIndex = interceptors.endIndex
  141. // Make some contexts.
  142. self._userContexts = []
  143. self._userContexts.reserveCapacity(interceptors.count)
  144. for index in 0 ..< interceptors.count {
  145. let context = ClientInterceptorContext(for: interceptors[index], atIndex: index, in: self)
  146. self._userContexts.append(context)
  147. }
  148. self._setupDeadline()
  149. }
  150. /// Emit a response part message into the interceptor pipeline.
  151. ///
  152. /// This should be called by the transport layer when receiving a response part from the server.
  153. ///
  154. /// - Parameter part: The part to emit into the pipeline.
  155. /// - Important: This *must* to be called from the `eventLoop`.
  156. @inlinable
  157. internal func receive(_ part: GRPCClientResponsePart<Response>) {
  158. self.invokeReceive(part, fromContextAtIndex: self._headIndex)
  159. }
  160. /// Invoke receive on the appropriate context when called from the context at the given index.
  161. @inlinable
  162. internal func invokeReceive(
  163. _ part: GRPCClientResponsePart<Response>,
  164. fromContextAtIndex index: Int
  165. ) {
  166. self._invokeReceive(part, onContextAtIndex: self._nextInboundIndex(after: index))
  167. }
  168. /// Invoke receive on the context at the given index, if doing so is safe.
  169. @inlinable
  170. internal func _invokeReceive(
  171. _ part: GRPCClientResponsePart<Response>,
  172. onContextAtIndex index: Int
  173. ) {
  174. self.eventLoop.assertInEventLoop()
  175. assert(self._indexIsValid(index))
  176. guard self._isOpen else {
  177. return
  178. }
  179. self._invokeReceive(part, onContextAtUncheckedIndex: index)
  180. }
  181. /// Invoke receive on the context at the given index, assuming that the index is valid and the
  182. /// pipeline is still open.
  183. @inlinable
  184. internal func _invokeReceive(
  185. _ part: GRPCClientResponsePart<Response>,
  186. onContextAtUncheckedIndex index: Int
  187. ) {
  188. switch index {
  189. case self._headIndex:
  190. self._invokeReceive(part, onContextAtUncheckedIndex: self._nextInboundIndex(after: index))
  191. case self._tailIndex:
  192. if part.isEnd {
  193. // Update our state before handling the response part.
  194. self._isOpen = false
  195. self._onResponsePart?(part)
  196. self.close()
  197. } else {
  198. self._onResponsePart?(part)
  199. }
  200. default:
  201. self._userContexts[index].invokeReceive(part)
  202. }
  203. }
  204. /// Emit an error into the interceptor pipeline.
  205. ///
  206. /// This should be called by the transport layer when receiving an error.
  207. ///
  208. /// - Parameter error: The error to emit.
  209. /// - Important: This *must* to be called from the `eventLoop`.
  210. @inlinable
  211. internal func errorCaught(_ error: Error) {
  212. self.invokeErrorCaught(error, fromContextAtIndex: self._headIndex)
  213. }
  214. /// Invoke `errorCaught` on the appropriate context when called from the context at the given
  215. /// index.
  216. @inlinable
  217. internal func invokeErrorCaught(_ error: Error, fromContextAtIndex index: Int) {
  218. self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
  219. }
  220. /// Invoke `errorCaught` on the context at the given index if that index exists and the pipeline
  221. /// is still open.
  222. @inlinable
  223. internal func _invokeErrorCaught(_ error: Error, onContextAtIndex index: Int) {
  224. self.eventLoop.assertInEventLoop()
  225. assert(self._indexIsValid(index))
  226. guard self._isOpen else {
  227. return
  228. }
  229. self._invokeErrorCaught(error, onContextAtUncheckedIndex: index)
  230. }
  231. /// Invoke `errorCaught` on the context at the given index assuming the index exists and the
  232. /// pipeline is still open.
  233. @inlinable
  234. internal func _invokeErrorCaught(_ error: Error, onContextAtUncheckedIndex index: Int) {
  235. switch index {
  236. case self._headIndex:
  237. self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
  238. case self._tailIndex:
  239. self._errorCaught(error)
  240. default:
  241. self._userContexts[index].invokeErrorCaught(error)
  242. }
  243. }
  244. /// Handles a caught error which has traversed the interceptor pipeline.
  245. @usableFromInline
  246. internal func _errorCaught(_ error: Error) {
  247. // We're about to call out to an error handler: update our state first.
  248. self._isOpen = false
  249. var unwrappedError: Error
  250. // Unwrap the error, if possible.
  251. if let errorContext = error as? GRPCError.WithContext {
  252. unwrappedError = errorContext.error
  253. self._errorDelegate?.didCatchError(
  254. errorContext.error,
  255. logger: self.logger,
  256. file: errorContext.file,
  257. line: errorContext.line
  258. )
  259. } else {
  260. unwrappedError = error
  261. self._errorDelegate?.didCatchErrorWithoutContext(error, logger: self.logger)
  262. }
  263. // Emit the unwrapped error.
  264. self._onError?(unwrappedError)
  265. // Close the pipeline.
  266. self.close()
  267. }
  268. /// Writes a request message into the interceptor pipeline.
  269. ///
  270. /// This should be called by the call object to send requests parts to the transport.
  271. ///
  272. /// - Parameters:
  273. /// - part: The request part to write.
  274. /// - promise: A promise to complete when the request part has been successfully written.
  275. /// - Important: This *must* to be called from the `eventLoop`.
  276. @inlinable
  277. internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  278. self.invokeSend(part, promise: promise, fromContextAtIndex: self._tailIndex)
  279. }
  280. /// Invoke send on the appropriate context when called from the context at the given index.
  281. @inlinable
  282. internal func invokeSend(
  283. _ part: GRPCClientRequestPart<Request>,
  284. promise: EventLoopPromise<Void>?,
  285. fromContextAtIndex index: Int
  286. ) {
  287. self._invokeSend(
  288. part,
  289. promise: promise,
  290. onContextAtIndex: self._nextOutboundIndex(after: index)
  291. )
  292. }
  293. /// Invoke send on the context at the given index, if it exists and the pipeline is still open.
  294. @inlinable
  295. internal func _invokeSend(
  296. _ part: GRPCClientRequestPart<Request>,
  297. promise: EventLoopPromise<Void>?,
  298. onContextAtIndex index: Int
  299. ) {
  300. self.eventLoop.assertInEventLoop()
  301. assert(self._indexIsValid(index))
  302. guard self._isOpen else {
  303. promise?.fail(GRPCError.AlreadyComplete())
  304. return
  305. }
  306. self._invokeSend(part, promise: promise, onContextAtUncheckedIndex: index)
  307. }
  308. /// Invoke send on the context at the given index assuming the index exists and the pipeline is
  309. /// still open.
  310. @inlinable
  311. internal func _invokeSend(
  312. _ part: GRPCClientRequestPart<Request>,
  313. promise: EventLoopPromise<Void>?,
  314. onContextAtUncheckedIndex index: Int
  315. ) {
  316. switch index {
  317. case self._headIndex:
  318. self._onRequestPart?(part, promise)
  319. case self._tailIndex:
  320. self._invokeSend(
  321. part,
  322. promise: promise,
  323. onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
  324. )
  325. default:
  326. self._userContexts[index].invokeSend(part, promise: promise)
  327. }
  328. }
  329. /// Send a request to cancel the RPC through the interceptor pipeline.
  330. ///
  331. /// This should be called by the call object when attempting to cancel the RPC.
  332. ///
  333. /// - Parameter promise: A promise to complete when the cancellation request has been handled.
  334. /// - Important: This *must* to be called from the `eventLoop`.
  335. @inlinable
  336. internal func cancel(promise: EventLoopPromise<Void>?) {
  337. self.invokeCancel(promise: promise, fromContextAtIndex: self._tailIndex)
  338. }
  339. /// Invoke `cancel` on the appropriate context when called from the context at the given index.
  340. @inlinable
  341. internal func invokeCancel(promise: EventLoopPromise<Void>?, fromContextAtIndex index: Int) {
  342. self._invokeCancel(promise: promise, onContextAtIndex: self._nextOutboundIndex(after: index))
  343. }
  344. /// Invoke `cancel` on the context at the given index if the index is valid and the pipeline is
  345. /// still open.
  346. @inlinable
  347. internal func _invokeCancel(
  348. promise: EventLoopPromise<Void>?,
  349. onContextAtIndex index: Int
  350. ) {
  351. self.eventLoop.assertInEventLoop()
  352. assert(self._indexIsValid(index))
  353. guard self._isOpen else {
  354. promise?.fail(GRPCError.AlreadyComplete())
  355. return
  356. }
  357. self._invokeCancel(promise: promise, onContextAtUncheckedIndex: index)
  358. }
  359. /// Invoke `cancel` on the context at the given index assuming the index is valid and the
  360. /// pipeline is still open.
  361. @inlinable
  362. internal func _invokeCancel(
  363. promise: EventLoopPromise<Void>?,
  364. onContextAtUncheckedIndex index: Int
  365. ) {
  366. switch index {
  367. case self._headIndex:
  368. self._onCancel?(promise)
  369. case self._tailIndex:
  370. self._invokeCancel(
  371. promise: promise,
  372. onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
  373. )
  374. default:
  375. self._userContexts[index].invokeCancel(promise: promise)
  376. }
  377. }
  378. }
  379. // MARK: - Lifecycle
  380. extension ClientInterceptorPipeline {
  381. /// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
  382. /// the RPC has completed. If this is not called, we will leak.
  383. /// - Important: This *must* to be called from the `eventLoop`.
  384. @inlinable
  385. internal func close() {
  386. self.eventLoop.assertInEventLoop()
  387. self._isOpen = false
  388. // Cancel the timeout.
  389. self._scheduledClose?.cancel()
  390. self._scheduledClose = nil
  391. // Drop the contexts since they reference us.
  392. self._userContexts.removeAll()
  393. // Cancel the transport.
  394. self._onCancel?(nil)
  395. // `ClientTransport` holds a reference to us and references to itself via these callbacks. Break
  396. // these references now by replacing the callbacks.
  397. self._onError = nil
  398. self._onCancel = nil
  399. self._onRequestPart = nil
  400. self._onResponsePart = nil
  401. }
  402. /// Sets up a deadline for the pipeline.
  403. @inlinable
  404. internal func _setupDeadline() {
  405. func setup() {
  406. self.eventLoop.assertInEventLoop()
  407. let timeLimit = self.details.options.timeLimit
  408. let deadline = timeLimit.makeDeadline()
  409. // There's no point scheduling this.
  410. if deadline == .distantFuture {
  411. return
  412. }
  413. self._scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
  414. // When the error hits the tail we'll call 'close()', this will cancel the transport if
  415. // necessary.
  416. self.errorCaught(GRPCError.RPCTimedOut(timeLimit))
  417. }
  418. }
  419. if self.eventLoop.inEventLoop {
  420. setup()
  421. } else {
  422. self.eventLoop.execute {
  423. setup()
  424. }
  425. }
  426. }
  427. }
  428. extension ClientInterceptorContext {
  429. @inlinable
  430. internal func invokeReceive(_ part: GRPCClientResponsePart<Response>) {
  431. self.interceptor.receive(part, context: self)
  432. }
  433. @inlinable
  434. internal func invokeSend(
  435. _ part: GRPCClientRequestPart<Request>,
  436. promise: EventLoopPromise<Void>?
  437. ) {
  438. self.interceptor.send(part, promise: promise, context: self)
  439. }
  440. @inlinable
  441. internal func invokeCancel(promise: EventLoopPromise<Void>?) {
  442. self.interceptor.cancel(promise: promise, context: self)
  443. }
  444. @inlinable
  445. internal func invokeErrorCaught(_ error: Error) {
  446. self.interceptor.errorCaught(error, context: self)
  447. }
  448. }