StreamingResponseCallContext.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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 Logging
  18. import NIO
  19. import NIOHTTP1
  20. import SwiftProtobuf
  21. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  22. ///
  23. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  24. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  25. /// the result of `error.asGRPCStatus()` will be returned to the client.
  26. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  27. open class StreamingResponseCallContext<ResponsePayload>: ServerCallContextBase {
  28. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  29. public let statusPromise: EventLoopPromise<GRPCStatus>
  30. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  31. self.statusPromise = eventLoop.makePromise()
  32. super.init(eventLoop: eventLoop, request: request, logger: logger)
  33. }
  34. /// Send a response to the client.
  35. ///
  36. /// - Parameter message: The message to send to the client.
  37. /// - Parameter compression: Whether compression should be used for this response. If compression
  38. /// is enabled in the call context, the value passed here takes precedence. Defaults to deferring
  39. /// to the value set on the call context.
  40. open func sendResponse(_ message: ResponsePayload,
  41. compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  42. fatalError("needs to be overridden")
  43. }
  44. }
  45. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  46. open class StreamingResponseCallContextImpl<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  47. public let channel: Channel
  48. /// - Parameters:
  49. /// - channel: The NIO channel the call is handled on.
  50. /// - request: The headers provided with this call.
  51. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  52. /// sending them to the client.
  53. ///
  54. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  55. public init(
  56. channel: Channel,
  57. request: HTTPRequestHead,
  58. errorDelegate: ServerErrorDelegate?,
  59. logger: Logger
  60. ) {
  61. self.channel = channel
  62. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  63. statusPromise.futureResult
  64. .map {
  65. GRPCStatusAndMetadata(status: $0, metadata: nil)
  66. }
  67. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  68. .recover { [weak errorDelegate] error in
  69. errorDelegate?.observeRequestHandlerError(error, request: request)
  70. if let transformed: GRPCStatusAndMetadata = errorDelegate?.transformRequestHandlerError(
  71. error,
  72. request: request
  73. ) {
  74. return transformed
  75. }
  76. if let grpcStatusTransformable = error as? GRPCStatusTransformable {
  77. return GRPCStatusAndMetadata(
  78. status: grpcStatusTransformable.makeGRPCStatus(),
  79. metadata: nil
  80. )
  81. }
  82. return GRPCStatusAndMetadata(status: .processingError, metadata: nil)
  83. }
  84. // Finish the call by returning the final status.
  85. .whenSuccess { statusAndMetadata in
  86. if let metadata = statusAndMetadata.metadata {
  87. self.trailingMetadata.add(contentsOf: metadata)
  88. }
  89. self.channel.writeAndFlush(
  90. NIOAny(
  91. WrappedResponse
  92. .statusAndTrailers(statusAndMetadata.status, self.trailingMetadata)
  93. ),
  94. promise: nil
  95. )
  96. }
  97. }
  98. override open func sendResponse(
  99. _ message: ResponsePayload,
  100. compression: Compression = .deferToCallDefault
  101. ) -> EventLoopFuture<Void> {
  102. let messageContext = _MessageContext(
  103. message,
  104. compressed: compression.isEnabled(callDefault: self.compressionEnabled)
  105. )
  106. return self.channel.writeAndFlush(NIOAny(WrappedResponse.message(messageContext)))
  107. }
  108. }
  109. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  110. ///
  111. /// Simply records all sent messages.
  112. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  113. open var recordedResponses: [ResponsePayload] = []
  114. override open func sendResponse(
  115. _ message: ResponsePayload,
  116. compression: Compression = .deferToCallDefault
  117. ) -> EventLoopFuture<Void> {
  118. self.recordedResponses.append(message)
  119. return eventLoop.makeSucceededFuture(())
  120. }
  121. }