ServiceServer.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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, rootCerts: String? = nil) {
  31. gRPC.initialize()
  32. self.address = address
  33. server = Server(address: address, key: keyString, certs: certificateString, rootCerts: rootCerts)
  34. }
  35. /// Create a server that accepts secure connections.
  36. public init?(address: String, certificateURL: URL, keyURL: URL, rootCertsURL: 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. var rootCerts: String?
  41. if let rootCertsURL = rootCertsURL {
  42. guard let rootCertsString = try? String(contentsOf: rootCertsURL, encoding: .utf8) else {
  43. return nil
  44. }
  45. rootCerts = rootCertsString
  46. }
  47. gRPC.initialize()
  48. self.address = address
  49. server = Server(address: address, key: key, certs: certificate, rootCerts: rootCerts)
  50. }
  51. public enum HandleMethodError: Error {
  52. case unknownMethod
  53. }
  54. /// Handle the given method. Needs to be overridden by actual implementations.
  55. /// Returns whether the method was actually handled.
  56. open func handleMethod(_ method: String, handler: Handler) throws -> ServerStatus? { fatalError("needs to be overridden") }
  57. /// Start the server.
  58. public func start() {
  59. server.run { [weak self] handler in
  60. guard let strongSelf = self else {
  61. print("ERROR: ServiceServer has been asked to handle a request even though it has already been deallocated")
  62. return
  63. }
  64. let unwrappedMethod = handler.method ?? "(nil)"
  65. if strongSelf.shouldLogRequests == true {
  66. let unwrappedHost = handler.host ?? "(nil)"
  67. let unwrappedCaller = handler.caller ?? "(nil)"
  68. print("Server received request to " + unwrappedHost
  69. + " calling " + unwrappedMethod
  70. + " from " + unwrappedCaller
  71. + " with metadata " + handler.requestMetadata.dictionaryRepresentation.description)
  72. }
  73. do {
  74. do {
  75. if let responseStatus = try strongSelf.handleMethod(unwrappedMethod, handler: handler),
  76. !handler.completionQueue.hasBeenShutdown {
  77. // The handler wants us to send the status for them; do that.
  78. // But first, ensure that all outgoing messages have been enqueued, to avoid ending the stream prematurely:
  79. handler.call.messageQueueEmpty.wait()
  80. try handler.sendStatus(responseStatus)
  81. }
  82. } catch _ as HandleMethodError {
  83. print("ServiceServer call to unknown method '\(unwrappedMethod)'")
  84. if !handler.completionQueue.hasBeenShutdown {
  85. // The method is not implemented by the service - send a status saying so.
  86. try handler.call.perform(OperationGroup(
  87. call: handler.call,
  88. operations: [
  89. .sendInitialMetadata(Metadata()),
  90. .receiveCloseOnServer,
  91. .sendStatusFromServer(.unimplemented, "unknown method " + unwrappedMethod, Metadata())
  92. ]) { _ in
  93. handler.shutdown()
  94. })
  95. }
  96. }
  97. } catch {
  98. // The individual sessions' `run` methods (which are called by `self.handleMethod`) only throw errors if
  99. // they encountered an error that has not also been "seen" by the actual request handler implementation.
  100. // Therefore, this error is "really unexpected" and should be logged here - there's nowhere else to log it otherwise.
  101. print("ServiceServer unexpected error handling method '\(unwrappedMethod)': \(error)")
  102. do {
  103. if !handler.completionQueue.hasBeenShutdown {
  104. try handler.sendStatus((error as? ServerStatus) ?? .processingError)
  105. }
  106. } catch {
  107. print("ServiceServer unexpected error handling method '\(unwrappedMethod)'; sending status failed as well: \(error)")
  108. handler.shutdown()
  109. }
  110. }
  111. }
  112. }
  113. }