ServerInterceptorPipeline.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. @usableFromInline
  19. internal final class ServerInterceptorPipeline<Request, Response> {
  20. /// The `EventLoop` this RPC is being executed on.
  21. @usableFromInline
  22. internal let eventLoop: EventLoop
  23. /// The path of the RPC in the format "/Service/Method", e.g. "/echo.Echo/Get".
  24. @usableFromInline
  25. internal let path: String
  26. /// The type of the RPC, e.g. "unary".
  27. @usableFromInline
  28. internal let type: GRPCCallType
  29. /// The remote peer's address.
  30. @usableFromInline
  31. internal let remoteAddress: SocketAddress?
  32. /// A logger.
  33. @usableFromInline
  34. internal let logger: Logger
  35. /// A reference to a 'UserInfo'.
  36. @usableFromInline
  37. internal let userInfoRef: Ref<UserInfo>
  38. /// A future which completes when the call closes. This may be used to register callbacks which
  39. /// free up resources used by the interceptor.
  40. @usableFromInline
  41. internal let closeFuture: EventLoopFuture<Void>
  42. /// Called when a response part has traversed the interceptor pipeline.
  43. @usableFromInline
  44. internal var _onResponsePart:
  45. Optional<
  46. (
  47. GRPCServerResponsePart<Response>,
  48. EventLoopPromise<Void>?
  49. ) -> Void
  50. >
  51. /// Called when a request part has traversed the interceptor pipeline.
  52. @usableFromInline
  53. internal var _onRequestPart: Optional<(GRPCServerRequestPart<Request>) -> Void>
  54. /// The index before the first user interceptor context index. (always -1).
  55. @usableFromInline
  56. internal let _headIndex: Int
  57. /// The index after the last user interceptor context index (i.e. 'userContext.endIndex').
  58. @usableFromInline
  59. internal let _tailIndex: Int
  60. /// Contexts for user provided interceptors.
  61. @usableFromInline
  62. internal var _userContexts: [ServerInterceptorContext<Request, Response>]
  63. /// Whether the interceptor pipeline is still open. It becomes closed after an 'end' response
  64. /// part has traversed the pipeline.
  65. @usableFromInline
  66. internal var _isOpen = true
  67. /// The index of the next context on the inbound side of the context at the given index.
  68. @inlinable
  69. internal func _nextInboundIndex(after index: Int) -> Int {
  70. // Unchecked arithmetic is okay here: our greatest inbound index is '_tailIndex' but we will
  71. // never ask for the inbound index after the tail.
  72. assert(self._indexIsValid(index))
  73. return index &+ 1
  74. }
  75. /// The index of the next context on the outbound side of the context at the given index.
  76. @inlinable
  77. internal func _nextOutboundIndex(after index: Int) -> Int {
  78. // Unchecked arithmetic is okay here: our lowest outbound index is '_headIndex' but we will
  79. // never ask for the outbound index after the head.
  80. assert(self._indexIsValid(index))
  81. return index &- 1
  82. }
  83. /// Returns true of the index is in the range `_headIndex ... _tailIndex`.
  84. @inlinable
  85. internal func _indexIsValid(_ index: Int) -> Bool {
  86. return self._headIndex <= index && index <= self._tailIndex
  87. }
  88. @inlinable
  89. internal init(
  90. logger: Logger,
  91. eventLoop: EventLoop,
  92. path: String,
  93. callType: GRPCCallType,
  94. remoteAddress: SocketAddress?,
  95. userInfoRef: Ref<UserInfo>,
  96. closeFuture: EventLoopFuture<Void>,
  97. interceptors: [ServerInterceptor<Request, Response>],
  98. onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void,
  99. onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  100. ) {
  101. self.logger = logger
  102. self.eventLoop = eventLoop
  103. self.path = path
  104. self.type = callType
  105. self.remoteAddress = remoteAddress
  106. self.userInfoRef = userInfoRef
  107. self.closeFuture = closeFuture
  108. self._onResponsePart = onResponsePart
  109. self._onRequestPart = onRequestPart
  110. // Head comes before user interceptors.
  111. self._headIndex = -1
  112. // Tail comes just after.
  113. self._tailIndex = interceptors.endIndex
  114. // Make some contexts.
  115. self._userContexts = []
  116. self._userContexts.reserveCapacity(interceptors.count)
  117. for index in 0 ..< interceptors.count {
  118. let context = ServerInterceptorContext(for: interceptors[index], atIndex: index, in: self)
  119. self._userContexts.append(context)
  120. }
  121. }
  122. /// Emit a request part message into the interceptor pipeline.
  123. ///
  124. /// - Parameter part: The part to emit into the pipeline.
  125. /// - Important: This *must* to be called from the `eventLoop`.
  126. @inlinable
  127. internal func receive(_ part: GRPCServerRequestPart<Request>) {
  128. self.invokeReceive(part, fromContextAtIndex: self._headIndex)
  129. }
  130. /// Invoke receive on the appropriate context when called from the context at the given index.
  131. @inlinable
  132. internal func invokeReceive(
  133. _ part: GRPCServerRequestPart<Request>,
  134. fromContextAtIndex index: Int
  135. ) {
  136. self._invokeReceive(part, onContextAtIndex: self._nextInboundIndex(after: index))
  137. }
  138. /// Invoke receive on the context at the given index, if doing so is safe.
  139. @inlinable
  140. internal func _invokeReceive(
  141. _ part: GRPCServerRequestPart<Request>,
  142. onContextAtIndex index: Int
  143. ) {
  144. self.eventLoop.assertInEventLoop()
  145. assert(self._indexIsValid(index))
  146. guard self._isOpen else {
  147. return
  148. }
  149. // We've checked the index.
  150. self._invokeReceive(part, onContextAtUncheckedIndex: index)
  151. }
  152. /// Invoke receive on the context at the given index, assuming that the index is valid and the
  153. /// pipeline is still open.
  154. @inlinable
  155. internal func _invokeReceive(
  156. _ part: GRPCServerRequestPart<Request>,
  157. onContextAtUncheckedIndex index: Int
  158. ) {
  159. switch index {
  160. case self._headIndex:
  161. // The next inbound index must exist, either for the tail or a user interceptor.
  162. self._invokeReceive(
  163. part,
  164. onContextAtUncheckedIndex: self._nextInboundIndex(after: self._headIndex)
  165. )
  166. case self._tailIndex:
  167. self._onRequestPart?(part)
  168. default:
  169. self._userContexts[index].invokeReceive(part)
  170. }
  171. }
  172. /// Write a response message into the interceptor pipeline.
  173. ///
  174. /// - Parameters:
  175. /// - part: The response part to sent.
  176. /// - promise: A promise to complete when the response part has been successfully written.
  177. /// - Important: This *must* to be called from the `eventLoop`.
  178. @inlinable
  179. internal func send(_ part: GRPCServerResponsePart<Response>, promise: EventLoopPromise<Void>?) {
  180. self.invokeSend(part, promise: promise, fromContextAtIndex: self._tailIndex)
  181. }
  182. /// Invoke send on the appropriate context when called from the context at the given index.
  183. @inlinable
  184. internal func invokeSend(
  185. _ part: GRPCServerResponsePart<Response>,
  186. promise: EventLoopPromise<Void>?,
  187. fromContextAtIndex index: Int
  188. ) {
  189. self._invokeSend(
  190. part,
  191. promise: promise,
  192. onContextAtIndex: self._nextOutboundIndex(after: index)
  193. )
  194. }
  195. /// Invoke send on the context at the given index, if doing so is safe. Fails the `promise` if it
  196. /// is not safe to do so.
  197. @inlinable
  198. internal func _invokeSend(
  199. _ part: GRPCServerResponsePart<Response>,
  200. promise: EventLoopPromise<Void>?,
  201. onContextAtIndex index: Int
  202. ) {
  203. self.eventLoop.assertInEventLoop()
  204. assert(self._indexIsValid(index))
  205. guard self._isOpen else {
  206. promise?.fail(GRPCError.AlreadyComplete())
  207. return
  208. }
  209. self._invokeSend(uncheckedIndex: index, part, promise: promise)
  210. }
  211. /// Invoke send on the context at the given index, assuming that the index is valid and the
  212. /// pipeline is still open.
  213. @inlinable
  214. internal func _invokeSend(
  215. uncheckedIndex index: Int,
  216. _ part: GRPCServerResponsePart<Response>,
  217. promise: EventLoopPromise<Void>?
  218. ) {
  219. switch index {
  220. case self._headIndex:
  221. let onResponsePart = self._onResponsePart
  222. if part.isEnd {
  223. self.close()
  224. }
  225. onResponsePart?(part, promise)
  226. case self._tailIndex:
  227. // The next outbound index must exist: it will be the head or a user interceptor.
  228. self._invokeSend(
  229. uncheckedIndex: self._nextOutboundIndex(after: self._tailIndex),
  230. part,
  231. promise: promise
  232. )
  233. default:
  234. self._userContexts[index].invokeSend(part, promise: promise)
  235. }
  236. }
  237. @inlinable
  238. internal func close() {
  239. // We're no longer open.
  240. self._isOpen = false
  241. // Each context hold a ref to the pipeline; break the retain cycle.
  242. self._userContexts.removeAll()
  243. // Drop the refs to the server handler.
  244. self._onRequestPart = nil
  245. self._onResponsePart = nil
  246. }
  247. }
  248. extension ServerInterceptorContext {
  249. @inlinable
  250. internal func invokeReceive(_ part: GRPCServerRequestPart<Request>) {
  251. self.interceptor.receive(part, context: self)
  252. }
  253. @inlinable
  254. internal func invokeSend(
  255. _ part: GRPCServerResponsePart<Response>,
  256. promise: EventLoopPromise<Void>?
  257. ) {
  258. self.interceptor.send(part, promise: promise, context: self)
  259. }
  260. }