ServerInterceptorPipeline.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. internal final class ServerInterceptorPipeline<Request, Response> {
  19. /// The `EventLoop` this RPC is being executed on.
  20. internal let eventLoop: EventLoop
  21. /// The path of the RPC in the format "/Service/Method", e.g. "/echo.Echo/Get".
  22. internal let path: String
  23. /// The type of the RPC, e.g. "unary".
  24. internal let type: GRPCCallType
  25. /// A logger.
  26. internal let logger: Logger
  27. /// The contexts associated with the interceptors stored in this pipeline. Contexts will be
  28. /// removed once the RPC has completed. Contexts are ordered from inbound to outbound, that is,
  29. /// the head is first and the tail is last.
  30. private var contexts: [ServerInterceptorContext<Request, Response>]?
  31. /// Returns the next context in the outbound direction for the context at the given index, if one
  32. /// exists.
  33. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next
  34. /// outbound context.
  35. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist.
  36. internal func nextOutboundContext(
  37. forIndex index: Int
  38. ) -> ServerInterceptorContext<Request, Response>? {
  39. return self.context(atIndex: index - 1)
  40. }
  41. /// Returns the next context in the inbound direction for the context at the given index, if one
  42. /// exists.
  43. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next
  44. /// inbound context.
  45. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist.
  46. internal func nextInboundContext(
  47. forIndex index: Int
  48. ) -> ServerInterceptorContext<Request, Response>? {
  49. return self.context(atIndex: index + 1)
  50. }
  51. /// Returns the context for the given index, if one exists.
  52. /// - Parameter index: The index of the `ServerInterceptorContext` to return.
  53. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist for the given index.
  54. private func context(atIndex index: Int) -> ServerInterceptorContext<Request, Response>? {
  55. return self.contexts?[checked: index]
  56. }
  57. /// The context closest to the `NIO.Channel`, i.e. where inbound events originate. This will be
  58. /// `nil` once the RPC has completed.
  59. internal var head: ServerInterceptorContext<Request, Response>? {
  60. return self.contexts?.first
  61. }
  62. /// The context closest to the application, i.e. where outbound events originate. This will be
  63. /// `nil` once the RPC has completed.
  64. internal var tail: ServerInterceptorContext<Request, Response>? {
  65. return self.contexts?.last
  66. }
  67. internal init(
  68. logger: Logger,
  69. eventLoop: EventLoop,
  70. path: String,
  71. callType: GRPCCallType,
  72. interceptors: [ServerInterceptor<Request, Response>],
  73. onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void,
  74. onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  75. ) {
  76. self.logger = logger
  77. self.eventLoop = eventLoop
  78. self.path = path
  79. self.type = callType
  80. // We need space for the head and tail as well as any user provided interceptors.
  81. var contexts: [ServerInterceptorContext<Request, Response>] = []
  82. contexts.reserveCapacity(interceptors.count + 2)
  83. // Start with the head.
  84. contexts.append(
  85. ServerInterceptorContext(
  86. for: .head(for: self, onResponsePart),
  87. atIndex: contexts.count,
  88. in: self
  89. )
  90. )
  91. // User provided interceptors.
  92. for interceptor in interceptors {
  93. contexts.append(
  94. ServerInterceptorContext(
  95. for: .userProvided(interceptor),
  96. atIndex: contexts.count,
  97. in: self
  98. )
  99. )
  100. }
  101. // Now the tail.
  102. contexts.append(
  103. ServerInterceptorContext(
  104. for: .tail(onRequestPart),
  105. atIndex: contexts.count,
  106. in: self
  107. )
  108. )
  109. self.contexts = contexts
  110. }
  111. /// Emit a request part message into the interceptor pipeline.
  112. ///
  113. /// - Parameter part: The part to emit into the pipeline.
  114. /// - Important: This *must* to be called from the `eventLoop`.
  115. internal func receive(_ part: GRPCServerRequestPart<Request>) {
  116. self.eventLoop.assertInEventLoop()
  117. self.head?.invokeReceive(part)
  118. }
  119. /// Write a response message into the interceptor pipeline.
  120. ///
  121. /// - Parameters:
  122. /// - part: The response part to sent.
  123. /// - promise: A promise to complete when the response part has been successfully written.
  124. /// - Important: This *must* to be called from the `eventLoop`.
  125. internal func send(_ part: GRPCServerResponsePart<Response>, promise: EventLoopPromise<Void>?) {
  126. self.eventLoop.assertInEventLoop()
  127. if let tail = self.tail {
  128. tail.invokeSend(part, promise: promise)
  129. } else {
  130. promise?.fail(GRPCError.AlreadyComplete())
  131. }
  132. }
  133. internal func close() {
  134. self.eventLoop.assertInEventLoop()
  135. self.contexts = nil
  136. }
  137. }