Call+AsyncRequestStreamWriter.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2021, 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 NIOCore
  17. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  18. extension Call where Request: Sendable, Response: Sendable {
  19. typealias AsyncWriter = NIOAsyncWriter<
  20. (Request, Compression),
  21. GRPCAsyncWriterSinkDelegate<(Request, Compression)>
  22. >
  23. internal func makeRequestStreamWriter()
  24. -> (GRPCAsyncRequestStreamWriter<Request>, AsyncWriter.Sink)
  25. {
  26. let delegate = GRPCAsyncWriterSinkDelegate<(Request, Compression)>(
  27. didYield: { requests in
  28. for (request, compression) in requests {
  29. let compress =
  30. compression
  31. .isEnabled(callDefault: self.options.messageEncoding.enabledForRequests)
  32. // TODO: be smarter about inserting flushes.
  33. // We currently always flush after every write which may trigger more syscalls than necessary.
  34. let metadata = MessageMetadata(compress: compress, flush: true)
  35. self.send(.message(request, metadata), promise: nil)
  36. }
  37. },
  38. didTerminate: { _ in self.send(.end, promise: nil) }
  39. )
  40. let writer = NIOAsyncWriter.makeWriter(isWritable: false, delegate: delegate)
  41. // Start as not-writable; writability will be toggled when the stream comes up.
  42. return (GRPCAsyncRequestStreamWriter<Request>(asyncWriter: writer.writer), writer.sink)
  43. }
  44. }