Server.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. /// Delay for which the spin loop should wait before starting over.
  32. let loopTimeout: TimeInterval
  33. /// Optional callback when server stops serving
  34. public var onCompletion: (() -> Void)?
  35. /// Initializes a Server
  36. ///
  37. /// - Parameter address: the address where the server will listen
  38. /// - Parameter loopTimeout: delay for which the spin loop should wait before starting over.
  39. public init(address: String, loopTimeout: TimeInterval = 600) {
  40. underlyingServer = cgrpc_server_create(address)
  41. completionQueue = CompletionQueue(
  42. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  43. self.loopTimeout = loopTimeout
  44. }
  45. /// Initializes a secure Server
  46. ///
  47. /// - Parameter address: the address where the server will listen
  48. /// - Parameter key: the private key for the server's certificates
  49. /// - Parameter certs: the server's certificates
  50. /// - Parameter rootCerts: used to validate client certificates; will enable enforcing valid client certificates when provided
  51. /// - Parameter loopTimeout: delay for which the spin loop should wait before starting over.
  52. public init(address: String, key: String, certs: String, rootCerts: String? = nil, loopTimeout: TimeInterval = 600) {
  53. underlyingServer = cgrpc_server_create_secure(address, key, certs, rootCerts, rootCerts == nil ? 0 : 1)
  54. completionQueue = CompletionQueue(
  55. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  56. self.loopTimeout = loopTimeout
  57. }
  58. deinit {
  59. cgrpc_server_destroy(underlyingServer)
  60. completionQueue.shutdown()
  61. }
  62. /// Run the server.
  63. ///
  64. /// - Parameter handlerFunction: will be called to handle an incoming request. Dispatched on a new thread, so can be blocking.
  65. public func run(handlerFunction: @escaping (Handler) -> Void) {
  66. cgrpc_server_start(underlyingServer)
  67. // run the server on a new background thread
  68. let spinloopThreadQueue = DispatchQueue(label: "SwiftGRPC.CompletionQueue.runToCompletion.spinloopThread")
  69. spinloopThreadQueue.async {
  70. do {
  71. // Allocate a handler _outside_ the spin loop, as we must use _this particular_ handler to serve the next call
  72. // once we have called `handler.requestCall`. In particular, we need to keep the current handler for the next
  73. // spin loop interation when we hit the `.queueTimeout` case. The handler should only be replaced once it is
  74. // "used up" for serving an incoming call.
  75. var handler = Handler(underlyingServer: self.underlyingServer)
  76. // Tell gRPC to store the next call's information in this handler object.
  77. try handler.requestCall(tag: Server.handlerCallTag)
  78. var spinloopActive = true
  79. while spinloopActive {
  80. try withAutoReleasePool {
  81. // block while waiting for an incoming request
  82. let event = self.completionQueue.wait(timeout: self.loopTimeout)
  83. if event.type == .complete {
  84. if event.tag == Server.handlerCallTag {
  85. // run the handler and remove it when it finishes
  86. if event.success != 0 {
  87. // hold onto the handler while it runs
  88. var strongHandlerReference: Handler?
  89. strongHandlerReference = handler
  90. // To prevent the "Variable 'strongHandlerReference' was written to, but never read" warning.
  91. _ = strongHandlerReference
  92. // this will start the completion queue on a new thread
  93. handler.completionQueue.runToCompletion {
  94. // release the handler when it finishes
  95. strongHandlerReference = nil
  96. }
  97. // Dispatch the handler function on a separate thread.
  98. let handlerDispatchThreadQueue = DispatchQueue(label: "SwiftGRPC.Server.run.dispatchHandlerThread")
  99. // Needs to be copied, because we will change the value of `handler` right after this.
  100. let handlerCopy = handler
  101. handlerDispatchThreadQueue.async {
  102. handlerFunction(handlerCopy)
  103. }
  104. }
  105. // This handler has now been "used up" for the current call; replace it with a fresh one for the next
  106. // loop iteration.
  107. handler = Handler(underlyingServer: self.underlyingServer)
  108. try handler.requestCall(tag: Server.handlerCallTag)
  109. } else if event.tag == Server.stopTag || event.tag == Server.destroyTag {
  110. spinloopActive = false
  111. return
  112. }
  113. } else if event.type == .queueTimeout {
  114. // Everything is fine, just start over *while continuing to use the existing handler*.
  115. return
  116. } else if event.type == .queueShutdown {
  117. spinloopActive = false
  118. return
  119. }
  120. }
  121. }
  122. } catch {
  123. print("server call error: \(error)")
  124. }
  125. self.onCompletion?()
  126. }
  127. }
  128. public func stop() {
  129. cgrpc_server_stop(underlyingServer)
  130. }
  131. }