public import Foundation import os public enum ConfigSource: Equatable, Sendable { case defaults case file(URL) case sourceText } public enum ConfigLoadState: Equatable, Sendable { case notLoaded case loaded case missingFileUsingDefaults case rejected } public struct ConfigSnapshot: Sendable { public let activeConfiguration: ParcelConfiguration public let lastGoodDocument: TOMLDocument? public let activeSource: ConfigSource public let attemptedSource: ConfigSource? public let loadState: ConfigLoadState public let diagnostics: [ConfigDiagnostic] } public actor ConfigStore { private static let signposter = OSSignposter(subsystem: "com.parcel", category: "Config") public static var defaultFileURL: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".config/parcel/parcel.toml", isDirectory: false) } public nonisolated let fileURL: URL public private(set) var snapshot = ConfigSnapshot( activeConfiguration: .defaults, lastGoodDocument: nil, activeSource: .defaults, attemptedSource: nil, loadState: .notLoaded, diagnostics: [] ) public var isWatching: Bool { watcher != nil } private var watcher: ConfigFileWatcher? private var watchID: UUID? private var previousContents: ConfigFileContents? private var subscribers: [UUID: AsyncStream.Continuation] = [:] public init(fileURL: URL = ConfigStore.defaultFileURL) { self.fileURL = fileURL } deinit { watcher?.cancel() for subscriber in subscribers.values { subscriber.finish() } } /// Includes the current snapshot. Slow consumers receive the newest state, not an unbounded history. public func updates() -> AsyncStream { let id = UUID() let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) continuation.onTermination = { [weak self] _ in Task { await self?.removeSubscriber(id) } } subscribers[id] = continuation continuation.yield(snapshot) return stream } @discardableResult public func reload() -> ConfigSnapshot { let signposter = Self.signposter let interval = signposter.isEnabled ? signposter.beginInterval("Reload", id: signposter.makeSignpostID()) : nil defer { if let interval { let outcome: Int = switch snapshot.loadState { case .notLoaded: 0 case .loaded: 1 case .missingFileUsingDefaults: 2 case .rejected: 3 } signposter.endInterval("Reload", interval, "outcome=\(outcome, privacy: .public)") } } let contents = ConfigFileContents.read(from: fileURL) previousContents = contents apply(contents) return snapshot } /// A running watcher resumes loading its file after the debounce interval. @discardableResult public func load(source: String) -> ConfigSnapshot { previousContents = nil apply(source: source, from: .sourceText) watcher?.requestReload() return snapshot } /// Watches file-system events with a short debounce and no timers while idle. public func startWatching(debounceInterval: Duration = .milliseconds(100)) throws { try startWatching(debounceInterval: debounceInterval, sleep: { try await Task.sleep(for: $0) }) } func startWatching( debounceInterval: Duration, sleep: @escaping @Sendable (Duration) async throws -> Void ) throws { guard debounceInterval > .zero else { throw ConfigDiagnostic( message: String( localized: "The configuration debounce interval must be greater than zero.", table: "Store", bundle: .module ) ) } guard watcher == nil else { return } let id = UUID() watchID = id previousContents = nil watcher = ConfigFileWatcher( fileURL: fileURL, debounceInterval: debounceInterval, sleep: sleep, changed: { [weak self] in await self?.fileChanged(watchID: id) ?? false }, failed: { [weak self] diagnostic in await self?.watchFailed(diagnostic, watchID: id) } ) } /// Waits for the canceled watcher to finish; it cannot publish after this call returns. public func stopWatching() async { watchID = nil let previous = watcher watcher = nil previous?.cancel() await previous?.waitUntilFinished() } private func fileChanged(watchID id: UUID) -> Bool { guard watchID == id, !Task.isCancelled else { return false } let contents = ConfigFileContents.read(from: fileURL) guard !Task.isCancelled else { return false } if contents != previousContents { previousContents = contents apply(contents) } return true } private func watchFailed(_ diagnostic: ConfigDiagnostic, watchID id: UUID) { guard watchID == id else { return } watcher = nil watchID = nil reject([diagnostic], from: .file(fileURL)) } private func apply(_ contents: ConfigFileContents) { let source = ConfigSource.file(fileURL) switch contents { case .bytes(let bytes): guard let text = String(data: bytes, encoding: .utf8) else { reject( [ ConfigDiagnostic( message: String( localized: "The configuration file at \(fileURL.path) is not valid UTF-8. Save it as UTF-8 and try again.", table: "Store", bundle: .module ) ) ], from: source ) return } apply(source: text, from: source) case .missing: if snapshot.activeSource == .defaults { publish( ConfigSnapshot( activeConfiguration: snapshot.activeConfiguration, lastGoodDocument: snapshot.lastGoodDocument, activeSource: snapshot.activeSource, attemptedSource: source, loadState: .missingFileUsingDefaults, diagnostics: [ ConfigDiagnostic( severity: .warning, message: String( localized: "No configuration file exists at \(fileURL.path). Using built-in defaults until a valid file is available.", table: "Store", bundle: .module ) ) ] ) ) } else { reject( [ ConfigDiagnostic( message: String( localized: "The configuration file at \(fileURL.path) is missing. Keeping the last good configuration.", table: "Store", bundle: .module ) ) ], from: source ) } case .failure(let diagnostic): reject([diagnostic], from: source) } } private func apply(source: String, from origin: ConfigSource) { do { let document = try TOMLDocument(parsing: source) let result = ConfigValidator.validate(document) guard let configuration = result.configuration, !result.diagnostics.contains(where: { $0.severity == .error }) else { var diagnostics = result.diagnostics if !diagnostics.contains(where: { $0.severity == .error }) { diagnostics.append( ConfigDiagnostic( message: String( localized: "Configuration validation did not produce a usable configuration.", table: "Store", bundle: .module ) ) ) } reject(diagnostics, from: origin) return } publish( ConfigSnapshot( activeConfiguration: configuration, lastGoodDocument: document, activeSource: origin, attemptedSource: origin, loadState: .loaded, diagnostics: result.diagnostics ) ) } catch let diagnostic as ConfigDiagnostic { reject([diagnostic], from: origin) } catch { reject( [ ConfigDiagnostic( message: String( localized: "Could not parse the configuration: \(error.localizedDescription)", table: "Store", bundle: .module ) ) ], from: origin ) } } private func reject(_ diagnostics: [ConfigDiagnostic], from source: ConfigSource) { publish( ConfigSnapshot( activeConfiguration: snapshot.activeConfiguration, lastGoodDocument: snapshot.lastGoodDocument, activeSource: snapshot.activeSource, attemptedSource: source, loadState: .rejected, diagnostics: diagnostics ) ) } private func publish(_ value: ConfigSnapshot) { snapshot = value for subscriber in subscribers.values { subscriber.yield(value) } } private func removeSubscriber(_ id: UUID) { subscribers.removeValue(forKey: id) } }