MinimalEchoProvider.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 GRPC
  17. import NIOCore
  18. /// The echo provider that comes with the example does some string processing, we'll avoid some of
  19. /// that here so we're looking at the right things.
  20. public class MinimalEchoProvider: Echo_EchoProvider {
  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: StatusOnlyCallContext
  28. ) -> EventLoopFuture<Echo_EchoResponse> {
  29. return context.eventLoop.makeSucceededFuture(.with { $0.text = request.text })
  30. }
  31. public func expand(
  32. request: Echo_EchoRequest,
  33. context: StreamingResponseCallContext<Echo_EchoResponse>
  34. ) -> EventLoopFuture<GRPCStatus> {
  35. for part in request.text.utf8.split(separator: UInt8(ascii: " ")) {
  36. context.sendResponse(.with { $0.text = String(part)! }, promise: nil)
  37. }
  38. return context.eventLoop.makeSucceededFuture(.ok)
  39. }
  40. public func collect(
  41. context: UnaryResponseCallContext<Echo_EchoResponse>
  42. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  43. var parts: [String] = []
  44. func onEvent(_ event: StreamEvent<Echo_EchoRequest>) {
  45. switch event {
  46. case let .message(request):
  47. parts.append(request.text)
  48. case .end:
  49. context.responsePromise.succeed(.with { $0.text = parts.joined(separator: " ") })
  50. }
  51. }
  52. return context.eventLoop.makeSucceededFuture(onEvent(_:))
  53. }
  54. public func update(
  55. context: StreamingResponseCallContext<Echo_EchoResponse>
  56. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  57. func onEvent(_ event: StreamEvent<Echo_EchoRequest>) {
  58. switch event {
  59. case let .message(request):
  60. context.sendResponse(.with { $0.text = request.text }, promise: nil)
  61. case .end:
  62. context.statusPromise.succeed(.ok)
  63. }
  64. }
  65. return context.eventLoop.makeSucceededFuture(onEvent(_:))
  66. }
  67. }