ServerSessionServerStreaming.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 Foundation
  17. import Dispatch
  18. import SwiftProtobuf
  19. public protocol ServerSessionServerStreaming: ServerSession { }
  20. open class ServerSessionServerStreamingImpl<InputType: Message, OutputType: Message>: ServerSessionImpl, ServerSessionServerStreaming {
  21. public typealias ProviderBlock = (InputType, ServerSessionServerStreamingImpl) throws -> Void
  22. private var providerBlock: ProviderBlock
  23. public init(handler:Handler, providerBlock: @escaping ProviderBlock) {
  24. self.providerBlock = providerBlock
  25. super.init(handler:handler)
  26. }
  27. public func send(_ response: OutputType, completion: ((Bool)->())?) throws {
  28. try handler.sendResponse(message:response.serializedData(), completion: completion)
  29. }
  30. public func run(queue:DispatchQueue) throws {
  31. try self.handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  32. if let requestData = requestData {
  33. do {
  34. let requestMessage = try InputType(serializedData:requestData)
  35. // to keep providers from blocking the server thread,
  36. // we dispatch them to another queue.
  37. queue.async {
  38. do {
  39. try self.providerBlock(requestMessage, self)
  40. try self.handler.sendStatus(statusCode:self.statusCode,
  41. statusMessage:self.statusMessage,
  42. trailingMetadata:self.trailingMetadata,
  43. completion:nil)
  44. } catch (let error) {
  45. print("error: \(error)")
  46. }
  47. }
  48. } catch (let error) {
  49. print("error: \(error)")
  50. }
  51. }
  52. }
  53. }
  54. }
  55. /// Simple fake implementation of ServerSessionServerStreaming that returns a previously-defined set of results
  56. /// and stores sent values for later verification.
  57. open class ServerSessionServerStreamingTestStub<OutputType: Message>: ServerSessionTestStub, ServerSessionServerStreaming {
  58. open var outputs: [OutputType] = []
  59. open func send(_ response: OutputType, completion: ((Bool)->())?) throws {
  60. outputs.append(response)
  61. }
  62. open func close() throws { }
  63. }