Server.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. /// Pointer to underlying C representation
  24. private let underlyingServer: UnsafeMutableRawPointer
  25. /// Completion queue used for server operations
  26. let completionQueue: CompletionQueue
  27. /// Active handlers
  28. private var handlers = Set<Handler>()
  29. /// Mutex for synchronizing access to handlers
  30. private let handlersMutex: Mutex = Mutex()
  31. /// Optional callback when server stops serving
  32. private 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) {
  47. underlyingServer = cgrpc_server_create_secure(address, key, certs)
  48. <<<<<<< HEAD
  49. completionQueue = CompletionQueue(
  50. underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer), name: "Server " + address)
  51. handlers = NSMutableSet()
  52. =======
  53. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_server_get_completion_queue(underlyingServer))
  54. completionQueue.name = "Server " + address
  55. >>>>>>> 3602c874d7d72af414fc2d22bc98baf0e2498f88
  56. }
  57. deinit {
  58. cgrpc_server_destroy(underlyingServer)
  59. }
  60. /// Run the server
  61. public func run(dispatchQueue: DispatchQueue = DispatchQueue.global(),
  62. handlerFunction: @escaping (Handler) -> Void) {
  63. cgrpc_server_start(underlyingServer)
  64. // run the server on a new background thread
  65. dispatchQueue.async {
  66. var running = true
  67. while running {
  68. do {
  69. let handler = Handler(underlyingServer: self.underlyingServer)
  70. try handler.requestCall(tag: 101)
  71. // block while waiting for an incoming request
  72. let event = self.completionQueue.wait(timeout: 600)
  73. if event.type == .complete {
  74. if event.tag == 101 {
  75. // run the handler and remove it when it finishes
  76. if event.success != 0 {
  77. // hold onto the handler while it runs
  78. self.handlersMutex.synchronize {
  79. self.handlers.insert(handler)
  80. }
  81. // this will start the completion queue on a new thread
  82. handler.completionQueue.runToCompletion(callbackQueue: dispatchQueue) {
  83. dispatchQueue.async {
  84. self.handlersMutex.synchronize {
  85. // release the handler when it finishes
  86. self.handlers.remove(handler)
  87. }
  88. }
  89. }
  90. // call the handler function on the server thread
  91. handlerFunction(handler)
  92. }
  93. } else if event.tag == 0 {
  94. running = false // exit the loop
  95. }
  96. } else if event.type == .queueTimeout {
  97. // everything is fine
  98. } else if event.type == .queueShutdown {
  99. running = false
  100. }
  101. } catch (let callError) {
  102. print("server call error: \(callError)")
  103. running = false
  104. }
  105. }
  106. if let onCompletion = self.onCompletion {
  107. onCompletion()
  108. }
  109. }
  110. }
  111. public func stop() {
  112. cgrpc_server_stop(underlyingServer)
  113. }
  114. public func onCompletion(completion: @escaping (() -> Void)) {
  115. onCompletion = completion
  116. }
  117. }