THRIFT-4838: Add unix socket support for Swift
Client: Swift
Patch: Kino Roy
diff --git a/lib/swift/Sources/TSocketServer.swift b/lib/swift/Sources/TSocketServer.swift
index 6cd9adf..27b4b55 100644
--- a/lib/swift/Sources/TSocketServer.swift
+++ b/lib/swift/Sources/TSocketServer.swift
@@ -102,6 +102,49 @@
// tell socket to listen
acceptConnectionInBackgroundAndNotify(handle: socketFileHandle)
}
+
+ public init(path: String,
+ inProtocol: InProtocol.Type,
+ outProtocol: OutProtocol.Type,
+ processor: Processor) throws {
+ self.processor = processor
+ // create a socket
+ let socket = UnixSocket(path: path)
+ let fd = socket.fd
+
+ if fd == -1 {
+ print("TSocketServer: No server socket")
+ throw TTransportError(error: .notOpen, message: "Could not create socket")
+ }
+
+ // wrap it in a file handle so we can get messages from it
+ socketFileHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
+
+ // register for notifications of accepted incoming connections
+ _ = NotificationCenter.default.addObserver(forName: .NSFileHandleConnectionAccepted,
+ object: nil, queue: nil) {
+ [weak self] notification in
+ guard let strongSelf = self else { return }
+ guard let clientSocket = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
+ strongSelf.connectionAccepted(clientSocket)
+ }
+
+ let bindRes = socket.bind()
+ guard bindRes == 0 else {
+ print("TServerSocket: bind failed")
+ throw TTransportError(error: .notOpen, message: "Could not create socket")
+ }
+ let listenRes = listen(fd, 1024)
+ guard listenRes == 0 else {
+ print("TServerSocket: listen failed")
+ throw TTransportError(error: .notOpen, message: "Could not create socket")
+ }
+
+ // tell socket to listen
+ acceptConnectionInBackgroundAndNotify(handle: socketFileHandle)
+
+ print("TSocketServer: Listening on unix path \(path)")
+ }
private func acceptConnectionInBackgroundAndNotify(handle: FileHandle) {
DispatchQueue(label: "TSocketServer.connectionAccept").async {
@@ -111,6 +154,7 @@
}
}
}
+
func connectionAccepted(_ clientSocket: FileHandle) {
// Now that we have a client connected, handle the request on queue
processingQueue.async {