import Darwin import Foundation import Testing @testable import ParcelIPC struct RequestWaitGate: Sendable { private let entered: AsyncStream private let enteredContinuation: AsyncStream.Continuation private let released: AsyncStream private let releaseContinuation: AsyncStream.Continuation init() { let entry = AsyncStream.makeStream() entered = entry.stream enteredContinuation = entry.continuation let release = AsyncStream.makeStream() released = release.stream releaseContinuation = release.continuation } func waitForEntry() async throws { var iterator = entered.makeAsyncIterator() guard await iterator.next() != nil else { throw CancellationError() } } func waitForRelease() async throws { enteredContinuation.yield() var iterator = released.makeAsyncIterator() guard await iterator.next() != nil else { throw CancellationError() } try Task.checkCancellation() } func release() { releaseContinuation.yield() releaseContinuation.finish() enteredContinuation.finish() } } actor FakeHandler: IPCHandler { struct Invocation: Equatable, Sendable { let command: String let args: [String] } let waitGate = RequestWaitGate() var invocations: [Invocation] = [] private var invocationObserver: (@Sendable (Invocation) -> Void)? func observeInvocations(_ observer: @escaping @Sendable (Invocation) -> Void) { invocationObserver = observer } var explanations: [UInt32] = [] var reloads = 0 func query(_ query: IPCQuery) async throws -> JSONValue { .object(["query": .string(query.rawValue), "items": .array([])]) } func run(command: String, args: [String]) async throws -> JSONValue { let invocation = Invocation(command: command, args: args) invocations.append(invocation) invocationObserver?(invocation) if command == "fail" { throw IPCError(code: "engine_failure", message: "The window is gone.") } if command == "other-error" { throw FakeError() } if command == "wait" { try await waitGate.waitForRelease() } return .object(["command": .string(command), "args": .array(args.map(JSONValue.string))]) } func why(window: UInt32) async throws -> JSONValue { explanations.append(window) if window == 13 { throw IPCError(code: "window_not_found", message: "The window is gone.") } if window == 14 { throw FakeError() } return .object(["window": .integer(Int64(window)), "reason": .string("A test explanation.")]) } func reloadConfig() async throws -> JSONValue { reloads += 1 return .bool(true) } struct FakeError: Error, LocalizedError { var errorDescription: String? { "A visible handler failure." } } } struct SocketFixture { let directory: URL var path: String { directory.appendingPathComponent("ipc.sock").path } init() throws { directory = URL(fileURLWithPath: "/tmp/parcel-ipc-" + UUID().uuidString.prefix(8)) try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) } func remove() { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } } func withServer( _ body: (IPCServer, IPCClient, FakeHandler, String) async throws -> Void ) async throws { let fixture = try SocketFixture() defer { fixture.remove() } let handler = FakeHandler() let server = try IPCServer(handler: handler, socketPath: fixture.path) let client = try IPCClient(socketPath: fixture.path) try await server.start() do { try await body(server, client, handler, fixture.path) await client.close() try await server.stop() } catch { await client.close() do { try await server.stop() } catch { Issue.record(error) } throw error } } func eventually(_ condition: @escaping @Sendable () async -> Bool) async throws { let clock = ContinuousClock() let deadline = clock.now.advanced(by: .seconds(3)) while !(await condition()) { guard clock.now < deadline else { throw Timeout() } try await Task.sleep(for: .milliseconds(2)) } } struct Timeout: Error {} func deadline(_ operation: @escaping @Sendable () async throws -> Value) async throws -> Value { try await withThrowingTaskGroup(of: Value.self) { group in group.addTask { try await operation() } group.addTask { try await Task.sleep(for: .seconds(3)) throw Timeout() } defer { group.cancelAll() } return try #require(await group.next()) } } @Suite("Live IPC", .timeLimit(.minutes(1))) struct ServerTests { @Test func ping() async throws { try await withServer { _, client, _, _ in let request = IPCRequest(id: .integer(42), command: "ping") let response = try await client.request(request) #expect(response == IPCResponse(id: request.id, result: .string("pong"))) } } @Test func version() async throws { try await withServer { _, client, _, _ in let response = try await client.request(IPCRequest(command: "version")) #expect(response.result == .object(["protocol": .integer(1), "version": .string("0.1.0")])) } } @Test(arguments: IPCQuery.allCases) func query(_ query: IPCQuery) async throws { try await withServer { _, client, _, _ in let response = try await client.request(IPCRequest(command: "query", args: [query.rawValue])) #expect(response.result == .object(["query": .string(query.rawValue), "items": .array([])])) } } @Test func runPreservesArguments() async throws { try await withServer { _, client, handler, _ in let args = ["left", "two words", "--future-option", "☀️"] let response = try await client.request(IPCRequest(command: "run", args: ["future-command"] + args)) #expect(response.ok) #expect(await handler.invocations == [.init(command: "future-command", args: args)]) } } } @Suite("Window explanation IPC", .timeLimit(.minutes(1))) struct WhyServerTests { @Test(arguments: [("1", UInt32(1)), ("00042", UInt32(42)), ("4294967295", UInt32.max)]) func why(window: (String, UInt32)) async throws { try await withServer { _, client, handler, _ in let request = IPCRequest(id: .integer(7), command: "why", args: [window.0]) let response = try await client.request(request) #expect( response == IPCResponse( id: request.id, result: .object([ "window": .integer(Int64(window.1)), "reason": .string("A test explanation."), ]))) #expect(await handler.explanations == [window.1]) } } @Test(arguments: [ [], [""], ["0"], ["000"], ["4294967296"], ["-1"], ["+1"], [" 1"], ["1 "], ["1.0"], ["0x1"], ["١"], ["1"], ["1", "2"], ]) func whyRejectsInvalidArguments(arguments: [String]) async throws { try await withServer { _, client, handler, _ in let response = try await client.request(IPCRequest(command: "why", args: arguments)) #expect(response.error?.code == "invalid_arguments") #expect(await handler.explanations.isEmpty) } } @Test func whyHandlerErrors() async throws { try await withServer { _, client, _, _ in let typed = try await client.request(IPCRequest(command: "why", args: ["13"])) #expect(typed.error == IPCError(code: "window_not_found", message: "The window is gone.")) let untyped = try await client.request(IPCRequest(command: "why", args: ["14"])) #expect(untyped.error == IPCError(code: "handler_error", message: "A visible handler failure.")) } } @Test func whyDefaultsToUnsupported() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let server = try IPCServer(handler: LegacyHandler(), socketPath: fixture.path) let client = try IPCClient(socketPath: fixture.path) try await server.start() do { let response = try await client.request(IPCRequest(command: "why", args: ["1"])) #expect( response.error == IPCError( code: "unsupported_command", message: "Window explanations are not supported by this server.")) await client.close() try await server.stop() } catch { await client.close() do { try await server.stop() } catch { Issue.record(error) } throw error } } } @Suite("IPC server lifecycle and errors", .timeLimit(.minutes(1))) struct ServerLifecycleTests { @Test func reloadConfig() async throws { try await withServer { _, client, handler, _ in let response = try await client.request(IPCRequest(command: "reload-config")) #expect(response.result == .bool(true)) #expect(await handler.reloads == 1) } } @Test(arguments: [0, 2, 99, -1]) func unknownVersions(_ version: Int) async throws { try await withServer { _, client, handler, _ in let response = try await client.request(IPCRequest(command: "run", args: ["focus", "left"], v: version)) #expect(response.error?.code == "unsupported_version") #expect(response.error?.message.contains("v=1") == true) #expect(await handler.invocations.isEmpty) } } @Test(arguments: [ IPCRequest(command: "query"), IPCRequest(command: "query", args: ["unknown"]), IPCRequest(command: "query", args: ["windows", "extra"]), IPCRequest(command: "run"), IPCRequest(command: "run", args: [""]), IPCRequest(command: "ping", args: ["extra"]), IPCRequest(command: "version", args: ["extra"]), IPCRequest(command: "reload-config", args: ["extra"]), ]) func invalidArguments(_ request: IPCRequest) async throws { try await withServer { _, client, _, _ in let response = try await client.request(request) #expect(response.error?.code == "invalid_arguments") } } @Test func unknownCommand() async throws { try await withServer { _, client, _, _ in let response = try await client.request(IPCRequest(command: "not-a-command")) #expect(response.error?.code == "unknown_command") } } @Test func typedHandlerError() async throws { try await withServer { _, client, _, _ in let response = try await client.request(IPCRequest(command: "run", args: ["fail"])) #expect(response.error == IPCError(code: "engine_failure", message: "The window is gone.")) } } @Test func untypedHandlerError() async throws { try await withServer { _, client, _, _ in let response = try await client.request(IPCRequest(command: "run", args: ["other-error"])) #expect(response.error == IPCError(code: "handler_error", message: "A visible handler failure.")) } } @Test func concurrentClients() async throws { try await withServer { _, _, handler, path in try await withThrowingTaskGroup(of: IPCResponse.self) { group in for number in 0..<32 { group.addTask { let client = try IPCClient(socketPath: path) return try await client.request( IPCRequest(id: .integer(Int64(number)), command: "run", args: ["focus", "left"])) } } var ids = Set() for try await response in group { #expect(response.ok) ids.insert(try #require(response.id)) } #expect(ids.count == 32) } #expect(await handler.invocations.count == 32) } } @Test func concurrentRequestsOnOneClient() async throws { try await withServer { _, client, _, _ in try await withThrowingTaskGroup(of: IPCResponse.self) { group in for number in 0..<16 { group.addTask { try await client.request(IPCRequest(id: .integer(Int64(number)), command: "ping")) } } var count = 0 for try await response in group { #expect(response.result == .string("pong")) count += 1 } #expect(count == 16) } } } @Test func subscribeAndDisconnect() async throws { try await withServer { server, client, _, _ in let subscription = try await client.subscribe(topics: [.focus, .layout]) #expect(await server.subscriberCount == 1) let expected = [ IPCEvent(topic: .focus, data: .integer(42)), IPCEvent(topic: .layout, data: .string("side")), ] try await server.publish(IPCEvent(topic: .window, data: .null)) for event in expected { try await server.publish(event) } let received = try await deadline { var iterator = subscription.events.makeAsyncIterator() return [try #require(await iterator.next()), try #require(await iterator.next())] } #expect(received == expected) await subscription.cancel() try await eventually { let subscribers = await server.subscriberCount let clients = await server.clientCount return subscribers == 0 && clients == 0 } } } @Test func defaultTopicsAndDuplicateTopics() async throws { try await withServer { server, client, _, _ in let all = try await client.subscribe() let duplicate = try await client.subscribe(topics: [.window, .window]) let event = IPCEvent(topic: .window, data: .string("created")) try await server.publish(event) let received = try await deadline { var first = all.events.makeAsyncIterator() var second = duplicate.events.makeAsyncIterator() return [try #require(await first.next()), try #require(await second.next())] } #expect(received == [event, event]) await all.cancel() await duplicate.cancel() } } @Test func serverStopEndsSubscriptions() async throws { try await withServer { server, client, _, _ in let subscription = try await client.subscribe() try await server.stop() let next = try await deadline { var iterator = subscription.events.makeAsyncIterator() return try await iterator.next() } #expect(next == nil) await subscription.cancel() } } @Test func clientCloseDisconnectsSubscription() async throws { try await withServer { server, client, _, _ in let subscription = try await client.subscribe() await client.close() try await eventually { await server.subscriberCount == 0 } await subscription.cancel() } } @Test func canceledIteratorDisconnects() async throws { try await withServer { server, client, _, _ in let subscription = try await client.subscribe() let reader = Task { for try await _ in subscription.events {} } reader.cancel() _ = await reader.result try await eventually { await server.subscriberCount == 0 } await subscription.cancel() } } @Test func invalidPublishVersion() async throws { try await withServer { server, _, _, _ in await #expect(throws: IPCError.self) { try await server.publish(IPCEvent(topic: .focus, data: .null, v: 2)) } } } @Test func requestCannotSubscribe() async throws { let client = try IPCClient(socketPath: "/tmp/nonexistent-parcel-test.sock") await #expect(throws: IPCTransportError.self) { try await client.request(IPCRequest(command: "subscribe")) } } @Test func notRunningIsFriendly() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let client = try IPCClient(socketPath: fixture.path) await #expect(throws: IPCTransportError.notRunning(fixture.path)) { try await client.request(IPCRequest(command: "ping")) } } @Test func permissionsAndShutdownCleanup() async throws { try await withServer { server, _, _, path in let attributes = try FileManager.default.attributesOfItem(atPath: path) #expect(attributes[.posixPermissions] as? Int == 0o600) let lockAttributes = try FileManager.default.attributesOfItem(atPath: path + ".lock") #expect(lockAttributes[.posixPermissions] as? Int == 0o600) try await server.stop() #expect(!FileManager.default.fileExists(atPath: path)) } } @Test func liveServerIsNotReplaced() async throws { try await withServer { _, client, _, path in let other = try IPCServer(handler: FakeHandler(), socketPath: path) await #expect(throws: IPCTransportError.alreadyRunning(path)) { try await other.start() } #expect(try await client.request(IPCRequest(command: "ping")).ok) } } @Test func duplicateStartFails() async throws { try await withServer { server, _, _, path in await #expect(throws: IPCTransportError.alreadyRunning(path)) { try await server.start() } } } @Test func stoppedServerCanRestart() async throws { try await withServer { server, client, _, _ in try await server.stop() try await server.start() #expect(try await client.request(IPCRequest(command: "ping")).ok) } } @Test func staleSocketIsRemoved() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let fd = try makeSocket() var address = try SocketAddress(fixture.path) #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) Darwin.close(fd) let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) try await server.start() let client = try IPCClient(socketPath: fixture.path) #expect(try await client.request(IPCRequest(command: "ping")).ok) try await server.stop() } @Test func regularFileIsNotDeleted() async throws { let fixture = try SocketFixture() defer { fixture.remove() } try Data("keep me".utf8).write(to: URL(fileURLWithPath: fixture.path)) let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) await #expect(throws: IPCTransportError.unsafeExistingPath(fixture.path)) { try await server.start() } #expect(try String(contentsOfFile: fixture.path, encoding: .utf8) == "keep me") } @Test func symlinkIsNotFollowed() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("keep.txt") try Data("keep me".utf8).write(to: target) try FileManager.default.createSymbolicLink(atPath: fixture.path, withDestinationPath: target.path) let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) await #expect(throws: IPCTransportError.unsafeExistingPath(fixture.path)) { try await server.start() } #expect(try String(contentsOf: target, encoding: .utf8) == "keep me") } @Test func lockSymlinkIsNotFollowed() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("keep.txt") try Data("keep me".utf8).write(to: target) try FileManager.default.createSymbolicLink(atPath: fixture.path + ".lock", withDestinationPath: target.path) let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) await #expect(throws: IPCTransportError.self) { try await server.start() } #expect(try String(contentsOf: target, encoding: .utf8) == "keep me") } @Test func liveSocketWithoutLockIsDetected() async throws { let fixture = try SocketFixture() defer { fixture.remove() } let fd = try makeSocket() defer { Darwin.close(fd) } var address = try SocketAddress(fixture.path) #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) #expect(Darwin.listen(fd, 4) == 0) let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) await #expect(throws: IPCTransportError.alreadyRunning(fixture.path)) { try await server.start() } #expect(FileManager.default.fileExists(atPath: fixture.path)) } @Test func shutdownDoesNotDeleteReplacementSocket() async throws { try await withServer { server, _, _, path in #expect(unlink(path) == 0) let fd = try makeSocket() defer { Darwin.close(fd) } var address = try SocketAddress(path) #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) try await server.stop() #expect(FileManager.default.fileExists(atPath: path)) } } @Test func requestCancellationDoesNotStopServer() async throws { try await withServer { _, client, handler, _ in let gate = handler.waitGate let started = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) defer { started.continuation.finish() } await handler.observeInvocations { started.continuation.yield($0) } let request = Task { defer { started.continuation.finish() } return try await client.request(IPCRequest(command: "run", args: ["wait"])) } defer { request.cancel() gate.release() } var events = started.stream.makeAsyncIterator() let invocation = try #require(await events.next(), "Request ended before the handler started") #expect(invocation == .init(command: "wait", args: [])) try await gate.waitForEntry() request.cancel() switch await request.result { case .success: Issue.record("The gated request completed despite cancellation") case .failure(let error): #expect(error is CancellationError || (error as? IPCTransportError) == .closed) } let response = try await client.request(IPCRequest(command: "ping")) #expect(response.ok) } } } private struct LegacyHandler: IPCHandler { func query(_ query: IPCQuery) async throws -> JSONValue { .null } func run(command: String, args: [String]) async throws -> JSONValue { .null } func reloadConfig() async throws -> JSONValue { .null } } @Suite("NDJSON framing", .timeLimit(.minutes(1))) struct FramingTests { @Test func partialAndMultipleMessages() async throws { try await withServer { _, _, _, path in let channel = SocketChannel(descriptor: try makeSocket()) try await channel.connect(path: path) let first = try IPCCodec.encode(IPCRequest(id: .integer(1), command: "ping")) try await channel.write(Data(first.prefix(5))) var remaining = Data(first.dropFirst(5)) remaining.append(try IPCCodec.encode(IPCRequest(id: .integer(2), command: "ping"))) try await channel.write(remaining) let firstLine = try #require(await channel.readLine()) let secondLine = try #require(await channel.readLine()) #expect(try IPCCodec.decode(IPCResponse.self, from: firstLine).id == .integer(1)) #expect(try IPCCodec.decode(IPCResponse.self, from: secondLine).id == .integer(2)) await channel.close() } } @Test(arguments: [ "not json", "{\"v\":1,\"id\":42,\"command\":\"ping\"}", "{\"v\":2,\"id\":42}", "{\"id\":42,\"command\":\"ping\",\"args\":[]}", ]) func malformedRequestGetsResponse(_ json: String) async throws { try await withServer { _, _, _, path in let channel = SocketChannel(descriptor: try makeSocket()) try await channel.connect(path: path) try await channel.write(Data((json + "\n").utf8)) let line = try #require(await channel.readLine()) let response = try IPCCodec.decode(IPCResponse.self, from: line) #expect(!response.ok) #expect(response.error?.code == (json.contains("\"v\":2") ? "unsupported_version" : "invalid_request")) #expect(response.id == (json == "not json" ? nil : .integer(42))) try await channel.write(IPCCodec.encode(IPCRequest(id: .integer(5), command: "ping"))) let next = try #require(await channel.readLine()) #expect(try IPCCodec.decode(IPCResponse.self, from: next).ok) await channel.close() } } @Test func invalidSubscriptionTopic() async throws { try await withServer { server, _, _, path in let channel = SocketChannel(descriptor: try makeSocket()) try await channel.connect(path: path) try await channel.write(IPCCodec.encode(IPCRequest(command: "subscribe", args: ["unknown"]))) let line = try #require(await channel.readLine()) #expect(try IPCCodec.decode(IPCResponse.self, from: line).error?.code == "invalid_arguments") #expect(await server.subscriberCount == 0) await channel.close() } } @Test func oversizedFrameClosesConnection() async throws { try await withServer { _, _, _, path in let channel = SocketChannel(descriptor: try makeSocket()) try await channel.connect(path: path) do { try await channel.write(Data(repeating: 32, count: IPCProtocol.maximumMessageBytes + 16_384)) let next = try await deadline { try await channel.readLine() } #expect(next == nil) } catch let error as IPCTransportError { if case .system = error {} else { Issue.record(error) } } await channel.close() } } @Test func truncatedFrameReportsError() async throws { var pair: [Int32] = [0, 0] #expect(socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0) try configureSocket(pair[0]) try configureSocket(pair[1]) let channel = SocketChannel(descriptor: pair[0]) let peer = SocketChannel(descriptor: pair[1]) try await peer.write(Data("unfinished".utf8)) await peer.close() await #expect(throws: IPCTransportError.truncatedMessage) { try await channel.readLine() } await channel.close() } }