ClientCallServerStreaming.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2018, 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 Dispatch
  17. import Foundation
  18. import SwiftProtobuf
  19. public protocol ClientCallServerStreaming: ClientCall {
  20. // TODO: Move the other, message type-dependent, methods into this protocol. At the moment, this is not possible,
  21. // as the protocol would then have an associated type requirement (and become pretty much unusable in the process).
  22. }
  23. open class ClientCallServerStreamingBase<InputType: Message, OutputType: Message>: ClientCallBase, ClientCallServerStreaming, StreamReceiving {
  24. public typealias ReceivedType = OutputType
  25. /// Call this once with the message to send. Nonblocking.
  26. public func start(request: InputType, metadata: Metadata, completion: ((CallResult) -> Void)?) throws -> Self {
  27. let requestData = try request.serializedData()
  28. try call.start(.serverStreaming,
  29. metadata: metadata,
  30. message: requestData,
  31. completion: completion)
  32. return self
  33. }
  34. }
  35. /// Simple fake implementation of ClientCallServerStreamingBase that returns a previously-defined set of results.
  36. open class ClientCallServerStreamingTestStub<OutputType: Message>: ClientCallServerStreaming {
  37. open class var method: String { fatalError("needs to be overridden") }
  38. open var lock = Mutex()
  39. open var outputs: [OutputType] = []
  40. public init() {}
  41. open func _receive(timeout: DispatchTime) throws -> OutputType? {
  42. return lock.synchronize {
  43. defer { if !outputs.isEmpty { outputs.removeFirst() } }
  44. return outputs.first
  45. }
  46. }
  47. open func receive(completion: @escaping (ResultOrRPCError<OutputType?>) -> Void) throws {
  48. completion(.result(try self._receive(timeout: .distantFuture)))
  49. }
  50. open func cancel() {}
  51. }