EchoAsyncProvider.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #if compiler(>=5.6)
  17. import EchoModel
  18. import GRPC
  19. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  20. public final class EchoAsyncProvider: Echo_EchoAsyncProvider {
  21. public let interceptors: Echo_EchoServerInterceptorFactoryProtocol?
  22. public init(interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil) {
  23. self.interceptors = interceptors
  24. }
  25. public func get(
  26. request: Echo_EchoRequest,
  27. context: GRPCAsyncServerCallContext
  28. ) async throws -> Echo_EchoResponse {
  29. return .with {
  30. $0.text = "Swift echo get: " + request.text
  31. }
  32. }
  33. public func expand(
  34. request: Echo_EchoRequest,
  35. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  36. context: GRPCAsyncServerCallContext
  37. ) async throws {
  38. for (i, part) in request.text.components(separatedBy: " ").lazy.enumerated() {
  39. try await responseStream.send(.with { $0.text = "Swift echo expand (\(i)): \(part)" })
  40. }
  41. }
  42. public func collect(
  43. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  44. context: GRPCAsyncServerCallContext
  45. ) async throws -> Echo_EchoResponse {
  46. let text = try await requestStream.reduce(into: "Swift echo collect:") { result, request in
  47. result += " \(request.text)"
  48. }
  49. return .with { $0.text = text }
  50. }
  51. public func update(
  52. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  53. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  54. context: GRPCAsyncServerCallContext
  55. ) async throws {
  56. var counter = 0
  57. for try await request in requestStream {
  58. let text = "Swift echo update (\(counter)): \(request.text)"
  59. try await responseStream.send(.with { $0.text = text })
  60. counter += 1
  61. }
  62. }
  63. }
  64. #endif // compiler(>=5.6)