ServiceServer.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 " + handler.requestMetadata.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. if !handler.completionQueue.hasBeenShutdown {
  77. // The method is not implemented by the service - send a status saying so.
  78. try handler.call.perform(OperationGroup(
  79. call: handler.call,
  80. operations: [
  81. .sendInitialMetadata(Metadata()),
  82. .receiveCloseOnServer,
  83. .sendStatusFromServer(.unimplemented, "unknown method " + unwrappedMethod, Metadata())
  84. ]) { _ in
  85. handler.shutdown()
  86. })
  87. }
  88. }
  89. } catch {
  90. // The individual sessions' `run` methods (which are called by `self.handleMethod`) only throw errors if
  91. // they encountered an error that has not also been "seen" by the actual request handler implementation.
  92. // Therefore, this error is "really unexpected" and should be logged here - there's nowhere else to log it otherwise.
  93. print("ServiceServer unexpected error handling method '\(unwrappedMethod)': \(error)")
  94. do {
  95. if !handler.completionQueue.hasBeenShutdown {
  96. try handler.sendStatus((error as? ServerStatus) ?? .processingError)
  97. }
  98. } catch {
  99. print("ServiceServer unexpected error handling method '\(unwrappedMethod)'; sending status failed as well: \(error)")
  100. handler.shutdown()
  101. }
  102. }
  103. }
  104. }
  105. }