Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import Foundationimport OSLogimport ParcelConfigimport ParcelEngine
struct AppCallbackTiming: Sendable { let now: @Sendable () -> ContinuousClock.Instant let sleep: @Sendable (Duration) async throws -> Void
static let system = AppCallbackTiming( now: { ContinuousClock.now }, sleep: { try await Task.sleep(for: $0) })}
@MainActorfinal class AppCallbackRunner { private let executor: AppCallbackExecutor private let onFailure: @MainActor (any Error) -> Void private var configuration: CallbackConfiguration private var pending: [EngineCallbackInvocation] = [] private var task: Task<Void, Never>? private var overflowTask: Task<Void, Never>? private var droppedCount = 0 private var accepting = true private let capacity: Int private let overflowFeedbackDelay: Duration private let timing: AppCallbackTiming
init( configuration: CallbackConfiguration = CallbackConfiguration(), capacity: Int = 32, timeout: Duration = .seconds(30), overflowFeedbackDelay: Duration = .seconds(1), timing: AppCallbackTiming = .system, onFailure: @escaping @MainActor (any Error) -> Void ) { precondition(capacity > 0 && overflowFeedbackDelay > .zero) self.configuration = configuration self.capacity = capacity self.overflowFeedbackDelay = overflowFeedbackDelay self.timing = timing self.executor = AppCallbackExecutor(timeout: timeout, callbackNow: timing.now) self.onFailure = onFailure }
func start() { accepting = true }
@discardableResult func applyConfiguration(_ configuration: CallbackConfiguration) -> Int { self.configuration = configuration let previousCount = pending.count pending.removeAll { !isCurrent($0) } return previousCount - pending.count }
private func isCurrent(_ invocation: EngineCallbackInvocation) -> Bool { !invocation.arguments.isEmpty && configuration.commands[invocation.event] == invocation.arguments }
func submit(_ invocation: EngineCallbackInvocation) { guard accepting, isCurrent(invocation) else { return } guard pending.count < capacity else { recordOverflow() return } pending.append(invocation) guard task == nil else { return } task = Task { [weak self] in guard let self else { return } defer { self.task = nil } while !self.pending.isEmpty, !Task.isCancelled { let invocation = self.pending.removeFirst() guard self.isCurrent(invocation) else { continue } do { try await self.executor.run(invocation) } catch is CancellationError { return } catch { self.onFailure(error) } } } }
private func recordOverflow() { droppedCount += 1 guard overflowTask == nil else { return } overflowTask = Task { [weak self] in guard let self else { return } do { try await self.timing.sleep(self.overflowFeedbackDelay) } catch { precondition(error is CancellationError) self.overflowTask = nil return } self.overflowTask = nil let count = self.droppedCount self.droppedCount = 0 self.onFailure(AppText.detail("Callbacks dropped: %@. Check for a slow callback.", String(count))) } }
func waitUntilIdle() async { while task != nil || overflowTask != nil { await task?.value await overflowTask?.value } }
func stop() async { accepting = false pending.removeAll() task?.cancel() overflowTask?.cancel() await executor.stop() await task?.value await overflowTask?.value task = nil overflowTask = nil droppedCount = 0 }}
actor AppCallbackExecutor { private var running: (process: AppCallbackProcess, task: Task<AppCallbackProcess.Result, any Error>)? private let timeout: Duration private let baseEnvironment: [String: String] private let callbackNow: @Sendable () -> ContinuousClock.Instant private let onOutput: @Sendable (CallbackEvent, AppCallbackProcess.Result) -> Void
init( timeout: Duration = .seconds(30), baseEnvironment: [String: String] = ProcessInfo.processInfo.environment, callbackNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }, onOutput: @escaping @Sendable (CallbackEvent, AppCallbackProcess.Result) -> Void = AppCallbackExecutor.log ) { precondition(timeout > .zero) self.timeout = timeout self.baseEnvironment = baseEnvironment self.callbackNow = callbackNow self.onOutput = onOutput }
func run(_ invocation: EngineCallbackInvocation) async throws { precondition(running == nil, "Callbacks must run serially") try CallbackConfiguration(commands: [invocation.event: invocation.arguments]).validate() guard !invocation.arguments.isEmpty else { return } try Task.checkCancellation() let process: AppCallbackProcess do { process = try AppCallbackProcess.spawn( arguments: invocation.arguments, environment: environment(for: invocation), callbackNow: callbackNow) } catch { throw AppText.detail( "Could not start callback: %@", "\(invocation.event.rawValue): \(error.localizedDescription)") } let timeout = self.timeout let task = Task { try await process.collect(timeout: timeout) } running = (process, task) defer { running = nil } let result: AppCallbackProcess.Result do { result = try await withTaskCancellationHandler { try await task.value } onCancel: { process.requestStop() } } catch { throw AppText.detail("Callback failed: %@", "\(invocation.event.rawValue): \(error.localizedDescription)") } onOutput(invocation.event, result) if Task.isCancelled || result.completion == .stopped { throw CancellationError() } var detail = invocation.event.rawValue let stderr = result.standardError.tail(maximumBytes: 1024) if !stderr.isEmpty { detail += "\n" + stderr } switch result.completion { case .exited(0): return case .timedOut: throw AppText.detail("Callback timed out: %@", detail) case .exited(let status): throw AppText.detail( "Callback failed: %@", "\(invocation.event.rawValue) (\(status))" + stderrSuffix(stderr)) case .signaled(let signal): throw AppText.detail( "Callback terminated by signal: %@", "\(invocation.event.rawValue) (\(signal))" + stderrSuffix(stderr)) case .stopped: throw CancellationError() } }
private func stderrSuffix(_ stderr: String) -> String { stderr.isEmpty ? "" : "\n" + stderr }
private func environment(for invocation: EngineCallbackInvocation) -> [String: String] { let contextKeys: Set<String> = [ "PARCEL_EVENT", "PARCEL_WINDOW_ID", "PARCEL_APP_PID", "PARCEL_BUNDLE_ID", "PARCEL_WINDOW_TITLE", "PARCEL_DISPLAY_ID", "PARCEL_SPACE_ID", "PARCEL_LAYOUT", ] var environment = [ "PATH": baseEnvironment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": baseEnvironment["HOME"] ?? FileManager.default.homeDirectoryForCurrentUser.path, "LANG": baseEnvironment["LANG"] ?? "en_US.UTF-8", ] environment.merge(invocation.environment.filter { contextKeys.contains($0.key) }) { _, new in new } environment["PARCEL_EVENT"] = invocation.event.rawValue return environment }
func stop() async { guard let running else { return } running.process.requestStop() // run() owns error delivery; shutdown only waits for its worker to finish. _ = await running.task.result }
private static func log(_ event: CallbackEvent, _ result: AppCallbackProcess.Result) { let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "callbacks") logger.info( "Callback \(event.rawValue, privacy: .public): \(String(describing: result.completion), privacy: .public)" ) if !result.standardOutput.bytes.isEmpty { logger.info( "stdout (\(result.standardOutput.discardedBytes, privacy: .public) bytes discarded): \(result.standardOutput.tail(), privacy: .private)" ) } if !result.standardError.bytes.isEmpty { logger.error( "stderr (\(result.standardError.discardedBytes, privacy: .public) bytes discarded): \(result.standardError.tail(), privacy: .private)" ) } }}