ResponsePartContainer.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2020, 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 NIO
  17. import NIOHPACK
  18. /// A container for RPC response parts.
  19. internal struct ResponsePartContainer<Response> {
  20. /// The type of handler for response message part.
  21. enum ResponseHandler {
  22. case unary(EventLoopPromise<Response>)
  23. case stream((Response) -> Void)
  24. }
  25. var lazyInitialMetadataPromise: LazyEventLoopPromise<HPACKHeaders>
  26. /// A handler for response messages.
  27. let responseHandler: ResponseHandler
  28. /// A promise for the trailing metadata.
  29. var lazyTrailingMetadataPromise: LazyEventLoopPromise<HPACKHeaders>
  30. /// A promise for the call status.
  31. var lazyStatusPromise: LazyEventLoopPromise<GRPCStatus>
  32. /// Fail all promises - except for the status promise - with the given error status. Succeed the
  33. /// status promise.
  34. mutating func fail(with error: Error, status: GRPCStatus) {
  35. self.lazyInitialMetadataPromise.fail(error)
  36. switch self.responseHandler {
  37. case let .unary(response):
  38. response.fail(error)
  39. case .stream:
  40. ()
  41. }
  42. self.lazyTrailingMetadataPromise.fail(error)
  43. // We always succeed the status.
  44. self.lazyStatusPromise.succeed(status)
  45. }
  46. /// Make a response container for a unary response.
  47. init(eventLoop: EventLoop, unaryResponsePromise: EventLoopPromise<Response>) {
  48. self.lazyInitialMetadataPromise = eventLoop.makeLazyPromise()
  49. self.lazyTrailingMetadataPromise = eventLoop.makeLazyPromise()
  50. self.lazyStatusPromise = eventLoop.makeLazyPromise()
  51. self.responseHandler = .unary(unaryResponsePromise)
  52. }
  53. /// Make a response container for a response which is streamed.
  54. init(eventLoop: EventLoop, streamingResponseHandler: @escaping (Response) -> Void) {
  55. self.lazyInitialMetadataPromise = eventLoop.makeLazyPromise()
  56. self.lazyTrailingMetadataPromise = eventLoop.makeLazyPromise()
  57. self.lazyStatusPromise = eventLoop.makeLazyPromise()
  58. self.responseHandler = .stream(streamingResponseHandler)
  59. }
  60. }