BaseCallHandler.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. /// Provides a means for decoding incoming gRPC messages into protobuf objects.
  21. ///
  22. /// Calls through to `processMessage` for individual messages it receives, which needs to be implemented by subclasses.
  23. public class BaseCallHandler<RequestMessage: Message, ResponseMessage: Message>: GRPCCallHandler {
  24. public func makeGRPCServerCodec() -> ChannelHandler { return GRPCServerCodec<RequestMessage, ResponseMessage>() }
  25. /// Called whenever a message has been received.
  26. ///
  27. /// Overridden by subclasses.
  28. public func processMessage(_ message: RequestMessage) throws {
  29. fatalError("needs to be overridden")
  30. }
  31. /// Needs to be implemented by this class so that subclasses can override it.
  32. ///
  33. /// Otherwise, the subclass's implementation will simply never be called (probably because the protocol's default
  34. /// implementation in an extension is being used instead).
  35. public func handlerAdded(context: ChannelHandlerContext) { }
  36. /// Called when the client has half-closed the stream, indicating that they won't send any further data.
  37. ///
  38. /// Overridden by subclasses if the "end-of-stream" event is relevant.
  39. public func endOfStreamReceived() throws { }
  40. /// Whether this handler can still write messages to the client.
  41. private var serverCanWrite = true
  42. /// Called for each error received in `errorCaught(context:error:)`.
  43. private weak var errorDelegate: ServerErrorDelegate?
  44. public init(errorDelegate: ServerErrorDelegate?) {
  45. self.errorDelegate = errorDelegate
  46. }
  47. /// Sends an error status to the client while ensuring that all call context promises are fulfilled.
  48. /// Because only the concrete call subclass knows which promises need to be fulfilled, this method needs to be overridden.
  49. func sendErrorStatus(_ status: GRPCStatus) {
  50. fatalError("needs to be overridden")
  51. }
  52. }
  53. extension BaseCallHandler: ChannelInboundHandler {
  54. public typealias InboundIn = GRPCServerRequestPart<RequestMessage>
  55. /// Passes errors to the user-provided `errorHandler`. After an error has been received an
  56. /// appropriate status is written. Errors which don't conform to `GRPCStatusTransformable`
  57. /// return a status with code `.internalError`.
  58. public func errorCaught(context: ChannelHandlerContext, error: Error) {
  59. errorDelegate?.observeLibraryError(error)
  60. let status = errorDelegate?.transformLibraryError(error)
  61. ?? (error as? GRPCStatusTransformable)?.asGRPCStatus()
  62. ?? .processingError
  63. sendErrorStatus(status)
  64. }
  65. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  66. switch self.unwrapInboundIn(data) {
  67. case .head(let requestHead):
  68. // Head should have been handled by `GRPCChannelHandler`.
  69. self.errorCaught(context: context, error: GRPCError.server(.invalidState("unexpected request head received \(requestHead)")))
  70. case .message(let message):
  71. do {
  72. try processMessage(message)
  73. } catch {
  74. self.errorCaught(context: context, error: error)
  75. }
  76. case .end:
  77. do {
  78. try endOfStreamReceived()
  79. } catch {
  80. self.errorCaught(context: context, error: error)
  81. }
  82. }
  83. }
  84. }
  85. extension BaseCallHandler: ChannelOutboundHandler {
  86. public typealias OutboundIn = GRPCServerResponsePart<ResponseMessage>
  87. public typealias OutboundOut = GRPCServerResponsePart<ResponseMessage>
  88. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  89. guard serverCanWrite else {
  90. promise?.fail(GRPCError.server(.serverNotWritable))
  91. return
  92. }
  93. // We can only write one status; make sure we don't write again.
  94. if case .status = unwrapOutboundIn(data) {
  95. serverCanWrite = false
  96. context.writeAndFlush(data, promise: promise)
  97. } else {
  98. context.write(data, promise: promise)
  99. }
  100. }
  101. }