StreamingResponseCallContext.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Foundation
  2. import SwiftProtobuf
  3. import NIO
  4. import NIOHTTP1
  5. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  6. ///
  7. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  8. /// - If `statusPromise` is failed and the error is of type `GRPCStatus`, that error will be returned to the client.
  9. /// - For other errors, `GRPCStatus.processingError` is returned to the client.
  10. open class StreamingResponseCallContext<ResponseMessage: Message>: ServerCallContextBase {
  11. public typealias WrappedResponse = GRPCServerResponsePart<ResponseMessage>
  12. public let statusPromise: EventLoopPromise<GRPCStatus>
  13. public override init(eventLoop: EventLoop, request: HTTPRequestHead) {
  14. self.statusPromise = eventLoop.newPromise()
  15. super.init(eventLoop: eventLoop, request: request)
  16. }
  17. open func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  18. fatalError("needs to be overridden")
  19. }
  20. }
  21. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  22. open class StreamingResponseCallContextImpl<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  23. public let channel: Channel
  24. public init(channel: Channel, request: HTTPRequestHead) {
  25. self.channel = channel
  26. super.init(eventLoop: channel.eventLoop, request: request)
  27. statusPromise.futureResult
  28. // Ensure that any error provided is of type `GRPCStatus`, using "internal server error" as a fallback.
  29. .mapIfError { error in
  30. (error as? GRPCStatus) ?? .processingError
  31. }
  32. // Finish the call by returning the final status.
  33. .whenSuccess {
  34. self.channel.writeAndFlush(NIOAny(WrappedResponse.status($0)), promise: nil)
  35. }
  36. }
  37. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  38. let promise: EventLoopPromise<Void> = eventLoop.newPromise()
  39. channel.writeAndFlush(NIOAny(WrappedResponse.message(message)), promise: promise)
  40. return promise.futureResult
  41. }
  42. }
  43. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  44. ///
  45. /// Simply records all sent messages.
  46. open class StreamingResponseCallContextTestStub<ResponseMessage: Message>: StreamingResponseCallContext<ResponseMessage> {
  47. open var recordedResponses: [ResponseMessage] = []
  48. open override func sendResponse(_ message: ResponseMessage) -> EventLoopFuture<Void> {
  49. recordedResponses.append(message)
  50. return eventLoop.newSucceededFuture(result: ())
  51. }
  52. }