ClientCallUnary.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 ClientCallUnary: ClientCall {
  20. /// Cancel the call.
  21. func cancel()
  22. }
  23. open class ClientCallUnaryBase<InputType: Message, OutputType: Message>: ClientCallBase, ClientCallUnary {
  24. /// Run the call. Blocks until the reply is received.
  25. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call. `ClientError` if receives no response.
  26. public func run(request: InputType, metadata: Metadata) throws -> OutputType {
  27. let sem = DispatchSemaphore(value: 0)
  28. var returnCallResult: CallResult!
  29. var returnResponse: OutputType?
  30. _ = try start(request: request, metadata: metadata) { response, callResult in
  31. returnResponse = response
  32. returnCallResult = callResult
  33. sem.signal()
  34. }
  35. _ = sem.wait()
  36. if let returnResponse = returnResponse {
  37. return returnResponse
  38. } else {
  39. throw ClientError.error(c: returnCallResult)
  40. }
  41. }
  42. /// Start the call. Nonblocking.
  43. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call.
  44. public func start(request: InputType,
  45. metadata: Metadata,
  46. completion: @escaping ((OutputType?, CallResult) -> Void)) throws -> Self {
  47. let requestData = try request.serializedData()
  48. try call.start(.unary, metadata: metadata, message: requestData) { callResult in
  49. if let responseData = callResult.resultData,
  50. let response = try? OutputType(serializedData: responseData) {
  51. completion(response, callResult)
  52. } else {
  53. completion(nil, callResult)
  54. }
  55. }
  56. return self
  57. }
  58. public func cancel() {
  59. call.cancel()
  60. }
  61. }