import CryptoKit import Darwin public import Foundation public import ParcelCore import Synchronization public enum SetupStoreError: Error, Sendable, Equatable { case invalidFileURL case unsupportedVersion(Int) case concurrentModification case defaultStoreUnavailableInTests } public struct SetupStoreCorruptionError: Error, Sendable { public let backupURL: URL public let underlyingError: any Error public init(backupURL: URL, underlyingError: any Error) { self.backupURL = backupURL self.underlyingError = underlyingError } } public struct SetupStore: Sendable { public static let currentVersion = 1 public static var defaultFileURL: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/dev.vinnymac.parcel", isDirectory: true) .appendingPathComponent("setups.json", isDirectory: false) } public let fileURL: URL private let state = StoreState() private let synchronizeFile: @Sendable (Int32) throws -> Void private let synchronizeDirectory: @Sendable (Int32) throws -> Void public init(fileURL: URL) { self.init(fileURL: fileURL, synchronizeFile: Self.synchronize, synchronizeDirectory: Self.synchronize) } init( fileURL: URL, synchronizeFile: @escaping @Sendable (Int32) throws -> Void = Self.synchronize, synchronizeDirectory: @escaping @Sendable (Int32) throws -> Void = Self.synchronize ) { self.fileURL = fileURL self.synchronizeFile = synchronizeFile self.synchronizeDirectory = synchronizeDirectory } /// Missing storage is empty; corruption is preserved and surfaced, never reset. public func load() throws -> SetupCatalog { try validateFileURL() return try state.observation.withLock { observation in try withFileLock(createDirectory: false) { directory in let data = try directory.flatMap { try read(fileURL.lastPathComponent, in: $0) } observation.revision = Revision(data) guard let data, let directory else { observation.recovery = nil return try SetupCatalog() } return try decode(data, in: directory, observation: &observation) } } } public func save(_ catalog: SetupCatalog) throws { try validateFileURL() try catalog.validate() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode(Storage(version: Self.currentVersion, setups: catalog.setups)) try state.observation.withLock { observation in try withFileLock(createDirectory: true) { directory in guard let directory else { throw SetupStoreError.invalidFileURL } let previous = try read(fileURL.lastPathComponent, in: directory) let revision = Revision(previous) if let expected = observation.revision, expected != revision { throw SetupStoreError.concurrentModification } // A caller that skipped load cannot erase corrupt or newer storage either. if let previous { _ = try decode(previous, in: directory, observation: &observation) } try writeAtomically(data, to: fileURL.lastPathComponent, in: directory) { guard try Revision(read(fileURL.lastPathComponent, in: directory)) == revision else { throw SetupStoreError.concurrentModification } } observation.revision = Revision(data) observation.recovery = nil try synchronizeDirectory(directory) } } } private func decode(_ data: Data, in directory: Int32, observation: inout Observation) throws -> SetupCatalog { let revision = Revision(data) if let recovery = observation.recovery, recovery.revision == revision { throw recovery.error } let decoder = JSONDecoder() do { let header = try decoder.decode(Header.self, from: data) guard header.version == Self.currentVersion else { throw SetupStoreError.unsupportedVersion(header.version) } let storage = try decoder.decode(Storage.self, from: data) let catalog = try SetupCatalog(setups: storage.setups) observation.recovery = nil return catalog } catch let error as SetupStoreError { throw error } catch { let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() let name = "\(fileURL.deletingPathExtension().lastPathComponent).\(digest).unreadable.json" let backupURL = fileURL.deletingLastPathComponent().appendingPathComponent(name) if let existing = try read(name, in: directory) { guard existing == data else { throw posixError(EEXIST, path: backupURL.path) } } else { try writeAtomically(data, to: name, in: directory) { guard try read(name, in: directory) == nil else { throw posixError(EEXIST, path: backupURL.path) } } } let corruption = SetupStoreCorruptionError(backupURL: backupURL, underlyingError: error) // Remember preservation before syncing: a retry must not produce more evidence or permit a save. observation.revision = revision observation.recovery = Recovery(revision: revision, error: corruption) do { try synchronizeDirectory(directory) } catch { let preservation = SetupStoreCorruptionError(backupURL: backupURL, underlyingError: error) observation.recovery = Recovery(revision: revision, error: preservation) throw preservation } throw corruption } } private func validateFileURL() throws { guard fileURL.isFileURL, !fileURL.path.contains("\0"), !fileURL.lastPathComponent.isEmpty, !fileURL.hasDirectoryPath, fileURL.lastPathComponent != "/" else { throw SetupStoreError.invalidFileURL } if Self.isTestProcess, fileURL.standardizedFileURL.resolvingSymlinksInPath() == Self.defaultFileURL.standardizedFileURL.resolvingSymlinksInPath() { throw SetupStoreError.defaultStoreUnavailableInTests } } 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 } 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 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 requireMode(directory, mode: 0o700, type: S_IFDIR, path: parent.path) let name = fileURL.lastPathComponent + ".lock" let lock = Darwin.openat(directory, name, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, 0o600) guard lock >= 0 else { throw posixError(errno, path: fileURL.path + ".lock") } return try withDescriptor(lock, path: fileURL.path + ".lock") { lock in try requireMode(lock, mode: 0o600, type: S_IFREG, path: fileURL.path + ".lock") while flock(lock, LOCK_EX) != 0 { let code = errno if code == EINTR { continue } throw posixError(code, path: fileURL.path + ".lock") } // Keep the sidecar inode in place so all writers lock the same file. return try operation(directory) } } } private func read(_ name: String, in directory: Int32) throws -> Data? { let descriptor = Darwin.openat(directory, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) guard descriptor >= 0 else { let code = errno if code == ENOENT { return nil } throw posixError(code, path: name) } return try withDescriptor(descriptor, path: name) { descriptor in try requireMode(descriptor, mode: 0o600, type: S_IFREG, path: name) return try FileHandle(fileDescriptor: descriptor, closeOnDealloc: false).readToEnd() ?? Data() } } private func requireMode(_ descriptor: Int32, mode: mode_t, type: mode_t, path: String) throws { var info = stat() guard Darwin.fstat(descriptor, &info) == 0 else { throw posixError(errno, path: path) } guard info.st_mode & S_IFMT == type else { throw posixError(EINVAL, 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 writeAtomically( _ data: Data, to name: String, in directory: Int32, beforeReplacement: () throws -> Void ) throws { let temporary = ".setups.\(UUID().uuidString).tmp" let descriptor = Darwin.openat( directory, temporary, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0o600) guard descriptor >= 0 else { throw posixError(errno, path: temporary) } do { try withDescriptor(descriptor, path: temporary) { descriptor in try requireMode(descriptor, mode: 0o600, type: S_IFREG, path: temporary) try data.withUnsafeBytes { bytes in guard let base = bytes.baseAddress else { return } var offset = 0 while offset < bytes.count { let count = Darwin.write(descriptor, base.advanced(by: offset), bytes.count - offset) if count < 0 { let code = errno if code == EINTR { continue } throw posixError(code, path: temporary) } guard count > 0 else { throw posixError(EIO, path: temporary) } offset += count } } try synchronizeFile(descriptor) } try beforeReplacement() guard Darwin.renameat(directory, temporary, directory, name) == 0 else { throw posixError(errno, path: name) } } catch { if Darwin.unlinkat(directory, temporary, 0) != 0, errno != ENOENT { throw posixError(errno, path: temporary) } throw error } } 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 synchronize(_ descriptor: Int32) throws { while Darwin.fsync(descriptor) != 0 { let code = errno if code == EINTR { continue } throw NSError(domain: NSPOSIXErrorDomain, code: Int(code)) } } 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 Recovery: Sendable { let revision: Revision let error: SetupStoreCorruptionError } private struct Observation: Sendable { var revision: Revision? var recovery: Recovery? } private final class StoreState: Sendable { let observation = Mutex(Observation()) } private struct Header: Decodable { let version: Int } private struct Storage: Codable { let version: Int let setups: [SavedSetup] } }