Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import Foundationimport Synchronization
final class ProcessExitWaiter: Sendable { private struct Exit: Sendable { let status: Int32 let instant: ContinuousClock.Instant }
private let recorded = Mutex<Exit?>(nil) private let events: AsyncStream<Exit> private let continuation: AsyncStream<Exit>.Continuation
init() { (events, continuation) = AsyncStream.makeStream() }
func record(status: Int32, at instant: ContinuousClock.Instant = .now) { let exit = Exit(status: status, instant: instant) let first = recorded.withLock { recorded in guard recorded == nil else { return false } recorded = exit return true } if first { continuation.yield(exit) continuation.finish() } }
func wait( for label: String, timeout: Duration, now: ContinuousClock.Instant = .now, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) async throws -> Int32 { let deadline = now.advanced(by: timeout) return try await withThrowingTaskGroup(of: Int32.self) { group in group.addTask { var iterator = self.events.makeAsyncIterator() guard let exit = await iterator.next() else { try Task.checkCancellation() throw E2EError(description: "Process exit stream ended before \(label)") } return try self.status(exit, before: deadline, label: label) } group.addTask { try await sleep(timeout) // Completion time belongs to the callback, not a delayed main-actor consumer. return try self.status(self.recorded.withLock { $0 }, before: deadline, label: label) } defer { group.cancelAll() } guard let result = try await group.next() else { throw E2EError(description: "No process exit observer for \(label)") } return result } }
private func status(_ exit: Exit?, before deadline: ContinuousClock.Instant, label: String) throws -> Int32 { guard let exit, exit.instant <= deadline else { throw E2EError(description: "Timed out waiting for \(label)") } return exit.status }}