ClientInterceptorPipeline.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. internal let details: CallDetails
  70. /// A task for closing the RPC in case of a timeout.
  71. private var scheduledClose: Scheduled<Void>?
  72. /// The contexts associated with the interceptors stored in this pipeline. Context will be removed
  73. /// once the RPC has completed. Contexts are ordered from outbound to inbound, that is, the tail
  74. /// is first and the head is last.
  75. private var contexts: InterceptorContextList<ClientInterceptorContext<Request, Response>>?
  76. /// Returns the next context in the outbound direction for the context at the given index, if one
  77. /// exists.
  78. /// - Parameter index: The index of the `ClientInterceptorContext` which is requesting the next
  79. /// outbound context.
  80. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist.
  81. internal func nextOutboundContext(
  82. forIndex index: Int
  83. ) -> ClientInterceptorContext<Request, Response>? {
  84. return self.context(atIndex: index + 1)
  85. }
  86. /// Returns the next context in the inbound direction for the context at the given index, if one
  87. /// exists.
  88. /// - Parameter index: The index of the `ClientInterceptorContext` which is requesting the next
  89. /// inbound context.
  90. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist.
  91. internal func nextInboundContext(
  92. forIndex index: Int
  93. ) -> ClientInterceptorContext<Request, Response>? {
  94. return self.context(atIndex: index - 1)
  95. }
  96. /// Returns the context for the given index, if one exists.
  97. /// - Parameter index: The index of the `ClientInterceptorContext` to return.
  98. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist for the given index.
  99. private func context(atIndex index: Int) -> ClientInterceptorContext<Request, Response>? {
  100. return self.contexts?[checked: index]
  101. }
  102. /// The context closest to the `NIO.Channel`, i.e. where inbound events originate. This will be
  103. /// `nil` once the RPC has completed.
  104. @usableFromInline
  105. internal var _head: ClientInterceptorContext<Request, Response>? {
  106. return self.contexts?.last
  107. }
  108. /// The context closest to the application, i.e. where outbound events originate. This will be
  109. /// `nil` once the RPC has completed.
  110. @usableFromInline
  111. internal var _tail: ClientInterceptorContext<Request, Response>? {
  112. return self.contexts?.first
  113. }
  114. internal init(
  115. eventLoop: EventLoop,
  116. details: CallDetails,
  117. interceptors: [ClientInterceptor<Request, Response>],
  118. errorDelegate: ClientErrorDelegate?,
  119. onError: @escaping (Error) -> Void,
  120. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  121. onRequestPart: @escaping (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
  122. onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
  123. ) {
  124. self.eventLoop = eventLoop
  125. self.details = details
  126. self.contexts = InterceptorContextList(
  127. for: self,
  128. interceptors: interceptors,
  129. errorDelegate: errorDelegate,
  130. onError: onError,
  131. onCancel: onCancel,
  132. onRequestPart: onRequestPart,
  133. onResponsePart: onResponsePart
  134. )
  135. self.setupDeadline()
  136. }
  137. /// Emit a response part message into the interceptor pipeline.
  138. ///
  139. /// This should be called by the transport layer when receiving a response part from the server.
  140. ///
  141. /// - Parameter part: The part to emit into the pipeline.
  142. /// - Important: This *must* to be called from the `eventLoop`.
  143. internal func receive(_ part: GRPCClientResponsePart<Response>) {
  144. self.eventLoop.assertInEventLoop()
  145. self._head?.invokeReceive(part)
  146. }
  147. /// Emit an error into the interceptor pipeline.
  148. ///
  149. /// This should be called by the transport layer when receiving an error.
  150. ///
  151. /// - Parameter error: The error to emit.
  152. /// - Important: This *must* to be called from the `eventLoop`.
  153. internal func errorCaught(_ error: Error) {
  154. self.eventLoop.assertInEventLoop()
  155. self._head?.invokeErrorCaught(error)
  156. }
  157. /// Writes a request message into the interceptor pipeline.
  158. ///
  159. /// This should be called by the call object to send requests parts to the transport.
  160. ///
  161. /// - Parameters:
  162. /// - part: The request part to write.
  163. /// - promise: A promise to complete when the request part has been successfully written.
  164. /// - Important: This *must* to be called from the `eventLoop`.
  165. @inlinable
  166. internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  167. self.eventLoop.assertInEventLoop()
  168. if let tail = self._tail {
  169. tail.invokeSend(part, promise: promise)
  170. } else {
  171. promise?.fail(GRPCError.AlreadyComplete())
  172. }
  173. }
  174. /// Send a request to cancel the RPC through the interceptor pipeline.
  175. ///
  176. /// This should be called by the call object when attempting to cancel the RPC.
  177. ///
  178. /// - Parameter promise: A promise to complete when the cancellation request has been handled.
  179. /// - Important: This *must* to be called from the `eventLoop`.
  180. internal func cancel(promise: EventLoopPromise<Void>?) {
  181. self.eventLoop.assertInEventLoop()
  182. if let tail = self._tail {
  183. tail.invokeCancel(promise: promise)
  184. } else {
  185. promise?.fail(GRPCError.AlreadyComplete())
  186. }
  187. }
  188. }
  189. // MARK: - Lifecycle
  190. extension ClientInterceptorPipeline {
  191. /// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
  192. /// the RPC has completed.
  193. /// - Important: This *must* to be called from the `eventLoop`.
  194. internal func close() {
  195. self.eventLoop.assertInEventLoop()
  196. // Grab the head, we'll use it to cancel the transport. This is most likely already closed,
  197. // but there's nothing to stop an interceptor from emitting its own error and leaving the
  198. // transport open.
  199. let head = self._head
  200. self.contexts = nil
  201. // Cancel the timeout.
  202. self.scheduledClose?.cancel()
  203. self.scheduledClose = nil
  204. // Cancel the transport.
  205. head?.invokeCancel(promise: nil)
  206. }
  207. /// Sets up a deadline for the pipeline.
  208. private func setupDeadline() {
  209. if self.eventLoop.inEventLoop {
  210. self._setupDeadline()
  211. } else {
  212. self.eventLoop.execute {
  213. self._setupDeadline()
  214. }
  215. }
  216. }
  217. /// Sets up a deadline for the pipeline.
  218. /// - Important: This *must* to be called from the `eventLoop`.
  219. private func _setupDeadline() {
  220. self.eventLoop.assertInEventLoop()
  221. let timeLimit = self.details.options.timeLimit
  222. let deadline = timeLimit.makeDeadline()
  223. // There's no point scheduling this.
  224. if deadline == .distantFuture {
  225. return
  226. }
  227. self.scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
  228. // When the error hits the tail we'll call 'close()', this will cancel the transport if
  229. // necessary.
  230. self.errorCaught(GRPCError.RPCTimedOut(timeLimit))
  231. }
  232. }
  233. }
  234. private extension InterceptorContextList {
  235. init<Request, Response>(
  236. for pipeline: ClientInterceptorPipeline<Request, Response>,
  237. interceptors: [ClientInterceptor<Request, Response>],
  238. errorDelegate: ClientErrorDelegate?,
  239. onError: @escaping (Error) -> Void,
  240. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  241. onRequestPart: @escaping (GRPCClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
  242. onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void
  243. ) where Element == ClientInterceptorContext<Request, Response> {
  244. let middle = interceptors.enumerated().map { index, interceptor in
  245. ClientInterceptorContext(
  246. for: .userProvided(interceptor),
  247. atIndex: index,
  248. in: pipeline
  249. )
  250. }
  251. let first = ClientInterceptorContext<Request, Response>(
  252. for: .tail(
  253. for: pipeline,
  254. errorDelegate: errorDelegate,
  255. onError: onError,
  256. onResponsePart: onResponsePart
  257. ),
  258. atIndex: middle.startIndex - 1,
  259. in: pipeline
  260. )
  261. let last = ClientInterceptorContext<Request, Response>(
  262. for: .head(onCancel: onCancel, onRequestPart: onRequestPart),
  263. atIndex: middle.endIndex,
  264. in: pipeline
  265. )
  266. self.init(first: first, middle: middle, last: last)
  267. }
  268. }