GRPCChannelHandler.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import SwiftProtobuf
  18. import NIO
  19. import NIOHTTP1
  20. /// Processes individual gRPC messages and stream-close events on a HTTP2 channel.
  21. public protocol GRPCCallHandler: ChannelHandler {
  22. func makeGRPCServerCodec() -> ChannelHandler
  23. }
  24. /// Provides `GRPCCallHandler` objects for the methods on a particular service name.
  25. ///
  26. /// Implemented by the generated code.
  27. public protocol CallHandlerProvider: class {
  28. /// The name of the service this object is providing methods for, including the package path.
  29. ///
  30. /// - Example: "io.grpc.Echo.EchoService"
  31. var serviceName: String { get }
  32. /// Determines, calls and returns the appropriate request handler (`GRPCCallHandler`), depending on the request's
  33. /// method. Returns nil for methods not handled by this service.
  34. func handleMethod(_ methodName: String, request: HTTPRequestHead, serverHandler: GRPCChannelHandler, channel: Channel, errorDelegate: ServerErrorDelegate?) -> GRPCCallHandler?
  35. }
  36. /// Listens on a newly-opened HTTP2 subchannel and yields to the sub-handler matching a call, if available.
  37. ///
  38. /// Once the request headers are available, asks the `CallHandlerProvider` corresponding to the request's service name
  39. /// for an `GRPCCallHandler` object. That object is then forwarded the individual gRPC messages.
  40. public final class GRPCChannelHandler {
  41. private let servicesByName: [String: CallHandlerProvider]
  42. private weak var errorDelegate: ServerErrorDelegate?
  43. public init(servicesByName: [String: CallHandlerProvider], errorDelegate: ServerErrorDelegate?) {
  44. self.servicesByName = servicesByName
  45. self.errorDelegate = errorDelegate
  46. }
  47. }
  48. extension GRPCChannelHandler: ChannelInboundHandler, RemovableChannelHandler {
  49. public typealias InboundIn = RawGRPCServerRequestPart
  50. public typealias OutboundOut = RawGRPCServerResponsePart
  51. public func errorCaught(context: ChannelHandlerContext, error: Error) {
  52. errorDelegate?.observeLibraryError(error)
  53. let status = errorDelegate?.transformLibraryError(error)
  54. ?? (error as? GRPCStatusTransformable)?.asGRPCStatus()
  55. ?? .processingError
  56. context.writeAndFlush(wrapOutboundOut(.status(status)), promise: nil)
  57. }
  58. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  59. let requestPart = self.unwrapInboundIn(data)
  60. switch requestPart {
  61. case .head(let requestHead):
  62. guard let callHandler = getCallHandler(channel: context.channel, requestHead: requestHead) else {
  63. errorCaught(context: context, error: GRPCError.server(.unimplementedMethod(requestHead.uri)))
  64. return
  65. }
  66. let codec = callHandler.makeGRPCServerCodec()
  67. let handlerRemoved: EventLoopPromise<Void> = context.eventLoop.makePromise()
  68. handlerRemoved.futureResult.whenSuccess {
  69. context.pipeline.addHandler(callHandler, position: .after(codec)).whenComplete { _ in
  70. // Send the .headers event back to begin the headers flushing for the response.
  71. // At this point, which headers should be returned is not known, as the content type is
  72. // processed in HTTP1ToRawGRPCServerCodec. At the same time the HTTP1ToRawGRPCServerCodec
  73. // handler doesn't have the data to determine whether headers should be returned, as it is
  74. // this handler that checks whether the stub for the requested Service/Method is implemented.
  75. // This likely signals that the architecture for these handlers could be improved.
  76. context.writeAndFlush(self.wrapOutboundOut(.headers(HTTPHeaders())), promise: nil)
  77. }
  78. }
  79. context.pipeline.addHandler(codec, position: .after(self))
  80. .whenSuccess { context.pipeline.removeHandler(context: context, promise: handlerRemoved) }
  81. case .message, .end:
  82. // We can reach this point if we're receiving messages for a method that isn't implemented.
  83. // A status resposne will have been fired which should also close the stream; there's not a
  84. // lot we can do at this point.
  85. break
  86. }
  87. }
  88. private func getCallHandler(channel: Channel, requestHead: HTTPRequestHead) -> GRPCCallHandler? {
  89. // URI format: "/package.Servicename/MethodName", resulting in the following components separated by a slash:
  90. // - uriComponents[0]: empty
  91. // - uriComponents[1]: service name (including the package name);
  92. // `CallHandlerProvider`s should provide the service name including the package name.
  93. // - uriComponents[2]: method name.
  94. let uriComponents = requestHead.uri.components(separatedBy: "/")
  95. guard uriComponents.count >= 3 && uriComponents[0].isEmpty,
  96. let providerForServiceName = servicesByName[uriComponents[1]],
  97. let callHandler = providerForServiceName.handleMethod(uriComponents[2], request: requestHead, serverHandler: self, channel: channel, errorDelegate: errorDelegate) else {
  98. return nil
  99. }
  100. return callHandler
  101. }
  102. }