ClientInterceptorPipeline.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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: [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. // We know we'll have at least a head and a tail as well as any user provided interceptors.
  127. var contexts: [ClientInterceptorContext<Request, Response>] = []
  128. contexts.reserveCapacity(interceptors.count + 2)
  129. // Start with the tail.
  130. contexts.append(
  131. ClientInterceptorContext(
  132. for: .tail(
  133. for: self,
  134. errorDelegate: errorDelegate,
  135. onError: onError,
  136. onResponsePart: onResponsePart
  137. ),
  138. atIndex: contexts.count,
  139. in: self
  140. )
  141. )
  142. // Now the user interceptors.
  143. for interceptor in interceptors {
  144. contexts.append(
  145. ClientInterceptorContext(
  146. for: .userProvided(interceptor),
  147. atIndex: contexts.count,
  148. in: self
  149. )
  150. )
  151. }
  152. // Finally, the head.
  153. contexts.append(
  154. ClientInterceptorContext(
  155. for: .head(onCancel: onCancel, onRequestPart: onRequestPart),
  156. atIndex: contexts.count,
  157. in: self
  158. )
  159. )
  160. self.contexts = contexts
  161. self.setupDeadline()
  162. }
  163. /// Emit a response part message into the interceptor pipeline.
  164. ///
  165. /// This should be called by the transport layer when receiving a response part from the server.
  166. ///
  167. /// - Parameter part: The part to emit into the pipeline.
  168. /// - Important: This *must* to be called from the `eventLoop`.
  169. internal func receive(_ part: GRPCClientResponsePart<Response>) {
  170. self.eventLoop.assertInEventLoop()
  171. self._head?.invokeReceive(part)
  172. }
  173. /// Emit an error into the interceptor pipeline.
  174. ///
  175. /// This should be called by the transport layer when receiving an error.
  176. ///
  177. /// - Parameter error: The error to emit.
  178. /// - Important: This *must* to be called from the `eventLoop`.
  179. internal func errorCaught(_ error: Error) {
  180. self.eventLoop.assertInEventLoop()
  181. self._head?.invokeErrorCaught(error)
  182. }
  183. /// Writes a request message into the interceptor pipeline.
  184. ///
  185. /// This should be called by the call object to send requests parts to the transport.
  186. ///
  187. /// - Parameters:
  188. /// - part: The request part to write.
  189. /// - promise: A promise to complete when the request part has been successfully written.
  190. /// - Important: This *must* to be called from the `eventLoop`.
  191. @inlinable
  192. internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  193. self.eventLoop.assertInEventLoop()
  194. if let tail = self._tail {
  195. tail.invokeSend(part, promise: promise)
  196. } else {
  197. promise?.fail(GRPCError.AlreadyComplete())
  198. }
  199. }
  200. /// Send a request to cancel the RPC through the interceptor pipeline.
  201. ///
  202. /// This should be called by the call object when attempting to cancel the RPC.
  203. ///
  204. /// - Parameter promise: A promise to complete when the cancellation request has been handled.
  205. /// - Important: This *must* to be called from the `eventLoop`.
  206. internal func cancel(promise: EventLoopPromise<Void>?) {
  207. self.eventLoop.assertInEventLoop()
  208. if let tail = self._tail {
  209. tail.invokeCancel(promise: promise)
  210. } else {
  211. promise?.fail(GRPCError.AlreadyComplete())
  212. }
  213. }
  214. }
  215. // MARK: - Lifecycle
  216. extension ClientInterceptorPipeline {
  217. /// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
  218. /// the RPC has completed.
  219. /// - Important: This *must* to be called from the `eventLoop`.
  220. internal func close() {
  221. self.eventLoop.assertInEventLoop()
  222. // Grab the head, we'll use it to cancel the transport. This is most likely already closed,
  223. // but there's nothing to stop an interceptor from emitting its own error and leaving the
  224. // transport open.
  225. let head = self._head
  226. self.contexts = nil
  227. // Cancel the timeout.
  228. self.scheduledClose?.cancel()
  229. self.scheduledClose = nil
  230. // Cancel the transport.
  231. head?.invokeCancel(promise: nil)
  232. }
  233. /// Sets up a deadline for the pipeline.
  234. private func setupDeadline() {
  235. if self.eventLoop.inEventLoop {
  236. self._setupDeadline()
  237. } else {
  238. self.eventLoop.execute {
  239. self._setupDeadline()
  240. }
  241. }
  242. }
  243. /// Sets up a deadline for the pipeline.
  244. /// - Important: This *must* to be called from the `eventLoop`.
  245. private func _setupDeadline() {
  246. self.eventLoop.assertInEventLoop()
  247. let timeLimit = self.details.options.timeLimit
  248. let deadline = timeLimit.makeDeadline()
  249. // There's no point scheduling this.
  250. if deadline == .distantFuture {
  251. return
  252. }
  253. self.scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
  254. // When the error hits the tail we'll call 'close()', this will cancel the transport if
  255. // necessary.
  256. self.errorCaught(GRPCError.RPCTimedOut(timeLimit))
  257. }
  258. }
  259. }