ClientInterceptorPipeline.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 NIO
  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. internal var logger: Logger {
  63. return self.details.options.logger
  64. }
  65. /// The `EventLoop` this RPC is being executed on.
  66. @usableFromInline
  67. internal let eventLoop: EventLoop
  68. /// The details of the call.
  69. @usableFromInline
  70. internal let details: CallDetails
  71. /// A task for closing the RPC in case of a timeout.
  72. @usableFromInline
  73. internal var _scheduledClose: Scheduled<Void>?
  74. @usableFromInline
  75. internal let _errorDelegate: ClientErrorDelegate?
  76. @usableFromInline
  77. internal let _onError: (Error) -> Void
  78. @usableFromInline
  79. internal let _onCancel: (EventLoopPromise<Void>?) -> Void
  80. @usableFromInline
  81. internal let _onRequestPart: (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void
  82. @usableFromInline
  83. internal let _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. interceptors: [ClientInterceptor<Request, Response>],
  122. errorDelegate: ClientErrorDelegate?,
  123. onError: @escaping (Error) -> Void,
  124. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  125. onRequestPart: @escaping (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
  126. onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
  127. ) {
  128. self.eventLoop = eventLoop
  129. self.details = details
  130. self._errorDelegate = errorDelegate
  131. self._onError = onError
  132. self._onCancel = onCancel
  133. self._onRequestPart = onRequestPart
  134. self._onResponsePart = onResponsePart
  135. // The tail is before the interceptors.
  136. self._tailIndex = -1
  137. // The head is after the interceptors.
  138. self._headIndex = interceptors.endIndex
  139. // Make some contexts.
  140. self._userContexts = []
  141. self._userContexts.reserveCapacity(interceptors.count)
  142. for index in 0 ..< interceptors.count {
  143. let context = ClientInterceptorContext(for: interceptors[index], atIndex: index, in: self)
  144. self._userContexts.append(context)
  145. }
  146. self._setupDeadline()
  147. }
  148. /// Emit a response part message into the interceptor pipeline.
  149. ///
  150. /// This should be called by the transport layer when receiving a response part from the server.
  151. ///
  152. /// - Parameter part: The part to emit into the pipeline.
  153. /// - Important: This *must* to be called from the `eventLoop`.
  154. @inlinable
  155. internal func receive(_ part: GRPCClientResponsePart<Response>) {
  156. self.invokeReceive(part, fromContextAtIndex: self._headIndex)
  157. }
  158. /// Invoke receive on the appropriate context when called from the context at the given index.
  159. @inlinable
  160. internal func invokeReceive(
  161. _ part: GRPCClientResponsePart<Response>,
  162. fromContextAtIndex index: Int
  163. ) {
  164. self._invokeReceive(part, onContextAtIndex: self._nextInboundIndex(after: index))
  165. }
  166. /// Invoke receive on the context at the given index, if doing so is safe.
  167. @inlinable
  168. internal func _invokeReceive(
  169. _ part: GRPCClientResponsePart<Response>,
  170. onContextAtIndex index: Int
  171. ) {
  172. self.eventLoop.assertInEventLoop()
  173. assert(self._indexIsValid(index))
  174. guard self._isOpen else {
  175. return
  176. }
  177. self._invokeReceive(part, onContextAtUncheckedIndex: index)
  178. }
  179. /// Invoke receive on the context at the given index, assuming that the index is valid and the
  180. /// pipeline is still open.
  181. @inlinable
  182. internal func _invokeReceive(
  183. _ part: GRPCClientResponsePart<Response>,
  184. onContextAtUncheckedIndex index: Int
  185. ) {
  186. switch index {
  187. case self._headIndex:
  188. self._invokeReceive(part, onContextAtUncheckedIndex: self._nextInboundIndex(after: index))
  189. case self._tailIndex:
  190. if part.isEnd {
  191. self.close()
  192. }
  193. self._onResponsePart(part)
  194. default:
  195. self._userContexts[index].invokeReceive(part)
  196. }
  197. }
  198. /// Emit an error into the interceptor pipeline.
  199. ///
  200. /// This should be called by the transport layer when receiving an error.
  201. ///
  202. /// - Parameter error: The error to emit.
  203. /// - Important: This *must* to be called from the `eventLoop`.
  204. @inlinable
  205. internal func errorCaught(_ error: Error) {
  206. self.invokeErrorCaught(error, fromContextAtIndex: self._headIndex)
  207. }
  208. /// Invoke `errorCaught` on the appropriate context when called from the context at the given
  209. /// index.
  210. @inlinable
  211. internal func invokeErrorCaught(_ error: Error, fromContextAtIndex index: Int) {
  212. self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
  213. }
  214. /// Invoke `errorCaught` on the context at the given index if that index exists and the pipeline
  215. /// is still open.
  216. @inlinable
  217. internal func _invokeErrorCaught(_ error: Error, onContextAtIndex index: Int) {
  218. self.eventLoop.assertInEventLoop()
  219. assert(self._indexIsValid(index))
  220. guard self._isOpen else {
  221. return
  222. }
  223. self._invokeErrorCaught(error, onContextAtUncheckedIndex: index)
  224. }
  225. /// Invoke `errorCaught` on the context at the given index assuming the index exists and the
  226. /// pipeline is still open.
  227. @inlinable
  228. internal func _invokeErrorCaught(_ error: Error, onContextAtUncheckedIndex index: Int) {
  229. switch index {
  230. case self._headIndex:
  231. self._invokeErrorCaught(error, onContextAtIndex: self._nextInboundIndex(after: index))
  232. case self._tailIndex:
  233. self._errorCaught(error)
  234. default:
  235. self._userContexts[index].invokeErrorCaught(error)
  236. }
  237. }
  238. /// Handles a caught error which has traversed the interceptor pipeline.
  239. @usableFromInline
  240. internal func _errorCaught(_ error: Error) {
  241. // We're about to complete, close the pipeline.
  242. self.close()
  243. var unwrappedError: Error
  244. // Unwrap the error, if possible.
  245. if let errorContext = error as? GRPCError.WithContext {
  246. unwrappedError = errorContext.error
  247. self._errorDelegate?.didCatchError(
  248. errorContext.error,
  249. logger: self.logger,
  250. file: errorContext.file,
  251. line: errorContext.line
  252. )
  253. } else {
  254. unwrappedError = error
  255. self._errorDelegate?.didCatchErrorWithoutContext(error, logger: self.logger)
  256. }
  257. // Emit the unwrapped error.
  258. self._onError(unwrappedError)
  259. }
  260. /// Writes a request message into the interceptor pipeline.
  261. ///
  262. /// This should be called by the call object to send requests parts to the transport.
  263. ///
  264. /// - Parameters:
  265. /// - part: The request part to write.
  266. /// - promise: A promise to complete when the request part has been successfully written.
  267. /// - Important: This *must* to be called from the `eventLoop`.
  268. @inlinable
  269. internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  270. self.invokeSend(part, promise: promise, fromContextAtIndex: self._tailIndex)
  271. }
  272. /// Invoke send on the appropriate context when called from the context at the given index.
  273. @inlinable
  274. internal func invokeSend(
  275. _ part: GRPCClientRequestPart<Request>,
  276. promise: EventLoopPromise<Void>?,
  277. fromContextAtIndex index: Int
  278. ) {
  279. self._invokeSend(
  280. part,
  281. promise: promise,
  282. onContextAtIndex: self._nextOutboundIndex(after: index)
  283. )
  284. }
  285. /// Invoke send on the context at the given index, if it exists and the pipeline is still open.
  286. @inlinable
  287. internal func _invokeSend(
  288. _ part: GRPCClientRequestPart<Request>,
  289. promise: EventLoopPromise<Void>?,
  290. onContextAtIndex index: Int
  291. ) {
  292. self.eventLoop.assertInEventLoop()
  293. assert(self._indexIsValid(index))
  294. guard self._isOpen else {
  295. promise?.fail(GRPCError.AlreadyComplete())
  296. return
  297. }
  298. self._invokeSend(part, promise: promise, onContextAtUncheckedIndex: index)
  299. }
  300. /// Invoke send on the context at the given index assuming the index exists and the pipeline is
  301. /// still open.
  302. @inlinable
  303. internal func _invokeSend(
  304. _ part: GRPCClientRequestPart<Request>,
  305. promise: EventLoopPromise<Void>?,
  306. onContextAtUncheckedIndex index: Int
  307. ) {
  308. switch index {
  309. case self._headIndex:
  310. self._onRequestPart(part, promise)
  311. case self._tailIndex:
  312. self._invokeSend(
  313. part,
  314. promise: promise,
  315. onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
  316. )
  317. default:
  318. self._userContexts[index].invokeSend(part, promise: promise)
  319. }
  320. }
  321. /// Send a request to cancel the RPC through the interceptor pipeline.
  322. ///
  323. /// This should be called by the call object when attempting to cancel the RPC.
  324. ///
  325. /// - Parameter promise: A promise to complete when the cancellation request has been handled.
  326. /// - Important: This *must* to be called from the `eventLoop`.
  327. @inlinable
  328. internal func cancel(promise: EventLoopPromise<Void>?) {
  329. self.invokeCancel(promise: promise, fromContextAtIndex: self._tailIndex)
  330. }
  331. /// Invoke `cancel` on the appropriate context when called from the context at the given index.
  332. @inlinable
  333. internal func invokeCancel(promise: EventLoopPromise<Void>?, fromContextAtIndex index: Int) {
  334. self._invokeCancel(promise: promise, onContextAtIndex: self._nextOutboundIndex(after: index))
  335. }
  336. /// Invoke `cancel` on the context at the given index if the index is valid and the pipeline is
  337. /// still open.
  338. @inlinable
  339. internal func _invokeCancel(
  340. promise: EventLoopPromise<Void>?,
  341. onContextAtIndex index: Int
  342. ) {
  343. self.eventLoop.assertInEventLoop()
  344. assert(self._indexIsValid(index))
  345. guard self._isOpen else {
  346. promise?.fail(GRPCError.AlreadyComplete())
  347. return
  348. }
  349. self._invokeCancel(promise: promise, onContextAtUncheckedIndex: index)
  350. }
  351. /// Invoke `cancel` on the context at the given index assuming the index is valid and the
  352. /// pipeline is still open.
  353. @inlinable
  354. internal func _invokeCancel(
  355. promise: EventLoopPromise<Void>?,
  356. onContextAtUncheckedIndex index: Int
  357. ) {
  358. switch index {
  359. case self._headIndex:
  360. self._onCancel(promise)
  361. case self._tailIndex:
  362. self._invokeCancel(
  363. promise: promise,
  364. onContextAtUncheckedIndex: self._nextOutboundIndex(after: index)
  365. )
  366. default:
  367. self._userContexts[index].invokeCancel(promise: promise)
  368. }
  369. }
  370. }
  371. // MARK: - Lifecycle
  372. extension ClientInterceptorPipeline {
  373. /// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
  374. /// the RPC has completed.
  375. /// - Important: This *must* to be called from the `eventLoop`.
  376. @inlinable
  377. internal func close() {
  378. self.eventLoop.assertInEventLoop()
  379. self._isOpen = false
  380. // Cancel the timeout.
  381. self._scheduledClose?.cancel()
  382. self._scheduledClose = nil
  383. // Cancel the transport.
  384. self._onCancel(nil)
  385. }
  386. /// Sets up a deadline for the pipeline.
  387. @inlinable
  388. internal func _setupDeadline() {
  389. func setup() {
  390. self.eventLoop.assertInEventLoop()
  391. let timeLimit = self.details.options.timeLimit
  392. let deadline = timeLimit.makeDeadline()
  393. // There's no point scheduling this.
  394. if deadline == .distantFuture {
  395. return
  396. }
  397. self._scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
  398. // When the error hits the tail we'll call 'close()', this will cancel the transport if
  399. // necessary.
  400. self.errorCaught(GRPCError.RPCTimedOut(timeLimit))
  401. }
  402. }
  403. if self.eventLoop.inEventLoop {
  404. setup()
  405. } else {
  406. self.eventLoop.execute {
  407. setup()
  408. }
  409. }
  410. }
  411. }
  412. extension ClientInterceptorContext {
  413. @inlinable
  414. internal func invokeReceive(_ part: GRPCClientResponsePart<Response>) {
  415. self.interceptor.receive(part, context: self)
  416. }
  417. @inlinable
  418. internal func invokeSend(
  419. _ part: GRPCClientRequestPart<Request>,
  420. promise: EventLoopPromise<Void>?
  421. ) {
  422. self.interceptor.send(part, promise: promise, context: self)
  423. }
  424. @inlinable
  425. internal func invokeCancel(promise: EventLoopPromise<Void>?) {
  426. self.interceptor.cancel(promise: promise, context: self)
  427. }
  428. @inlinable
  429. internal func invokeErrorCaught(_ error: Error) {
  430. self.interceptor.errorCaught(error, context: self)
  431. }
  432. }