ServerInterceptorPipeline.swift 9.0 KB

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