RPCRouter.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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/Services-swift.struct/register(_:)`` which will in turn register
  27. /// 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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  35. public struct RPCRouter: Sendable {
  36. @usableFromInline
  37. struct RPCHandler: Sendable {
  38. @usableFromInline
  39. let _fn:
  40. @Sendable (
  41. _ stream: RPCStream<
  42. RPCAsyncSequence<RPCRequestPart, any Error>,
  43. RPCWriter<RPCResponsePart>.Closable
  44. >,
  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: ServerRequest.Stream<Input>
  54. ) async throws -> ServerResponse.Stream<Output>
  55. ) {
  56. self._fn = { stream, interceptors in
  57. await ServerRPCExecutor.execute(
  58. stream: stream,
  59. deserializer: deserializer,
  60. serializer: serializer,
  61. interceptors: interceptors,
  62. handler: handler
  63. )
  64. }
  65. }
  66. @inlinable
  67. func handle(
  68. stream: RPCStream<
  69. RPCAsyncSequence<RPCRequestPart, any Error>,
  70. RPCWriter<RPCResponsePart>.Closable
  71. >,
  72. interceptors: [any ServerInterceptor]
  73. ) async {
  74. await self._fn(stream, interceptors)
  75. }
  76. }
  77. @usableFromInline
  78. private(set) var handlers: [MethodDescriptor: RPCHandler]
  79. /// Creates a new router with no methods registered.
  80. public init() {
  81. self.handlers = [:]
  82. }
  83. /// Returns all descriptors known to the router in an undefined order.
  84. public var methods: [MethodDescriptor] {
  85. Array(self.handlers.keys)
  86. }
  87. /// Returns the number of methods registered with the router.
  88. public var count: Int {
  89. self.handlers.count
  90. }
  91. /// Returns whether a handler exists for a given method.
  92. ///
  93. /// - Parameter descriptor: A descriptor of the method.
  94. /// - Returns: Whether a handler exists for the method.
  95. public func hasHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  96. return self.handlers.keys.contains(descriptor)
  97. }
  98. /// Registers a handler with the router.
  99. ///
  100. /// - Note: if a handler already exists for a given method then it will be replaced.
  101. ///
  102. /// - Parameters:
  103. /// - descriptor: A descriptor for the method to register a handler for.
  104. /// - deserializer: A deserializer to deserialize input messages received from the client.
  105. /// - serializer: A serializer to serialize output messages to send to the client.
  106. /// - handler: The function which handles the request and returns a response.
  107. @inlinable
  108. public mutating func registerHandler<Input: Sendable, Output: Sendable>(
  109. forMethod descriptor: MethodDescriptor,
  110. deserializer: some MessageDeserializer<Input>,
  111. serializer: some MessageSerializer<Output>,
  112. handler: @Sendable @escaping (
  113. _ request: ServerRequest.Stream<Input>
  114. ) async throws -> ServerResponse.Stream<Output>
  115. ) {
  116. self.handlers[descriptor] = RPCHandler(
  117. method: descriptor,
  118. deserializer: deserializer,
  119. serializer: serializer,
  120. handler: handler
  121. )
  122. }
  123. /// Removes any handler registered for the specified method.
  124. ///
  125. /// - Parameter descriptor: A descriptor of the method to remove a handler for.
  126. /// - Returns: Whether a handler was removed.
  127. @discardableResult
  128. public mutating func removeHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  129. return self.handlers.removeValue(forKey: descriptor) != nil
  130. }
  131. }
  132. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  133. extension RPCRouter {
  134. internal func handle(
  135. stream: RPCStream<
  136. RPCAsyncSequence<RPCRequestPart, any Error>,
  137. RPCWriter<RPCResponsePart>.Closable
  138. >,
  139. interceptors: [any ServerInterceptor]
  140. ) async {
  141. if let handler = self.handlers[stream.descriptor] {
  142. await handler.handle(stream: stream, interceptors: interceptors)
  143. } else {
  144. // If this throws then the stream must be closed which we can't do anything about, so ignore
  145. // any error.
  146. try? await stream.outbound.write(.status(.rpcNotImplemented, [:]))
  147. stream.outbound.finish()
  148. }
  149. }
  150. }
  151. extension Status {
  152. fileprivate static let rpcNotImplemented = Status(
  153. code: .unimplemented,
  154. message: "Requested RPC isn't implemented by this server."
  155. )
  156. }