2
0

ServiceServer.swift 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. open class ServiceServer {
  20. public let address: String
  21. public let server: Server
  22. public var shouldLogRequests = true
  23. /// Create a server that accepts insecure connections.
  24. public init(address: String) {
  25. gRPC.initialize()
  26. self.address = address
  27. server = Server(address: address)
  28. }
  29. /// Create a server that accepts secure connections.
  30. public init(address: String, certificateString: String, keyString: String) {
  31. gRPC.initialize()
  32. self.address = address
  33. server = Server(address: address, key: keyString, certs: certificateString)
  34. }
  35. /// Create a server that accepts secure connections.
  36. public init?(address: String, certificateURL: URL, keyURL: URL) {
  37. guard let certificate = try? String(contentsOf: certificateURL, encoding: .utf8),
  38. let key = try? String(contentsOf: keyURL, encoding: .utf8)
  39. else { return nil }
  40. gRPC.initialize()
  41. self.address = address
  42. server = Server(address: address, key: key, certs: certificate)
  43. }
  44. /// Handle the given method. Needs to be overridden by actual implementations.
  45. /// Returns whether the method was actually handled.
  46. open func handleMethod(_ method: String, handler: Handler, queue: DispatchQueue) throws -> Bool { fatalError("needs to be overridden") }
  47. /// Start the server.
  48. public func start(queue: DispatchQueue = DispatchQueue.global()) {
  49. server.run { [weak self] handler in
  50. guard let strongSelf = self else {
  51. print("ERROR: ServiceServer has been asked to handle a request even though it has already been deallocated")
  52. return
  53. }
  54. let unwrappedMethod = handler.method ?? "(nil)"
  55. if strongSelf.shouldLogRequests == true {
  56. let unwrappedHost = handler.host ?? "(nil)"
  57. let unwrappedCaller = handler.caller ?? "(nil)"
  58. print("Server received request to " + unwrappedHost
  59. + " calling " + unwrappedMethod
  60. + " from " + unwrappedCaller
  61. + " with " + handler.requestMetadata.description)
  62. }
  63. do {
  64. if !(try strongSelf.handleMethod(unwrappedMethod, handler: handler, queue: queue)) {
  65. do {
  66. try handler.call.perform(OperationGroup(
  67. call: handler.call,
  68. operations: [
  69. .sendInitialMetadata(Metadata()),
  70. .receiveCloseOnServer,
  71. .sendStatusFromServer(.unimplemented, "unknown method " + unwrappedMethod, Metadata())
  72. ]) { _ in
  73. handler.shutdown()
  74. })
  75. } catch {
  76. print("ServiceServer.start error sending status for unknown method: \(error)")
  77. }
  78. }
  79. } catch {
  80. print("Server error: \(error)")
  81. }
  82. }
  83. }
  84. }