2
0

ServerInterceptorPipeline.swift 9.2 KB

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