Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685import Darwinimport Foundationimport OSLogimport Synchronization
struct AppCallbackOutput: Sendable { private static let capacity = 16_384 private(set) var bytes = Data() private(set) var discardedBytes = 0
mutating func append(_ data: Data) { let excess = max(0, bytes.count + data.count - Self.capacity) discardedBytes += excess if data.count >= Self.capacity { bytes = Data(data.suffix(Self.capacity)) } else { if excess > 0 { bytes.removeFirst(excess) } bytes.append(data) } }
func tail(maximumBytes: Int = 16_384) -> String { String(decoding: bytes.suffix(maximumBytes), as: UTF8.self) }}
final class AppCallbackProcess: Sendable { enum Completion: Equatable, Sendable { case exited(Int32) case signaled(Int32) case timedOut case stopped }
struct Diagnostics: Sendable { let collectionDelay: Duration let exitNoticeReceived: Bool let exitNoticeBeforeTermination: Bool let exitReadbackAttempts: Int let normalDeadlineReadback: Bool }
struct Result: Sendable { let completion: Completion let standardOutput: AppCallbackOutput let standardError: AppCallbackOutput let diagnostics: Diagnostics }
private let pid: pid_t private let startedAt: ContinuousClock.Instant private let callbackStartedAt: ContinuousClock.Instant private let callbackNow: @Sendable () -> ContinuousClock.Instant private let standardOutput: Int32 private let standardError: Int32 private let eventQueue: Int32 private let signals: AppCallbackSignalOperations private let groupMembers: @Sendable (pid_t) throws -> [AppCallbackGroupMember] private let stopRequested = Mutex(false)
var processIdentifier: pid_t { pid }
private init( pid: pid_t, startedAt: ContinuousClock.Instant, callbackStartedAt: ContinuousClock.Instant, callbackNow: @escaping @Sendable () -> ContinuousClock.Instant, standardOutput: Int32, standardError: Int32, eventQueue: Int32, signals: AppCallbackSignalOperations, groupMembers: @escaping @Sendable (pid_t) throws -> [AppCallbackGroupMember] ) { self.pid = pid self.startedAt = startedAt self.callbackStartedAt = callbackStartedAt self.callbackNow = callbackNow self.standardOutput = standardOutput self.standardError = standardError self.eventQueue = eventQueue self.signals = signals self.groupMembers = groupMembers }
deinit { Self.closeDescriptor(standardOutput) Self.closeDescriptor(standardError) Self.closeDescriptor(eventQueue) }
static func spawn( arguments: [String], environment: [String: String], signals: AppCallbackSignalOperations = .system, groupMembers: @escaping @Sendable (pid_t) throws -> [AppCallbackGroupMember] = AppCallbackGroupInspection .members, callbackNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now } ) throws -> AppCallbackProcess { precondition(!arguments.isEmpty) for (key, value) in environment where value.contains("\0") { throw AppCallbackSystemFailure(operation: "NUL in callback environment (\(key))", code: EINVAL) } let output = try makePipe() var transferred = false defer { closeDescriptor(output.write) if !transferred { closeDescriptor(output.read) } } let error = try makePipe() defer { closeDescriptor(error.write) if !transferred { closeDescriptor(error.read) } } let eventQueue = try makeEventQueue(output: output.read, error: error.read) defer { if !transferred { closeDescriptor(eventQueue) } } var actions: posix_spawn_file_actions_t? try check(posix_spawn_file_actions_init(&actions), "posix_spawn_file_actions_init") defer { destroy(posix_spawn_file_actions_destroy(&actions), "posix_spawn_file_actions_destroy") } try check(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0), "stdin redirect") try check(posix_spawn_file_actions_adddup2(&actions, output.write, STDOUT_FILENO), "stdout redirect") try check(posix_spawn_file_actions_adddup2(&actions, error.write, STDERR_FILENO), "stderr redirect") for descriptor in [output.read, output.write, error.read, error.write] { try check(posix_spawn_file_actions_addclose(&actions, descriptor), "close inherited pipe") } var attributes: posix_spawnattr_t? try check(posix_spawnattr_init(&attributes), "posix_spawnattr_init") defer { destroy(posix_spawnattr_destroy(&attributes), "posix_spawnattr_destroy") } try check(posix_spawnattr_setpgroup(&attributes, 0), "posix_spawnattr_setpgroup") var signalMask = sigset_t() sigemptyset(&signalMask) try check(posix_spawnattr_setsigmask(&attributes, &signalMask), "posix_spawnattr_setsigmask") var signalDefaults = sigset_t() sigfillset(&signalDefaults) try check(posix_spawnattr_setsigdefault(&attributes, &signalDefaults), "posix_spawnattr_setsigdefault") let flags = POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_CLOEXEC_DEFAULT | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF try check(posix_spawnattr_setflags(&attributes, Int16(flags)), "posix_spawnattr_setflags") var pid: pid_t = 0 let startedAt = ContinuousClock.now let callbackStartedAt = callbackNow() try withCStringArray(arguments) { argv in try withCStringArray(environment.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }) { envp in try arguments[0].withCString { executable in try check(posix_spawn(&pid, executable, &actions, &attributes, argv, envp), "posix_spawn") } } } transferred = true return AppCallbackProcess( pid: pid, startedAt: startedAt, callbackStartedAt: callbackStartedAt, callbackNow: callbackNow, standardOutput: output.read, standardError: error.read, eventQueue: eventQueue, signals: signals, groupMembers: groupMembers) }
func requestStop() { let wasRequested = stopRequested.withLock { let previous = $0 $0 = true return previous } guard !wasRequested else { return } do { try Self.updateEventQueue( eventQueue, event: Self.event(ident: 1, filter: Int16(EVFILT_USER), flags: 0, notes: UInt32(NOTE_TRIGGER))) } catch { Self.logCleanup(error) } }
func collect( timeout: Duration, onCollected: @escaping @Sendable (Swift.Result<Result, any Error>, Duration) -> Void = { _, _ in } ) async throws -> Result { try await collect(timeout: timeout, onWaiting: {}, onCollected: onCollected) }
func collect( timeout: Duration, onWaiting: @escaping @Sendable () -> Void, onCollected: @escaping @Sendable (Swift.Result<Result, any Error>, Duration) -> Void ) async throws -> Result { try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in startCollecting( timeout: timeout, onWaiting: onWaiting, onCollected: { result, elapsed in onCollected(result, elapsed) continuation.resume(with: result) }) } } onCancel: { self.requestStop() } }
func startCollecting( timeout: Duration, onWaiting: @escaping @Sendable () -> Void = {}, onCollected: @escaping @Sendable (Swift.Result<Result, any Error>, Duration) -> Void ) { // Blocking process and pipe waits must not occupy Swift's cooperative executor. let thread = Thread { let start = ContinuousClock.now let result = Swift.Result { try self.collectOnThread(timeout: timeout, onWaiting: onWaiting) } onCollected(result, ContinuousClock.now - start) } thread.name = "Parcel callback \(pid)" thread.start() }
private func collectOnThread(timeout: Duration, onWaiting: @Sendable () -> Void) throws -> Result { let collectionDelay = ContinuousClock.now - startedAt let deadline = callbackStartedAt.advanced(by: timeout) var status: Int32? var leaderOwned = true var leaderExited = false var completion: Completion? var leaderExitDeadline: ContinuousClock.Instant? var finalDrainDeadline: ContinuousClock.Instant? var output = AppCallbackOutput() var error = AppCallbackOutput() var outputOpen = true var errorOpen = true var checkLeader = true var exitNoticeReceived = false var exitNoticeBeforeTermination = false var exitReadbackAttempts = 0 var normalDeadlineReadback = false do { // Registration precedes the first readback so an exit cannot slip between observation and waiting. try observeLeaderExit(leaderOwned: &leaderOwned) while true { // Reuse one deadline snapshot so a late wake cannot skip the final exit readback. let now = ContinuousClock.now let leaderExitExpired = leaderExitDeadline.map { now >= $0 } == true let callbackDeadlineExpired = completion == nil && callbackNow() >= deadline if status == nil && (checkLeader || exitNoticeReceived || leaderExitExpired || callbackDeadlineExpired) { checkLeader = false normalDeadlineReadback = normalDeadlineReadback || callbackDeadlineExpired var info = siginfo_t() while waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) == -1 { if errno == EINTR { continue } let code = errno if code == ECHILD { leaderOwned = false } throw AppCallbackSystemFailure(operation: "waitid", code: code) } var waitable = info.si_pid == pid if !waitable && exitNoticeReceived { try waitForExitReadback( leaderOwned: &leaderOwned, attempts: &exitReadbackAttempts, exitDeadline: leaderExitDeadline ) waitable = true } if waitable { // Keep the zombie leader waitable until its group is killed, preventing PID reuse. leaderExited = true try terminateGroup(leaderExited: true, leaderOwned: &leaderOwned) var value: Int32 = 0 while waitpid(pid, &value, 0) == -1 { if errno == EINTR { continue } let code = errno if code == ECHILD { leaderOwned = false } throw AppCallbackSystemFailure(operation: "waitpid", code: code) } leaderOwned = false status = value if completion == nil { completion = (value & 0x7f) == 0 ? .exited((value >> 8) & 0xff) : .signaled(value & 0x7f) } finalDrainDeadline = ContinuousClock.now.advanced(by: .milliseconds(100)) } } if completion == nil { if stopRequested.withLock({ $0 }) { completion = .stopped try terminateGroup(leaderOwned: &leaderOwned) leaderExitDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) } else if callbackDeadlineExpired { completion = .timedOut try terminateGroup(leaderOwned: &leaderOwned) leaderExitDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) } } if status == nil && leaderExitExpired { throw AppCallbackSystemFailure(operation: "callback leader exit (\(pid))", code: ETIMEDOUT) } if outputOpen { outputOpen = try drainObservedPipe(standardOutput, into: &output) } if errorOpen { errorOpen = try drainObservedPipe(standardError, into: &error) } if let completion, status != nil, (!outputOpen && !errorOpen) || finalDrainDeadline.map({ ContinuousClock.now >= $0 }) == true { return Result( completion: completion, standardOutput: output, standardError: error, diagnostics: Diagnostics( collectionDelay: collectionDelay, exitNoticeReceived: exitNoticeReceived, exitNoticeBeforeTermination: exitNoticeBeforeTermination, exitReadbackAttempts: exitReadbackAttempts, normalDeadlineReadback: normalDeadlineReadback)) } onWaiting() // Only the callback lifetime follows injected time; native teardown always stays bounded in real time. let nextDeadline: ContinuousClock.Instant? = if status != nil { finalDrainDeadline } else if completion != nil { leaderExitDeadline } else { ContinuousClock.now.advanced(by: max(.zero, callbackNow().duration(to: deadline))) } guard let nextDeadline else { preconditionFailure("Missing callback wait deadline") } checkLeader = try waitForEvents(until: nextDeadline) // NOTE_EXIT is one-shot; retain it until exit status becomes waitable. if checkLeader { exitNoticeReceived = true exitNoticeBeforeTermination = exitNoticeBeforeTermination || completion == nil } } } catch { var failures: [any Error] = [error] if leaderOwned { do { try terminateGroup(leaderExited: leaderExited, leaderOwned: &leaderOwned) } catch { failures.append(error) } switch reapForCleanup() { case .reaped: break case .unavailable(let failure): failures.append(failure) case .deferred(let failure): failures.append(failure) Self.reapInBackground(pid) } } throw AppCallbackProcessFailure(failures: failures) } }
private func observeLeaderExit(leaderOwned: inout Bool) throws { let deadline = ContinuousClock.now.advanced(by: .milliseconds(250)) var event = Self.event( ident: UInt64(pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT), notes: NOTE_EXIT) while kevent64(eventQueue, &event, 1, nil, 0, 0, nil) == -1 { if errno == EINTR { continue } let code = errno guard code == ESRCH else { throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) } // Exit can remove the process from kqueue lookup before its owned zombie becomes waitable. if try leaderHasExited(leaderOwned: &leaderOwned) { return } guard ContinuousClock.now < deadline else { throw AppCallbackSystemFailure(operation: "observe callback leader exit", code: code) } if poll(nil, 0, 1) == -1 && errno != EINTR { throw AppCallbackSystemFailure(operation: "poll callback exit observation", code: errno) } } }
private func waitForExitReadback( leaderOwned: inout Bool, attempts: inout Int, exitDeadline: ContinuousClock.Instant? ) throws { let transitionDeadline = ContinuousClock.now.advanced(by: .milliseconds(250)) let deadline = exitDeadline.map { min($0, transitionDeadline) } ?? transitionDeadline while true { attempts += 1 if try leaderHasExited(leaderOwned: &leaderOwned) { return } guard ContinuousClock.now < deadline else { throw AppCallbackSystemFailure( operation: "readback callback exit notice (\(pid); attempts=\(attempts))", code: ETIMEDOUT) } if poll(nil, 0, 1) == -1 && errno != EINTR { throw AppCallbackSystemFailure(operation: "poll callback exit readback", code: errno) } } }
private func waitForEvents(until deadline: ContinuousClock.Instant) throws -> Bool { var events = [kevent64_s](repeating: kevent64_s(), count: 4) while true { let remaining = max(.zero, ContinuousClock.now.duration(to: deadline)).components let nanoseconds = (remaining.attoseconds + 999_999_999) / 1_000_000_000 var timeout = timespec( tv_sec: Int(remaining.seconds + nanoseconds / 1_000_000_000), tv_nsec: Int(nanoseconds % 1_000_000_000)) let count = events.withUnsafeMutableBufferPointer { kevent64(eventQueue, nil, 0, $0.baseAddress, Int32($0.count), 0, &timeout) } guard count >= 0 else { if errno == EINTR { continue } throw AppCallbackSystemFailure(operation: "wait for callback events", code: errno) } var leaderExited = false for event in events.prefix(Int(count)) { if event.flags & UInt16(EV_ERROR) != 0 && event.data != 0 { throw AppCallbackSystemFailure(operation: "callback event", code: Int32(event.data)) } if event.filter == Int16(EVFILT_PROC) && event.fflags & NOTE_EXIT != 0 { leaderExited = true } } return leaderExited } }
private func drainObservedPipe(_ descriptor: Int32, into output: inout AppCallbackOutput) throws -> Bool { let open = try drain(descriptor, into: &output) if !open { // EOF is level-triggered too; remove it or closed pipes would spin while the leader remains alive. try Self.updateEventQueue( eventQueue, event: Self.event(ident: UInt64(descriptor), filter: Int16(EVFILT_READ), flags: UInt16(EV_DELETE))) } return open }
private func terminateGroup(leaderExited: Bool = false, leaderOwned: inout Bool) throws { var failures: [any Error] = [] do { var exited = leaderExited if !exited { exited = try leaderHasExited(leaderOwned: &leaderOwned) } if exited { try settleExitedGroup() } else { let code = signals.killGroup(pid) if code != 0 && code != ESRCH { if code == EPERM, try leaderHasExited(leaderOwned: &leaderOwned) { try settleExitedGroup() } else { throw AppCallbackSystemFailure(operation: "killpg", code: code) } } } } catch { failures.append(error) } // A failed group signal must not skip our independently owned, unreaped leader. if leaderOwned { let code = signals.killLeader(pid) if code != 0 && code != ESRCH { failures.append(AppCallbackSystemFailure(operation: "kill callback leader", code: code)) } } if !failures.isEmpty { throw AppCallbackProcessFailure(failures: failures) } }
private func leaderHasExited(leaderOwned: inout Bool) throws -> Bool { var info = siginfo_t() while waitid(P_PID, id_t(pid), &info, WEXITED | WNOHANG | WNOWAIT) == -1 { if errno == EINTR { continue } let code = errno if code == ECHILD { leaderOwned = false } throw AppCallbackSystemFailure(operation: "verify callback leader exit", code: code) } return info.si_pid == pid }
private func settleExitedGroup() throws { let deadline = ContinuousClock.now.advanced(by: .milliseconds(250)) var lastSignalCode: Int32 = 0 while true { let members = try groupMembers(pid) guard AppCallbackGroupInspection.isKnownExitedGroup(leader: pid, members: members) else { throw AppCallbackSystemFailure(operation: "inspect callback process group (\(pid))", code: EIO) } if AppCallbackGroupInspection.isZombieOnly(leader: pid, members: members) { return } // Signalable membership disappears before process states settle; do not demand a second successful kill. if ContinuousClock.now >= deadline { let states = members.map { "\($0.pid):\($0.state)" }.joined(separator: ",") throw AppCallbackSystemFailure( operation: "killpg (\(pid); members=\(states))", code: lastSignalCode == EPERM ? EPERM : ETIMEDOUT) } lastSignalCode = signals.killGroup(pid) if lastSignalCode != 0 && lastSignalCode != ESRCH && lastSignalCode != EPERM { throw AppCallbackSystemFailure(operation: "killpg", code: lastSignalCode) } if poll(nil, 0, 10) == -1 && errno != EINTR { throw AppCallbackSystemFailure(operation: "poll callback group cleanup", code: errno) } } }
private enum CleanupReap { case reaped case unavailable(AppCallbackSystemFailure) case deferred(AppCallbackSystemFailure) }
private func reapForCleanup() -> CleanupReap { let deadline = ContinuousClock.now.advanced(by: .milliseconds(250)) while true { var value: Int32 = 0 let waited = waitpid(pid, &value, WNOHANG) if waited == pid { return .reaped } if waited == -1 && errno != EINTR { let code = errno let failure = AppCallbackSystemFailure(operation: "waitpid cleanup (\(pid))", code: code) return code == ECHILD ? .unavailable(failure) : .deferred(failure) } if ContinuousClock.now >= deadline { return .deferred(AppCallbackSystemFailure(operation: "waitpid cleanup (\(pid))", code: ETIMEDOUT)) } if poll(nil, 0, 10) == -1 && errno != EINTR { return .deferred(AppCallbackSystemFailure(operation: "poll callback cleanup", code: errno)) } } }
private static func reapInBackground(_ pid: pid_t) { // Failed signaling cannot delay feedback, but the child must still be reaped when it eventually exits. let thread = Thread { var value: Int32 = 0 while waitpid(pid, &value, 0) == -1 { if errno == EINTR { continue } logCleanup(AppCallbackSystemFailure(operation: "waitpid deferred cleanup (\(pid))", code: errno)) return } } thread.name = "Parcel callback cleanup \(pid)" thread.qualityOfService = .utility thread.start() }
private func drain(_ descriptor: Int32, into output: inout AppCallbackOutput) throws -> Bool { var buffer = [UInt8](repeating: 0, count: 4096) // Bound each pass so continuous output cannot starve timeout or shutdown checks. for _ in 0..<16 { let count = buffer.withUnsafeMutableBytes { Darwin.read(descriptor, $0.baseAddress, $0.count) } if count > 0 { output.append(Data(buffer.prefix(count))) } else if count == 0 { return false } else if errno == EAGAIN || errno == EWOULDBLOCK { return true } else if errno != EINTR { throw AppCallbackSystemFailure(operation: "read callback output", code: errno) } } return true }
private static func makeEventQueue(output: Int32, error: Int32) throws -> Int32 { let descriptor = kqueue() guard descriptor >= 0 else { throw AppCallbackSystemFailure(operation: "callback kqueue", code: errno) } do { guard fcntl(descriptor, F_SETFD, FD_CLOEXEC) != -1 else { throw AppCallbackSystemFailure(operation: "callback kqueue close-on-exec", code: errno) } try updateEventQueue( descriptor, event: event(ident: 1, filter: Int16(EVFILT_USER), flags: UInt16(EV_ADD | EV_CLEAR))) for pipe in [output, error] { try updateEventQueue( descriptor, event: event(ident: UInt64(pipe), filter: Int16(EVFILT_READ), flags: UInt16(EV_ADD))) } return descriptor } catch { closeDescriptor(descriptor) throw error } }
private static func event(ident: UInt64, filter: Int16, flags: UInt16, notes: UInt32 = 0) -> kevent64_s { kevent64_s(ident: ident, filter: filter, flags: flags, fflags: notes, data: 0, udata: 0, ext: (0, 0)) }
private static func updateEventQueue(_ descriptor: Int32, event: kevent64_s) throws { var event = event while kevent64(descriptor, &event, 1, nil, 0, 0, nil) == -1 { if errno == EINTR { continue } throw AppCallbackSystemFailure(operation: "update callback events", code: errno) } }
private static func makePipe() throws -> (read: Int32, write: Int32) { var descriptors: [Int32] = [0, 0] guard pipe(&descriptors) == 0 else { throw AppCallbackSystemFailure(operation: "pipe", code: errno) } do { for descriptor in descriptors { guard fcntl(descriptor, F_SETFD, FD_CLOEXEC) != -1 else { throw AppCallbackSystemFailure(operation: "pipe close-on-exec", code: errno) } } let flags = fcntl(descriptors[0], F_GETFL) guard flags != -1, fcntl(descriptors[0], F_SETFL, flags | O_NONBLOCK) != -1 else { throw AppCallbackSystemFailure(operation: "nonblocking callback output", code: errno) } return (descriptors[0], descriptors[1]) } catch { for descriptor in descriptors { closeDescriptor(descriptor) } throw error } }
private static func withCStringArray<Value>( _ strings: [String], body: (UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>) throws -> Value ) throws -> Value { var pointers: [UnsafeMutablePointer<CChar>?] = [] defer { for pointer in pointers { free(pointer) } } for string in strings { guard let pointer = string.withCString({ strdup($0) }) else { throw AppCallbackSystemFailure(operation: "callback string allocation", code: ENOMEM) } pointers.append(pointer) } pointers.append(nil) return try pointers.withUnsafeMutableBufferPointer { buffer in guard let baseAddress = buffer.baseAddress else { preconditionFailure("Missing callback strings") } return try body(baseAddress) } }
private static func check(_ code: Int32, _ operation: String) throws { guard code == 0 else { throw AppCallbackSystemFailure(operation: operation, code: code) } }
private static func closeDescriptor(_ descriptor: Int32) { if Darwin.close(descriptor) == -1 { logCleanup(AppCallbackSystemFailure(operation: "close callback descriptor", code: errno)) } }
private static func destroy(_ code: Int32, _ operation: String) { if code != 0 { logCleanup(AppCallbackSystemFailure(operation: operation, code: code)) } }
private static func logCleanup(_ error: any Error) { Logger(subsystem: "dev.vinnymac.parcel", category: "callbacks") .error("Callback cleanup failed: \(error.localizedDescription, privacy: .public)") }}
struct AppCallbackSignalOperations: Sendable { // Return error codes directly so injected operations do not alter thread-local errno. let killGroup: @Sendable (pid_t) -> Int32 let killLeader: @Sendable (pid_t) -> Int32
static let system = AppCallbackSignalOperations( killGroup: { Darwin.killpg($0, SIGKILL) == -1 ? errno : 0 }, killLeader: { Darwin.kill($0, SIGKILL) == -1 ? errno : 0 })}
struct AppCallbackGroupMember: Equatable, Sendable { let pid: pid_t let group: pid_t let state: Int32}
enum AppCallbackGroupInspection { static func isZombieOnly(leader: pid_t, members: [AppCallbackGroupMember]) -> Bool { isKnownExitedGroup(leader: leader, members: members) && members.allSatisfy { $0.state == SZOMB } }
static func isKnownExitedGroup(leader: pid_t, members: [AppCallbackGroupMember]) -> Bool { members.contains { $0.pid == leader && $0.state == SZOMB } && Set(members.map(\.pid)).count == members.count && members.allSatisfy { $0.pid > 1 && $0.group == leader && [SIDL, SRUN, SSLEEP, SSTOP, SZOMB].contains($0.state) } }
static func members(of group: pid_t) throws -> [AppCallbackGroupMember] { var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PGRP, group] let stride = MemoryLayout<kinfo_proc>.stride for _ in 0..<3 { var size = 0 guard sysctl(&mib, UInt32(mib.count), nil, &size, nil, 0) == 0 else { throw AppCallbackSystemFailure(operation: "size callback process group", code: errno) } guard size % stride == 0 && size / stride < 4096 else { throw AppCallbackSystemFailure(operation: "callback process group size", code: EOVERFLOW) } var records = [kinfo_proc](repeating: kinfo_proc(), count: size / stride + 8) var actualSize = records.count * stride let result = records.withUnsafeMutableBufferPointer { buffer in sysctl(&mib, UInt32(mib.count), buffer.baseAddress, &actualSize, nil, 0) } if result == 0 { guard actualSize % stride == 0 && actualSize <= records.count * stride else { throw AppCallbackSystemFailure(operation: "callback process group snapshot", code: EOVERFLOW) } return records.prefix(actualSize / stride).map { AppCallbackGroupMember( pid: $0.kp_proc.p_pid, group: $0.kp_eproc.e_pgid, state: Int32($0.kp_proc.p_stat)) } } let code = errno if code != ENOMEM && code != EINTR { throw AppCallbackSystemFailure(operation: "read callback process group", code: code) } } throw AppCallbackSystemFailure(operation: "unstable callback process group", code: EAGAIN) }}
private struct AppCallbackProcessFailure: Error, LocalizedError { let failures: [any Error] var errorDescription: String? { failures.map(\.localizedDescription).joined(separator: "\n") }}
private struct AppCallbackSystemFailure: Error, LocalizedError { let operation: String let code: Int32 var errorDescription: String? { "\(operation): \(String(cString: strerror(code)))" }}