ServiceServer.swift 5.0 KB

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