ServiceServer.swift 4.6 KB

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