ServerInterceptorPipeline.swift 8.7 KB

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