ClientInterceptorPipeline.swift 18 KB

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