Server.swift 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. /// Active handlers
  32. private var handlers = Set<Handler>()
  33. /// Mutex for synchronizing access to handlers
  34. private let handlersMutex: Mutex = Mutex()
  35. /// Optional callback when server stops serving
  36. public var onCompletion: (() -> Void)?
  37. /// Initializes a Server
  38. ///
  39. /// - Parameter address: the address where the server will listen
  40. public init(address: String) {
  41. underlyingServer = cgrpc_server_create(address)
  42. completionQueue = CompletionQueue(
  43. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  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. public init(address: String, key: String, certs: String) {
  51. underlyingServer = cgrpc_server_create_secure(address, key, certs)
  52. completionQueue = CompletionQueue(
  53. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  54. }
  55. deinit {
  56. cgrpc_server_destroy(underlyingServer)
  57. }
  58. /// Run the server
  59. public func run(dispatchQueue: DispatchQueue = DispatchQueue.global(),
  60. handlerFunction: @escaping (Handler) -> Void) {
  61. cgrpc_server_start(underlyingServer)
  62. // run the server on a new background thread
  63. dispatchQueue.async {
  64. var running = true
  65. while running {
  66. do {
  67. let handler = Handler(underlyingServer: self.underlyingServer)
  68. try handler.requestCall(tag: Server.handlerCallTag)
  69. // block while waiting for an incoming request
  70. let event = self.completionQueue.wait(timeout: 600)
  71. if event.type == .complete {
  72. if event.tag == Server.handlerCallTag {
  73. // run the handler and remove it when it finishes
  74. if event.success != 0 {
  75. // hold onto the handler while it runs
  76. self.handlersMutex.synchronize {
  77. self.handlers.insert(handler)
  78. }
  79. // this will start the completion queue on a new thread
  80. handler.completionQueue.runToCompletion(callbackQueue: dispatchQueue) {
  81. dispatchQueue.async {
  82. self.handlersMutex.synchronize {
  83. // release the handler when it finishes
  84. self.handlers.remove(handler)
  85. }
  86. }
  87. }
  88. // call the handler function on the server thread
  89. handlerFunction(handler)
  90. }
  91. } else if event.tag == Server.stopTag || event.tag == Server.destroyTag {
  92. running = false // exit the loop
  93. }
  94. } else if event.type == .queueTimeout {
  95. // everything is fine
  96. } else if event.type == .queueShutdown {
  97. running = false
  98. }
  99. } catch {
  100. print("server call error: \(error)")
  101. running = false
  102. }
  103. }
  104. self.onCompletion?()
  105. }
  106. }
  107. public func stop() {
  108. cgrpc_server_stop(underlyingServer)
  109. }
  110. }