StreamingResponseCallContext.swift 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  21. ///
  22. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  23. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  24. /// the result of `error.asGRPCStatus()` will be returned to the client.
  25. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  26. open class StreamingResponseCallContext<ResponseMessage: Message>: ServerCallContextBase {
  27. public typealias WrappedResponse = GRPCServerResponsePart<ResponseMessage>
  28. public let statusPromise: EventLoopPromise<GRPCStatus>
  29. public override init(eventLoop: EventLoop, request: HTTPRequestHead) {
  30. self.statusPromise = eventLoop.makePromise()
  31. super.init(eventLoop: eventLoop, request: request)
  32. }
  33. open func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  34. fatalError("needs to be overridden")
  35. }
  36. }
  37. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  38. open class StreamingResponseCallContextImpl<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  39. public let channel: Channel
  40. /// - Parameters:
  41. /// - channel: The NIO channel the call is handled on.
  42. /// - request: The headers provided with this call.
  43. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  44. /// sending them to the client.
  45. ///
  46. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  47. public init(channel: Channel, request: HTTPRequestHead, errorDelegate: ServerErrorDelegate?) {
  48. self.channel = channel
  49. super.init(eventLoop: channel.eventLoop, request: request)
  50. statusPromise.futureResult
  51. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  52. .recover { [weak errorDelegate] error in
  53. errorDelegate?.observeRequestHandlerError(error, request: request)
  54. return errorDelegate?.transformRequestHandlerError(error, request: request)
  55. ?? (error as? GRPCStatusTransformable)?.asGRPCStatus()
  56. ?? .processingError
  57. }
  58. // Finish the call by returning the final status.
  59. .whenSuccess {
  60. self.channel.writeAndFlush(NIOAny(WrappedResponse.status($0)), promise: nil)
  61. }
  62. }
  63. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  64. let promise: EventLoopPromise<Void> = eventLoop.makePromise()
  65. channel.writeAndFlush(NIOAny(WrappedResponse.message(message)), promise: promise)
  66. return promise.futureResult
  67. }
  68. }
  69. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  70. ///
  71. /// Simply records all sent messages.
  72. open class StreamingResponseCallContextTestStub<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  73. open var recordedResponses: [ResponseMessage] = []
  74. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  75. recordedResponses.append(message)
  76. return eventLoop.makeSucceededFuture(())
  77. }
  78. }