Server.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. /*
  2. * Copyright 2016, 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. #if SWIFT_PACKAGE
  17. import CgRPC
  18. import Dispatch
  19. #endif
  20. import Foundation
  21. /// gRPC Server
  22. public class Server {
  23. static let handlerCallTag = 101
  24. // These are sent by the CgRPC shim.
  25. static let stopTag = 0
  26. static let destroyTag = 1000
  27. /// Pointer to underlying C representation
  28. private let underlyingServer: UnsafeMutableRawPointer
  29. /// Completion queue used for server operations
  30. let completionQueue: CompletionQueue
  31. /// Optional callback when server stops serving
  32. public var onCompletion: (() -> Void)?
  33. /// Initializes a Server
  34. ///
  35. /// - Parameter address: the address where the server will listen
  36. public init(address: String) {
  37. underlyingServer = cgrpc_server_create(address)
  38. completionQueue = CompletionQueue(
  39. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  40. }
  41. /// Initializes a secure Server
  42. ///
  43. /// - Parameter address: the address where the server will listen
  44. /// - Parameter key: the private key for the server's certificates
  45. /// - Parameter certs: the server's certificates
  46. public init(address: String, key: String, certs: String, rootCerts: String? = nil) {
  47. underlyingServer = cgrpc_server_create_secure(address, key, certs, rootCerts, rootCerts == nil ? 0 : 1)
  48. completionQueue = CompletionQueue(
  49. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  50. }
  51. deinit {
  52. cgrpc_server_destroy(underlyingServer)
  53. completionQueue.shutdown()
  54. }
  55. /// Run the server.
  56. ///
  57. /// - Parameter handlerFunction: will be called to handle an incoming request. Dispatched on a new thread, so can be blocking.
  58. public func run(handlerFunction: @escaping (Handler) -> Void) {
  59. cgrpc_server_start(underlyingServer)
  60. // run the server on a new background thread
  61. let spinloopThreadQueue = DispatchQueue(label: "SwiftGRPC.CompletionQueue.runToCompletion.spinloopThread")
  62. spinloopThreadQueue.async {
  63. spinloop: while true {
  64. do {
  65. let handler = Handler(underlyingServer: self.underlyingServer)
  66. try handler.requestCall(tag: Server.handlerCallTag)
  67. // block while waiting for an incoming request
  68. let event = self.completionQueue.wait(timeout: 600)
  69. if event.type == .complete {
  70. if event.tag == Server.handlerCallTag {
  71. // run the handler and remove it when it finishes
  72. if event.success != 0 {
  73. // hold onto the handler while it runs
  74. var strongHandlerReference: Handler?
  75. strongHandlerReference = handler
  76. // To prevent the "Variable 'strongHandlerReference' was written to, but never read" warning.
  77. _ = strongHandlerReference
  78. // this will start the completion queue on a new thread
  79. handler.completionQueue.runToCompletion {
  80. // release the handler when it finishes
  81. strongHandlerReference = nil
  82. }
  83. // Dispatch the handler function on a separate thread.
  84. let handlerDispatchThreadQueue = DispatchQueue(label: "SwiftGRPC.Server.run.dispatchHandlerThread")
  85. handlerDispatchThreadQueue.async {
  86. handlerFunction(handler)
  87. }
  88. }
  89. } else if event.tag == Server.stopTag || event.tag == Server.destroyTag {
  90. break spinloop
  91. }
  92. } else if event.type == .queueTimeout {
  93. // everything is fine
  94. continue
  95. } else if event.type == .queueShutdown {
  96. break spinloop
  97. }
  98. } catch {
  99. print("server call error: \(error)")
  100. break spinloop
  101. }
  102. }
  103. self.onCompletion?()
  104. }
  105. }
  106. public func stop() {
  107. cgrpc_server_stop(underlyingServer)
  108. }
  109. }