Files
VirtualBuddy/VirtualCore/Source/SavedSession/SavedSessionConcurrency.swift
Guilherme Rambo 2a7cf4151b New virtual machine state preservation system (#780)
* Fix HostingWindowController allowing repeated requests to close while waiting for confirmation

* New virtual machine state preservation system with automatic save on close/quit and safe restoration

* Use visible directories for saved state storage for easier debugging in Finder

* Hide state restoration controls for unsupported Linux VMs

* Add app-level preference for what happens by default when attempting to close a running VM

* Use a custom sheet for VM close confirmation

* Improve VM close choice sheet

* Harden session storage against path traversal, fix race conditions in state coordination
2026-10-05 12:51:43 -03:00

46 lines
1.3 KiB
Swift

import Foundation
/// Runs file work away from the main actor. Cancelling the caller cancels the work at its next cancellation check.
func performOffMainActor<T: Sendable>(_ work: @escaping @Sendable () throws -> T) async throws -> T {
let task = Task.detached(priority: .userInitiated) { try work() }
return try await withTaskCancellationHandler {
try await task.value
} onCancel: {
task.cancel()
}
}
/// Serializes operations on a virtual machine. Waiters are served in the order they arrived.
@MainActor
final class VMOperationLease {
private var isHeld = false
private var waiters = [CheckedContinuation<Void, Never>]()
var isBusy: Bool { isHeld }
func acquire() async {
guard isHeld else {
isHeld = true
return
}
await withCheckedContinuation { waiters.append($0) }
}
func release() {
if waiters.isEmpty {
isHeld = false
} else {
/// Ownership is handed over directly so that nobody can sneak in between.
waiters.removeFirst().resume()
}
}
func perform<T>(_ operation: () async throws -> T) async rethrows -> T {
await acquire()
defer { release() }
return try await operation()
}
}