import CryptoKit import Darwin public import Foundation public import ParcelCore import Synchronization public enum WorkspaceStateStoreError: Error, Sendable, Equatable { case invalidFileURL case unsupportedVersion(Int) case concurrentModification case defaultStoreUnavailableInTests } public struct WorkspaceStateStoreRecoveryError: Error, Sendable { public let recoveryURL: URL public let underlyingError: any Error public init(recoveryURL: URL, underlyingError: any Error) { self.recoveryURL = recoveryURL self.underlyingError = underlyingError } } public struct WorkspaceStateStore: Sendable { public static let currentVersion = 3 public static var defaultFileURL: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/dev.vinnymac.parcel", isDirectory: true) .appendingPathComponent("workspace-state.json", isDirectory: false) } public let fileURL: URL private let state = StoreState() private let now: @Sendable () -> Date private let synchronizeDirectory: @Sendable (Int32) throws -> Void public init(fileURL: URL) { self.init(fileURL: fileURL, now: { Date() }, synchronizeDirectory: Self.syncDirectory) } init( fileURL: URL, now: @escaping @Sendable () -> Date, synchronizeDirectory: @escaping @Sendable (Int32) throws -> Void = Self.syncDirectory ) { self.fileURL = fileURL self.now = now self.synchronizeDirectory = synchronizeDirectory } public func load() throws -> WorkspaceMemory { try validateFileURL() return try state.observation.withLock { observation in try withFileLock(createDirectory: false) { directory in guard directory != nil else { observation.revision = Revision(nil) return observation.emptyMemory } let data = try readData() let memory = try data.map { try decode( $0, timestamp: now().timeIntervalSince1970, titleSalt: observation.emptyMemory.titleSalt) } ?? observation.emptyMemory observation.revision = Revision(data) return memory } } } public func save(_ memory: WorkspaceMemory) throws { try validateFileURL() try memory.validate() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode( Storage(version: Self.currentVersion, titleSalt: memory.titleSalt, records: memory.records)) try state.observation.withLock { observation in try withFileLock(createDirectory: true) { directory in let previous = try readData() let revision = Revision(previous) if let expected = observation.revision, expected != revision { throw WorkspaceStateStoreError.concurrentModification } // Even a writer that skipped load must not erase corrupt or newer data. if let previous { _ = try decode( previous, timestamp: now().timeIntervalSince1970, titleSalt: observation.emptyMemory.titleSalt) } try writeAtomically(data, replacing: revision) observation.revision = Revision(data) guard let directory else { throw WorkspaceStateStoreError.invalidFileURL } try synchronizeDirectory(directory) } } } @discardableResult public func reset() throws -> URL? { try validateFileURL() return try state.observation.withLock { observation in var preservedURL: URL? do { return try withFileLock(createDirectory: false) { directory in guard let directory else { observation.revision = Revision(nil) return nil } guard try fileExists() else { observation.revision = Revision(nil) return nil } let recovery: URL? do { guard let data = try readData() else { throw posixError(ENOENT, path: fileURL.path) } _ = try decode( data, timestamp: now().timeIntervalSince1970, titleSalt: observation.emptyMemory.titleSalt) recovery = nil } catch { recovery = recoveryURL() } if let recovery { var descriptor = Darwin.open(fileURL.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) // A mode-zero file is unreadable, but an explicit reset must still retain its bytes. if descriptor < 0 { guard errno == EACCES else { throw posixError(errno, path: fileURL.path) } guard Darwin.chmod(fileURL.path, 0o600) == 0 else { throw posixError(errno, path: fileURL.path) } descriptor = Darwin.open(fileURL.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) } guard descriptor >= 0 else { throw posixError(errno, path: fileURL.path) } try withDescriptor(descriptor, path: fileURL.path) { descriptor in guard Darwin.fchmod(descriptor, 0o600) == 0 else { throw posixError(errno, path: fileURL.path) } guard Darwin.fsync(descriptor) == 0 else { throw posixError(errno, path: fileURL.path) } } guard Darwin.rename(fileURL.path, recovery.path) == 0 else { throw posixError(errno, path: fileURL.path) } preservedURL = recovery } else { guard Darwin.unlink(fileURL.path) == 0 else { throw posixError(errno, path: fileURL.path) } } observation.revision = Revision(nil) observation.emptyMemory = Self.freshMemory() try synchronizeDirectory(directory) return recovery } } catch { guard let preservedURL else { throw error } throw WorkspaceStateStoreRecoveryError(recoveryURL: preservedURL, underlyingError: error) } } } private func validateFileURL() throws { guard fileURL.isFileURL, !fileURL.path.contains("\0"), !fileURL.lastPathComponent.isEmpty else { throw WorkspaceStateStoreError.invalidFileURL } if Self.isTestProcess, fileURL.standardizedFileURL.resolvingSymlinksInPath() == Self.defaultFileURL.standardizedFileURL.resolvingSymlinksInPath() { throw WorkspaceStateStoreError.defaultStoreUnavailableInTests } _ = try fileExists() } private static var isTestProcess: Bool { let process = ProcessInfo.processInfo if process.environment["XCTestConfigurationFilePath"] != nil || process.environment["XCTestBundlePath"] != nil || process.arguments.contains("--testing-library") || process.arguments.first.map({ $0.split(separator: "/").contains { $0.hasSuffix(".xctest") } }) == true { return true } // Xcode can host Swift Testing in an app; its loaded test bundle is a runtime signal, not an opt-in flag. return (0..<_dyld_image_count()).contains { index in guard let name = _dyld_get_image_name(index) else { return false } return String(cString: name).split(separator: "/").contains { $0.hasSuffix(".xctest") } } } private func fileExists() throws -> Bool { var info = stat() guard Darwin.lstat(fileURL.path, &info) == 0 else { let code = errno if code == ENOENT { return false } throw posixError(code, path: fileURL.path) } guard info.st_mode & S_IFMT == S_IFREG else { throw posixError(info.st_mode & S_IFMT == S_IFDIR ? EISDIR : EINVAL, path: fileURL.path) } return true } private func readData() throws -> Data? { guard try fileExists() else { return nil } return try Data(contentsOf: fileURL) } private func withFileLock(createDirectory: Bool, _ operation: (Int32?) throws -> T) throws -> T { let parent = fileURL.deletingLastPathComponent() if createDirectory { try FileManager.default.createDirectory( at: parent, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) } let descriptor = Darwin.open(parent.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) guard descriptor >= 0 else { let code = errno if code == ENOENT, !createDirectory { return try operation(nil) } throw posixError(code, path: parent.path) } return try withDescriptor(descriptor, path: parent.path) { directory in try repairMode(directory, mode: 0o700, path: parent.path) let lockPath = fileURL.path + ".lock" let lock = Darwin.open(lockPath, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600) guard lock >= 0 else { throw posixError(errno, path: lockPath) } return try withDescriptor(lock, path: lockPath) { lock in var info = stat() guard Darwin.fstat(lock, &info) == 0 else { throw posixError(errno, path: lockPath) } guard info.st_mode & S_IFMT == S_IFREG else { throw posixError(EINVAL, path: lockPath) } try repairMode(lock, mode: 0o600, path: lockPath) while flock(lock, LOCK_EX) != 0 { let code = errno if code == EINTR { continue } throw posixError(code, path: lockPath) } // The sidecar must stay in place: unlinking it lets later writers lock a different inode. return try operation(directory) } } } private func repairMode(_ descriptor: Int32, mode: mode_t, path: String) throws { var info = stat() guard Darwin.fstat(descriptor, &info) == 0 else { throw posixError(errno, path: path) } if info.st_mode & 0o7777 != mode { guard Darwin.fchmod(descriptor, mode) == 0 else { throw posixError(errno, path: path) } guard Darwin.fstat(descriptor, &info) == 0 else { throw posixError(errno, path: path) } } guard info.st_mode & 0o7777 == mode else { throw posixError(EPERM, path: path) } } private func withDescriptor(_ descriptor: Int32, path: String, _ operation: (Int32) throws -> T) throws -> T { let result: T do { result = try operation(descriptor) } catch { guard Darwin.close(descriptor) == 0 else { throw posixError(errno, path: path) } throw error } guard Darwin.close(descriptor) == 0 else { throw posixError(errno, path: path) } return result } private static func syncDirectory(_ descriptor: Int32) throws { while Darwin.fsync(descriptor) != 0 { let code = errno if code == EINTR { continue } throw NSError(domain: NSPOSIXErrorDomain, code: Int(code)) } } private func recoveryURL() -> URL { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let timestamp = formatter.string(from: now()).replacingOccurrences(of: ":", with: "-") return fileURL.deletingLastPathComponent().appendingPathComponent( "\(fileURL.deletingPathExtension().lastPathComponent).\(timestamp).\(UUID().uuidString).unreadable.json") } private func writeAtomically(_ data: Data, replacing revision: Revision) throws { var template = fileURL.deletingLastPathComponent().appendingPathComponent(".workspace-state.XXXXXX").path .utf8CString var descriptor = try template.withUnsafeMutableBufferPointer { buffer in guard let pointer = buffer.baseAddress else { throw WorkspaceStateStoreError.invalidFileURL } return Darwin.mkstemp(pointer) } guard descriptor >= 0 else { throw posixError(errno, path: fileURL.path) } let temporaryPath = String(decoding: template.dropLast().map { UInt8(bitPattern: $0) }, as: UTF8.self) do { guard Darwin.fchmod(descriptor, 0o600) == 0 else { throw posixError(errno, path: temporaryPath) } try data.withUnsafeBytes { bytes in guard let base = bytes.baseAddress else { return } var offset = 0 while offset < bytes.count { let written = Darwin.write(descriptor, base.advanced(by: offset), bytes.count - offset) if written < 0 { let code = errno if code == EINTR { continue } throw posixError(code, path: temporaryPath) } guard written > 0 else { throw posixError(EIO, path: temporaryPath) } offset += written } } guard Darwin.fsync(descriptor) == 0 else { throw posixError(errno, path: temporaryPath) } let closed = Darwin.close(descriptor) descriptor = -1 guard closed == 0 else { throw posixError(errno, path: temporaryPath) } guard try Revision(readData()) == revision else { throw WorkspaceStateStoreError.concurrentModification } guard Darwin.rename(temporaryPath, fileURL.path) == 0 else { throw posixError(errno, path: fileURL.path) } } catch { if descriptor >= 0 { guard Darwin.close(descriptor) == 0 else { throw posixError(errno, path: temporaryPath) } } if Darwin.unlink(temporaryPath) != 0, errno != ENOENT { throw posixError(errno, path: temporaryPath) } throw error } } private func decode(_ data: Data, timestamp: TimeInterval, titleSalt: Data) throws -> WorkspaceMemory { let decoder = JSONDecoder() let header = try decoder.decode(Header.self, from: data) switch header.version { case 1: let legacy = try decoder.decode(LegacyStorage.self, from: data) return try WorkspaceMemory( records: legacy.records.map { try $0.migrated(timestamp: timestamp) }, titleSalt: titleSalt) case 2: let legacy = try decoder.decode(VersionTwoStorage.self, from: data) let seeded = WorkspaceMemory(titleSalt: titleSalt) return try WorkspaceMemory( records: legacy.records.map { record in WorkspaceMemory.Record( workspace: record.workspace, windows: try record.windows.map { window in WorkspaceMemory.SavedWindow( token: window.token, bundleID: window.bundleID, titleDigest: try seeded.titleDigest(for: window.title), role: window.role, subrole: window.subrole, display: window.display, isFloating: window.isFloating, normalizedFloatingFrame: window.normalizedFloatingFrame) }, lastSeen: timestamp) }, titleSalt: seeded.titleSalt) case Self.currentVersion: let storage = try decoder.decode(Storage.self, from: data) return try WorkspaceMemory(records: storage.records, titleSalt: storage.titleSalt) default: throw WorkspaceStateStoreError.unsupportedVersion(header.version) } } private static func freshMemory() -> WorkspaceMemory { WorkspaceMemory(titleSalt: SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) }) } private func posixError(_ code: Int32, path: String) -> NSError { NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: path]) } private struct Revision: Sendable, Equatable { let digest: Data? init(_ data: Data?) { digest = data.map { Data(SHA256.hash(data: $0)) } } } private struct Observation: Sendable { var revision: Revision? var emptyMemory = WorkspaceStateStore.freshMemory() } private final class StoreState: Sendable { let observation = Mutex(Observation()) } private struct Header: Decodable { let version: Int } private struct Storage: Codable { let version: Int let titleSalt: Data let records: [WorkspaceMemory.Record] } private struct VersionTwoStorage: Decodable { let records: [VersionTwoRecord] } private struct VersionTwoRecord: Decodable { let workspace: Workspace let windows: [VersionTwoWindow] private enum CodingKeys: String, CodingKey { case workspace, windows } private struct RatioCheck: Decodable { let key: WorkspaceKey let ratio: Double let configuredRatio: Double? } init(from decoder: any Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let check = try container.decode(RatioCheck.self, forKey: .workspace) guard check.ratio.isFinite, MainRatio.bounds.contains(check.ratio), check.configuredRatio.map({ $0.isFinite && MainRatio.bounds.contains($0) }) != false else { throw WorkspaceMemoryError.invalidWorkspace(check.key) } workspace = try container.decode(Workspace.self, forKey: .workspace) windows = try container.decode([VersionTwoWindow].self, forKey: .windows) } } private struct VersionTwoWindow: Decodable { let token: WindowID let bundleID: String let title: String let role: String let subrole: String? let display: DisplayID let isFloating: Bool let normalizedFloatingFrame: Rect? } private struct LegacyStorage: Decodable { let records: [LegacyRecord] } private struct LegacyRecord: Decodable { let key: WorkspaceKey let layout: Layout let ratio: Double let gaps: Gaps let reservedEdges: Insets let windowCap: Int let whenFull: WhenFull func migrated(timestamp: TimeInterval) throws -> WorkspaceMemory.Record { guard ratio.isFinite, MainRatio.bounds.contains(ratio), windowCap > 0 else { throw WorkspaceMemoryError.invalidWorkspace(key) } return WorkspaceMemory.Record( workspace: Workspace( key: key, layout: layout, ratio: MainRatio(ratio), gaps: gaps, reservedEdges: reservedEdges, windowCap: windowCap, whenFull: whenFull), lastSeen: timestamp) } } }