RPCRouter.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /*
  2. * Copyright 2023, 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. /// Stores and provides handlers for RPCs.
  17. ///
  18. /// The router stores a handler for each RPC it knows about. Each handler encapsulate the business
  19. /// logic for the RPC which is typically implemented by service owners. To register a handler you
  20. /// can call ``registerHandler(forMethod:deserializer:serializer:handler:)``. You can check whether
  21. /// the router has a handler for a method with ``hasHandler(forMethod:)`` or get a list of all
  22. /// methods with handlers registered by calling ``methods``. You can also remove the handler for a
  23. /// given method by calling ``removeHandler(forMethod:)``.
  24. ///
  25. /// In most cases you won't need to interact with the router directly. Instead you should register
  26. /// your services with ``GRPCServer/init(transport:services:interceptors:)`` which will in turn
  27. /// register each method with the router.
  28. ///
  29. /// You may wish to not serve all methods from your service in which case you can either:
  30. ///
  31. /// 1. Remove individual methods by calling ``removeHandler(forMethod:)``, or
  32. /// 2. Implement ``RegistrableRPCService/registerMethods(with:)`` to register only the methods you
  33. /// want to be served.
  34. public struct RPCRouter: Sendable {
  35. @usableFromInline
  36. struct RPCHandler: Sendable {
  37. @usableFromInline
  38. let _fn:
  39. @Sendable (
  40. _ stream: RPCStream<
  41. RPCAsyncSequence<RPCRequestPart, any Error>,
  42. RPCWriter<RPCResponsePart>.Closable
  43. >,
  44. _ context: ServerContext,
  45. _ interceptors: [any ServerInterceptor]
  46. ) async -> Void
  47. @inlinable
  48. init<Input, Output>(
  49. method: MethodDescriptor,
  50. deserializer: some MessageDeserializer<Input>,
  51. serializer: some MessageSerializer<Output>,
  52. handler: @Sendable @escaping (
  53. _ request: StreamingServerRequest<Input>,
  54. _ context: ServerContext
  55. ) async throws -> StreamingServerResponse<Output>
  56. ) {
  57. self._fn = { stream, context, interceptors in
  58. await ServerRPCExecutor.execute(
  59. context: context,
  60. stream: stream,
  61. deserializer: deserializer,
  62. serializer: serializer,
  63. interceptors: interceptors,
  64. handler: handler
  65. )
  66. }
  67. }
  68. @inlinable
  69. func handle(
  70. stream: RPCStream<
  71. RPCAsyncSequence<RPCRequestPart, any Error>,
  72. RPCWriter<RPCResponsePart>.Closable
  73. >,
  74. context: ServerContext,
  75. interceptors: [any ServerInterceptor]
  76. ) async {
  77. await self._fn(stream, context, interceptors)
  78. }
  79. }
  80. @usableFromInline
  81. private(set) var handlers: [MethodDescriptor: RPCHandler]
  82. /// Creates a new router with no methods registered.
  83. public init() {
  84. self.handlers = [:]
  85. }
  86. /// Returns all descriptors known to the router in an undefined order.
  87. public var methods: [MethodDescriptor] {
  88. Array(self.handlers.keys)
  89. }
  90. /// Returns the number of methods registered with the router.
  91. public var count: Int {
  92. self.handlers.count
  93. }
  94. /// Returns whether a handler exists for a given method.
  95. ///
  96. /// - Parameter descriptor: A descriptor of the method.
  97. /// - Returns: Whether a handler exists for the method.
  98. public func hasHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  99. return self.handlers.keys.contains(descriptor)
  100. }
  101. /// Registers a handler with the router.
  102. ///
  103. /// - Note: if a handler already exists for a given method then it will be replaced.
  104. ///
  105. /// - Parameters:
  106. /// - descriptor: A descriptor for the method to register a handler for.
  107. /// - deserializer: A deserializer to deserialize input messages received from the client.
  108. /// - serializer: A serializer to serialize output messages to send to the client.
  109. /// - handler: The function which handles the request and returns a response.
  110. @inlinable
  111. public mutating func registerHandler<Input: Sendable, Output: Sendable>(
  112. forMethod descriptor: MethodDescriptor,
  113. deserializer: some MessageDeserializer<Input>,
  114. serializer: some MessageSerializer<Output>,
  115. handler: @Sendable @escaping (
  116. _ request: StreamingServerRequest<Input>,
  117. _ context: ServerContext
  118. ) async throws -> StreamingServerResponse<Output>
  119. ) {
  120. self.handlers[descriptor] = RPCHandler(
  121. method: descriptor,
  122. deserializer: deserializer,
  123. serializer: serializer,
  124. handler: handler
  125. )
  126. }
  127. /// Removes any handler registered for the specified method.
  128. ///
  129. /// - Parameter descriptor: A descriptor of the method to remove a handler for.
  130. /// - Returns: Whether a handler was removed.
  131. @discardableResult
  132. public mutating func removeHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  133. return self.handlers.removeValue(forKey: descriptor) != nil
  134. }
  135. }
  136. extension RPCRouter {
  137. internal func handle(
  138. stream: RPCStream<
  139. RPCAsyncSequence<RPCRequestPart, any Error>,
  140. RPCWriter<RPCResponsePart>.Closable
  141. >,
  142. context: ServerContext,
  143. interceptors: [any ServerInterceptor]
  144. ) async {
  145. if let handler = self.handlers[stream.descriptor] {
  146. await handler.handle(stream: stream, context: context, interceptors: interceptors)
  147. } else {
  148. // If this throws then the stream must be closed which we can't do anything about, so ignore
  149. // any error.
  150. try? await stream.outbound.write(.status(.rpcNotImplemented, [:]))
  151. await stream.outbound.finish()
  152. }
  153. }
  154. }
  155. extension Status {
  156. fileprivate static let rpcNotImplemented = Status(
  157. code: .unimplemented,
  158. message: "Requested RPC isn't implemented by this server."
  159. )
  160. }