ServiceServer.swift 5.4 KB

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