import Foundation import ParcelCore import ParcelEngine import ParcelUI @MainActor final class TourTidyTransaction { struct Operations { let checkpoint: @MainActor () throws -> Void let arrange: @MainActor () async throws -> [String] let commit: @MainActor () async throws -> Void let release: @MainActor () -> Void let drain: @MainActor () async throws -> Void let restoreWorkspace: @MainActor () async throws -> Void let hasPotentialWindowMovement: @MainActor () -> Bool let recordRecovery: @MainActor (Bool) throws -> Void var describeFailure: @MainActor (any Error) -> String = { $0.localizedDescription } } private let operations: Operations private let log: TourTidyLog private let deadline: Duration private let waitForDeadline: @MainActor (Duration) async throws -> Void private var isBusy = false private var committed = false private var deadlineExpired = false private var deadlineFailure: (any Error)? init( operations: Operations, deadline: Duration = .seconds(20), log: TourTidyLog = TourTidyLog(), waitForDeadline: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) { self.operations = operations self.log = log self.deadline = deadline self.waitForDeadline = waitForDeadline } func run() async -> TourStartResult { guard !isBusy else { return .failedBeforeWrite(details: [TourSetupFailure.busy.localizedDescription]) } isBusy = true committed = false deadlineExpired = false deadlineFailure = nil let interval = log.begin() defer { isBusy = false; log.end(interval) } let operation = Task { @MainActor in await self.runAttempt() } let timer = Task { @MainActor in do { try Task.checkCancellation() try await self.waitForDeadline(self.deadline) guard !Task.isCancelled, !self.committed else { return } self.deadlineExpired = true operation.cancel() } catch { guard !Task.isCancelled, !self.committed else { return } self.deadlineFailure = error operation.cancel() } } let result = await withTaskCancellationHandler { await operation.value } onCancel: { operation.cancel() } timer.cancel() await timer.value return result } private func runAttempt() async -> TourStartResult { do { try Task.checkCancellation() log.phase("checkpoint") try operations.checkpoint() } catch is CancellationError { return await recover(from: CancellationError()) } catch { log.failure(error); return .progressSaveFailed } do { log.phase("arrange") let partial = try await operations.arrange() try Task.checkCancellation() log.phase("commit") try await operations.commit() try Task.checkCancellation() // The deadline cannot interleave with this commitment and global release. committed = true operations.release() log.phase(partial.isEmpty ? "completed" : "completed-partial") return partial.isEmpty ? .success : .partial(details: partial) } catch { return await recover(from: error) } } private func recover(from failure: any Error) async -> TourStartResult { let originalFailure = deadlineFailure ?? (deadlineExpired ? TourSetupFailure.tidyFailed : failure) log.failure(originalFailure) let original = operations.describeFailure(originalFailure) // This owned recovery task is deliberately independent of action cancellation. return await Task { @MainActor in var details = [original] do { self.log.phase("drain") try await self.operations.drain() let moved = self.operations.hasPotentialWindowMovement() if moved { self.log.phase("restore") try await self.operations.restoreWorkspace() } try self.operations.recordRecovery(false) self.log.phase(moved ? "restored" : "failed-before-write") return moved ? .restored(details: details) : .failedBeforeWrite(details: details) } catch { self.log.failure(error) if let original = originalFailure as? EngineWorkspaceFailure, case .unsettled(let arrangementWindows) = original, let recovery = error as? EngineWorkspaceFailure, case .unsettled(let recoveryWindows) = recovery { var seen: Set = [] let windows = (arrangementWindows + recoveryWindows).filter { seen.insert($0).inserted } details = [self.operations.describeFailure(EngineWorkspaceFailure.unsettled(windows))] } else { details.append(self.operations.describeFailure(error)) } do { try self.operations.recordRecovery(true) } catch { self.log.failure(error) details.append(self.operations.describeFailure(error)) } self.log.phase("recovery-required") return .recoveryRequired(details: details) } }.value } }