import Foundation import Testing @testable import ParcelConfig @Suite(.timeLimit(.minutes(1))) struct ConfigStoreTests { @Test func defaultURLUsesTheCurrentHomeDirectory() { let expected = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".config/parcel/parcel.toml") #expect(ConfigStore.defaultFileURL == expected) } @Test func initialSnapshotHasExplicitUnloadedDefaults() async { let store = ConfigStore() let snapshot = await store.snapshot #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.attemptedSource == nil) #expect(snapshot.loadState == .notLoaded) #expect(snapshot.diagnostics.isEmpty) #expect(await !store.isWatching) } @Test func sourceLoadingPreservesCommentsAndUnicode() async { let store = ConfigStore() let source = "# 改善 café\n[layout]\nratio = 0.6 # Keep this comment.\n" let snapshot = await store.load(source: source) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.activeSource == .sourceText) #expect(snapshot.attemptedSource == .sourceText) #expect(snapshot.loadState == .loaded) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.isEmpty) } @Test func rejectedAppearanceReloadKeepsColorsAndGeometryUntilRecovery() async throws { let store = ConfigStore() let source = "[appearance]\npalette = 'kiln'\nmode = 'dark'\nactive-border-color = '#A1B2C3'\nborder-radius = 12.5\n" let good = await store.load(source: source) #expect(good.loadState == .loaded) #expect(good.activeConfiguration.appearance.palette == .kiln) let rejected = await store.load(source: "[appearance]\npalette = 'tide'\nactive-border-color = '#123'\n") #expect(rejected.loadState == .rejected) #expect(rejected.activeConfiguration == good.activeConfiguration) #expect(rejected.lastGoodDocument?.render() == source) let error = try #require(rejected.diagnostics.first) #expect(error.severity == .error) #expect(error.location.line == 3) let recovered = await store.load(source: "[appearance]\npalette = 'rose'\nborder-opacity = 0.5\n") #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) #expect(recovered.activeConfiguration.appearance == AppearanceConfiguration(palette: .rose, borderOpacity: 0.5)) } @Test func initiallyInvalidSyntaxKeepsDefaultsAndParserLocation() async throws { let store = ConfigStore() let snapshot = await store.load(source: "[layout]\nratio = \n") #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.loadState == .rejected) let diagnostic = try #require(snapshot.diagnostics.first) #expect(diagnostic.severity == .error) #expect(diagnostic.location.line == 2) #expect(diagnostic.location.column > 1) } @Test func initiallyInvalidSchemaKeepsDefaultsAndValidatorDiagnostics() async throws { let store = ConfigStore() let source = "[motion]\nspeed = -1\n" let expected = ConfigValidator.validate(try TOMLDocument(parsing: source)).diagnostics let snapshot = await store.load(source: source) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.loadState == .rejected) #expect(snapshot.diagnostics == expected) #expect(snapshot.diagnostics.first?.location.line == 2) } @Test(arguments: ["[layout]\nratio =\n", "[layout]\nratio = 8\n"]) func rejectedSourceKeepsTheLastGoodConfigurationAndDocument(invalid: String) async { let store = ConfigStore() let source = "# Original formatting\n[layout]\nratio=0.6\n" let good = await store.load(source: source) let rejected = await store.load(source: invalid) #expect(rejected.activeConfiguration == good.activeConfiguration) #expect(rejected.activeSource == good.activeSource) #expect(rejected.lastGoodDocument?.render() == source) #expect(rejected.loadState == .rejected) #expect(rejected.diagnostics.contains { $0.severity == .error }) } @Test func validConfigurationWithWarningsStillBecomesLastGood() async { let store = ConfigStore() let source = "unknown-setting = true\n[layout]\nratio = 0.6\n" let snapshot = await store.load(source: source) #expect(snapshot.loadState == .loaded) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.count == 1) #expect(snapshot.diagnostics.first?.severity == .warning) } @Test func retiredAutomaticTilingBindingLoadsWarnsAndRecoversWithoutChangingTheFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[layout]\ndefault = 'side'\n[keybindings]\n pause-tiling = 'ctrl-alt-p'\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) let stream = await store.updates() var updates = stream.makeAsyncIterator() #expect(await updates.next()?.loadState == .notLoaded) let loaded = await store.reload() #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(loaded.lastGoodDocument?.render() == source) #expect(loaded.activeConfiguration.keybindings[.toggleAutomaticTiling] == nil) #expect(loaded.activeConfiguration.layout.global.defaultLayout == .side) #expect(loaded.diagnostics.count == 1) let warning = try #require(loaded.diagnostics.first) #expect(warning.severity == .warning) #expect(warning.location.line == 4) #expect(warning.location.column == 3) #expect(warning.message.contains("toggle-automatic-tiling")) #expect(await updates.next()?.diagnostics == loaded.diagnostics) #expect(try String(contentsOf: fixture.fileURL, encoding: .utf8) == source) try fixture.write( source.replacingOccurrences(of: "pause-tiling = 'ctrl-alt-p'", with: "toggle-automatic-tiling = 'cmd-f20'")) let recovered = await store.reload() #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) #expect( recovered.activeConfiguration.keybindings[.toggleAutomaticTiling] == KeyChord(modifiers: .cmd, key: .f20)) #expect(recovered.activeConfiguration.layout == loaded.activeConfiguration.layout) } @Test func goodSourceRecoversAndClearsOldDiagnostics() async { let store = ConfigStore() await store.load(source: "[motion]\nspeed = -1\n") let source = "[motion]\nenabled = false\n" let recovered = await store.load(source: source) #expect(recovered.loadState == .loaded) #expect(!recovered.activeConfiguration.motion.enabled) #expect(recovered.lastGoodDocument?.render() == source) #expect(recovered.diagnostics.isEmpty) } @Test func missingInitialFileReportsDefaultsWithoutCreatingAFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .missingFileUsingDefaults) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.attemptedSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.diagnostics.first?.severity == .warning) #expect(snapshot.diagnostics.first?.location == SourceLocation()) #expect(!FileManager.default.fileExists(atPath: fixture.fileURL.path)) } @Test func utf8FileLoadingReportsItsOrigin() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "# 配置\n[layout]\nratio = 0.6\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.activeSource == .file(fixture.fileURL)) #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) #expect(snapshot.lastGoodDocument?.render() == source) #expect(snapshot.diagnostics.isEmpty) } @Test func initialInvalidFileReportsProblemsWithoutBecomingActive() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[motion]\nspeed = -1\n") let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .rejected) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.activeSource == .defaults) #expect(snapshot.attemptedSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument == nil) #expect(snapshot.diagnostics.first?.location.line == 2) } @Test func invalidUTF8IsRejectedWithoutLossyDecoding() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[layout]\nratio = 0.6\n") let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.reload() try Data([0xFF, 0xFE, 0x61]).write(to: fixture.fileURL) let bad = await store.reload() #expect(bad.loadState == .rejected) #expect(bad.activeConfiguration == good.activeConfiguration) #expect(bad.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(bad.activeSource == good.activeSource) #expect(bad.diagnostics.first?.severity == .error) #expect(bad.diagnostics.first?.location == SourceLocation()) #expect(bad.diagnostics.first?.message.contains("UTF-8") == true) } @Test func deletingAFileWhoseValuesEqualDefaultsStillPreservesItsDocument() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "# Intentionally use the defaults.\n" try fixture.write(source) let store = ConfigStore(fileURL: fixture.fileURL) await store.reload() try FileManager.default.removeItem(at: fixture.fileURL) let missing = await store.reload() #expect(missing.activeConfiguration == .defaults) #expect(missing.activeSource == .file(fixture.fileURL)) #expect(missing.lastGoodDocument?.source == source) #expect(missing.loadState == .rejected) #expect(missing.diagnostics.first?.severity == .error) } @Test func directoryReadFailureKeepsLastGoodAndIdentifiesTheAttemptedFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.load(source: "[motion]\nenabled = false\n") let failed = await store.reload() #expect(failed.loadState == .rejected) #expect(failed.activeConfiguration == good.activeConfiguration) #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(failed.activeSource == .sourceText) #expect(failed.attemptedSource == .file(fixture.fileURL)) #expect(failed.diagnostics.first?.severity == .error) #expect(failed.diagnostics.first?.location == SourceLocation()) } @Test func unreadableFileReportsAnIOErrorAndRecovers() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[layout]\nratio = 0.6\n") let store = ConfigStore(fileURL: fixture.fileURL) let good = await store.reload() try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: fixture.fileURL.path) let failed = await store.reload() try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.fileURL.path) #expect(failed.loadState == .rejected) #expect(failed.activeConfiguration == good.activeConfiguration) #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) #expect(failed.diagnostics.first?.severity == .error) let recovered = await store.reload() #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) } @Test func nonFileURLsAreRejectedWithoutNetworkAccess() async throws { let url = try #require(URL(string: "https://example.invalid/parcel.toml")) let store = ConfigStore(fileURL: url) let snapshot = await store.reload() #expect(snapshot.loadState == .rejected) #expect(snapshot.activeConfiguration == .defaults) #expect(snapshot.diagnostics.first?.severity == .error) } @Test func symbolicLinksLoadTheirTarget() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("target.toml") let source = "[motion]\nenabled = false\n" try Data(source.utf8).write(to: target) try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) let store = ConfigStore(fileURL: fixture.fileURL) let snapshot = await store.reload() #expect(snapshot.loadState == .loaded) #expect(snapshot.activeSource == .file(fixture.fileURL)) #expect(snapshot.lastGoodDocument?.source == source) } @Test func watcherFollowsAtomicReplacement() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } let stream = await store.updates() var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.lastGoodDocument?.source == original) try fixture.write(replacement, atomic: true) let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) #expect(snapshot.loadState == .loaded) #expect(await iterator.next()?.lastGoodDocument?.source == replacement) } } @Test func watcherRearmsAfterRepeatedAtomicSaves() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("version = 1") try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } for index in 0..<3 { let source = "# Save \(index)\nversion = 1" try fixture.write(source, atomic: true) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } let edited = source + "\n# In place" try fixture.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } } } } @Test func watcherFollowsFileDeletionAndRecreation() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[motion]\nenabled = false\n" try fixture.write(source) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.removeItem(at: fixture.fileURL) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.lastGoodDocument?.source == source) try fixture.write(source) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded && $0.lastGoodDocument?.source == source } #expect(recreated.lastGoodDocument?.source == source) #expect(recreated.diagnostics.isEmpty) try fixture.writeInPlace("version = 1") _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } } } @Test func watcherFollowsEditsThroughASymlinkAndTargetReplacement() async throws { let fixture = try TemporaryConfigFile() let target = try TemporaryConfigFile() defer { fixture.remove() target.remove() } try target.write("version = 1") try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target.fileURL) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let edited = "[motion]\nenabled = false\n" try fixture.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } let replacement = "[layout]\nratio = 0.7\n" try target.write(replacement, atomic: true) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } try target.writeInPlace(edited) _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } try FileManager.default.removeItem(at: target.fileURL) _ = try await waitForSnapshot(store) { $0.loadState == .rejected } try target.write(replacement) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(recreated.lastGoodDocument?.source == replacement) #expect(recreated.activeSource == .file(fixture.fileURL)) } } @Test func watcherFollowsRelativeDanglingSymlinkAndRetargeting() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("nested/target.toml") try FileManager.default.createSymbolicLink( atPath: fixture.fileURL.path, withDestinationPath: "nested/target.toml") try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: target) _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let other = fixture.directory.appendingPathComponent("other.toml") let source = "[motion]\nenabled = false\n" try Data(source.utf8).write(to: other) try FileManager.default.removeItem(at: fixture.fileURL) try FileManager.default.createSymbolicLink(atPath: fixture.fileURL.path, withDestinationPath: "other.toml") _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } try fixture.writeInPlace("version = 1") _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } } } @Test func watcherLoadsAfterMissingAncestorDirectoriesAreCreated() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let file = fixture.directory.appendingPathComponent("one/two/parcel.toml") let store = ConfigStore(fileURL: file) try await store.startWatching() do { _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } try FileManager.default.createDirectory( at: file.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: file) _ = try await waitForSnapshot(store) { $0.loadState == .loaded } } catch { await store.stopWatching() throw error } await store.stopWatching() } @Test func watcherDetectsSameSizeInPlaceWritesWithRestoredModificationTime() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" #expect(original.utf8.count == replacement.utf8.count) try fixture.write(original) let values = try fixture.fileURL.resourceValues(forKeys: [.contentModificationDateKey]) let modified = try #require(values.contentModificationDate) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } try fixture.writeInPlace(replacement) try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: fixture.fileURL.path) let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) } } @Test func watcherRecoversFromBadSyntaxToGoodContent() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "# Last good\n[layout]\nratio = 0.6\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } try fixture.write("[layout]\nratio =\n", atomic: true) let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.lastGoodDocument?.source == original) #expect(failed.activeConfiguration.layout.global.ratio == 0.6) #expect(failed.diagnostics.first?.location.line == 2) let replacement = "# Recovered\n[layout]\nratio = 0.8\n" try fixture.write(replacement, atomic: true) let recovered = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(recovered.loadState == .loaded) #expect(recovered.diagnostics.isEmpty) } } @Test func watcherFollowsDeletionAndRecreationOfTheParentDirectory() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let source = "[layout]\nratio = 0.6\n" try fixture.write(source) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.removeItem(at: fixture.directory) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.lastGoodDocument?.source == source) #expect(missing.activeSource == .file(fixture.fileURL)) #expect(missing.diagnostics.first?.severity == .error) try FileManager.default.createDirectory(at: fixture.directory, withIntermediateDirectories: true) try fixture.write(source) let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(recreated.lastGoodDocument?.source == source) #expect(recreated.diagnostics.isEmpty) } } @Test(arguments: [false, true]) func watcherFollowsAncestorRenameAndRecreation(throughSymlink: Bool) async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let outer = fixture.directory.appendingPathComponent("outer") let target = outer.appendingPathComponent("inner/parcel.toml") try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("[layout]\nratio = 0.6\n".utf8).write(to: target) if throughSymlink { try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) } let store = ConfigStore(fileURL: throughSymlink ? fixture.fileURL : target) try await store.startWatching() do { _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try FileManager.default.moveItem(at: outer, to: fixture.directory.appendingPathComponent("moved")) let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(missing.activeConfiguration.layout.global.ratio == 0.6) try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("[layout]\nratio = 0.7\n".utf8).write(to: target) _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.7 } try Data("[layout]\nratio = 0.8\n".utf8).write(to: target, options: .atomic) _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.8 } #expect(await store.isWatching) } catch { await store.stopWatching() throw error } await store.stopWatching() } @Test(arguments: ["deleted", "regular", "retargeted"]) func symlinkDiscoveryRetriesWhenTheLinkChangesAfterInspection(replacement: String) throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("target.toml") try Data("version = 1".utf8).write(to: target) try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) let suffix = "/\(fixture.directory.lastPathComponent)/parcel.toml" var replaced = false let paths = try ConfigFileWatcher.watchPaths(for: fixture.fileURL) { path in if path.hasSuffix(suffix), !replaced { replaced = true try FileManager.default.removeItem(at: fixture.fileURL) if replacement == "regular" { try fixture.write("version = 1") } let destination = try ConfigFileWatcher.symlinkDestination(path) #expect(destination == nil) if replacement == "retargeted" { try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) } return destination } return try ConfigFileWatcher.symlinkDestination(path) } #expect(replaced) let directory = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) #expect(paths[directory]?.contains(.write) == true) if replacement == "regular" { #expect(paths["\(directory)/parcel.toml"]?.contains(.write) == true) } if replacement == "retargeted" { #expect(paths["\(directory)/target.toml"]?.contains(.write) == true) } } @Test func symlinkReadDistinguishesTransientChangesFromAccessFailures() throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) try fixture.write("version = 1") #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.appendingPathComponent("child").path) == nil) let blocked = fixture.directory.appendingPathComponent("blocked") try FileManager.default.createDirectory(at: blocked, withIntermediateDirectories: false) try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: blocked.path) defer { do { try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: blocked.path) } catch { Issue.record(error) } } #expect(throws: (any Error).self) { try ConfigFileWatcher.symlinkDestination(blocked.appendingPathComponent("link").path) } } @Test func ancestorSiblingChangesDoNotScheduleReloads() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let target = fixture.directory.appendingPathComponent("inner/parcel.toml") try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("version = 1".utf8).write(to: target) let paths = try ConfigFileWatcher.watchPaths(for: target) let ancestor = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) #expect(paths[ancestor] == [.rename, .delete, .revoke]) let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( fileURL: target, debounceInterval: .milliseconds(100), sleep: { try await recorder.sleep($0) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) for _ in 0..<3 { try fixture.write("# Unrelated sibling") try FileManager.default.removeItem(at: fixture.fileURL) } try await Task.sleep(for: .milliseconds(300)) watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.changes == 1) #expect(await recorder.sleeps == 0) #expect(await recorder.diagnostics.isEmpty) } @Test func watcherLoadsAFileCreatedAfterAnInitialMissingFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try await fixture.withWatchingStore { store in let stream = await store.updates() var updates = stream.makeAsyncIterator() let initial = try await waitForSnapshot(&updates) { $0.loadState == .missingFileUsingDefaults } #expect(initial.activeSource == .defaults) let source = "[motion]\nenabled = false\n" try fixture.write(source) let loaded = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == source } #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(!loaded.activeConfiguration.motion.enabled) #expect(loaded.diagnostics.isEmpty) } } @Test func watcherLoadsCompletedContentAfterAnInitiallyEmptyFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try await fixture.withWatchingStore { store in let stream = await store.updates() var updates = stream.makeAsyncIterator() _ = try await waitForSnapshot(&updates) { $0.loadState == .missingFileUsingDefaults } try fixture.write("") let empty = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == "" } #expect(empty.loadState == .loaded) #expect(empty.activeConfiguration.motion.enabled) let source = "[motion]\nenabled = false\n" try fixture.write(source) let loaded = try await waitForSnapshot(&updates) { $0.lastGoodDocument?.source == source } #expect(loaded.loadState == .loaded) #expect(loaded.activeSource == .file(fixture.fileURL)) #expect(!loaded.activeConfiguration.motion.enabled) #expect(loaded.diagnostics.isEmpty) } } @Test func watcherRecoversFromAFileReadFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) try await fixture.withWatchingStore { store in let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.activeSource == .defaults) try FileManager.default.removeItem(at: fixture.fileURL) try fixture.write("[layout]\nratio = 0.6\n") let loaded = try await waitForSnapshot(store) { $0.loadState == .loaded } #expect(loaded.activeConfiguration.layout.global.ratio == 0.6) } } @Test func stoppedWatcherCannotPublishAndCanRestart() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "[layout]\nratio = 0.6\n" let replacement = "[layout]\nratio = 0.7\n" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } await store.stopWatching() await store.stopWatching() #expect(await !store.isWatching) try fixture.write(replacement) #expect(await store.snapshot.lastGoodDocument?.source == original) try await store.startWatching(debounceInterval: .milliseconds(15)) try await store.startWatching(debounceInterval: .milliseconds(15)) let restarted = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(restarted.diagnostics.isEmpty) } } @Test func cancellationInterruptsAPendingDebounce() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let sleep = WatcherSleepGate() defer { sleep.finish() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching(debounceInterval: .seconds(60), sleep: { try await sleep.sleep($0) }) do { _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } await store.load(source: "[motion]\nenabled = false\n") let pending = try #require(await starts.next()) #expect(pending.duration == .seconds(60)) await store.stopWatching() #expect(await completions.next() == true) #expect(await !store.isWatching) #expect(await store.snapshot.activeSource == .sourceText) } catch { await store.stopWatching() throw error } } @Test(arguments: [Duration.zero, .milliseconds(-1)]) func nonpositiveDebounceIntervalsAreRejected(interval: Duration) async throws { let store = ConfigStore() do { try await store.startWatching(debounceInterval: interval) Issue.record("An invalid debounce interval was accepted.") await store.stopWatching() } catch let diagnostic as ConfigDiagnostic { #expect(diagnostic.severity == .error) } #expect(await !store.isWatching) } @Test func updatesIncludeCurrentStateAndRejectedLoads() async throws { let store = ConfigStore() let stream = await store.updates() var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.loadState == .notLoaded) let source = "[layout]\nratio = 0.6\n" await store.load(source: source) #expect(await iterator.next()?.lastGoodDocument?.source == source) await store.load(source: "[layout]\nratio =\n") let rejected = try #require(await iterator.next()) #expect(rejected.loadState == .rejected) #expect(rejected.lastGoodDocument?.source == source) #expect(!rejected.diagnostics.isEmpty) } @Test func slowUpdateConsumersReceiveOnlyTheNewestSnapshot() async throws { let store = ConfigStore() let stream = await store.updates() await store.load(source: "[layout]\nratio = 0.6\n") await store.load(source: "[layout]\nratio = 0.7\n") var iterator = stream.makeAsyncIterator() let newest = try #require(await iterator.next()) #expect(newest.activeConfiguration.layout.global.ratio == 0.7) } @Test func cancelingOneUpdateConsumerDoesNotAffectOthers() async { let store = ConfigStore() let canceledStream = await store.updates() let survivingStream = await store.updates() let consumer = Task { for await _ in canceledStream {} } consumer.cancel() await consumer.value await store.load(source: "[motion]\nenabled = false\n") var iterator = survivingStream.makeAsyncIterator() #expect(await iterator.next()?.activeConfiguration.motion.enabled == false) } @Test func idleWatcherDoesNotRetainTheStore() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } var store: ConfigStore? = ConfigStore(fileURL: fixture.fileURL) weak let weakStore = store let updates = try #require(await store?.updates()) if let store { try await store.startWatching(debounceInterval: .seconds(60)) _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } } store = nil try await waitForObservation { for await _ in updates {} try Task.checkCancellation() } #expect(weakStore == nil) } @Test func releasingStoreFinishesItsUpdateStreams() async throws { var store: ConfigStore? = ConfigStore() weak let weakStore = store let stream = try #require(await store?.updates()) var iterator = stream.makeAsyncIterator() #expect(await iterator.next()?.loadState == .notLoaded) store = nil #expect(weakStore == nil) #expect(await iterator.next() == nil) } @Test func watcherSurfacesUnexpectedDebounceFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .seconds(1), sleep: { _ in throw StoreTestError.injected }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) watcher.requestReload() await watcher.waitUntilFinished() let diagnostics = await recorder.diagnostics #expect(diagnostics.count == 1) #expect(diagnostics.first?.severity == .error) #expect(diagnostics.first?.message.isEmpty == false) } @Test func watcherHasNoIdleReadsOrSleepsAndCoalescesBurstWrites() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("version = 1") let recorder = WatcherRecorder() let sleep = WatcherSleepGate() defer { sleep.finish() } let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .milliseconds(100), sleep: { duration in await recorder.recordSleep() try await sleep.sleep(duration) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) sleep.finish() } ) defer { watcher.cancel() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() try await recorder.waitForChanges(1) #expect(await recorder.changes == 1) #expect(await recorder.sleeps == 0) // Explicit events and sleep gates keep scheduling delays from splitting a burst. for burst in 1...2 { watcher.requestReload() let pending = try #require(await starts.next()) #expect(pending.duration == .milliseconds(100)) for _ in 0..<20 { watcher.requestReload() } #expect(await recorder.changes == burst) pending.resume() #expect(await completions.next() == false) try await recorder.waitForChanges(burst + 1) #expect(await recorder.changes == burst + 1) #expect(await recorder.sleeps == burst) } watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.changes == 3) #expect(await recorder.sleeps == 2) #expect(await recorder.diagnostics.isEmpty) } @Test func siblingFileChurnCannotStarveConfigurationReload() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try fixture.write("[motion]\nenabled = true\n", atomic: true) let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching(debounceInterval: .milliseconds(200)) do { _ = try await waitForSnapshot(store) { $0.loadState == .loaded } try await withThrowingTaskGroup(of: Void.self) { group in defer { group.cancelAll() } let (started, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) defer { continuation.finish() } let sibling = fixture.directory.appendingPathComponent("query.stdout") group.addTask { while true { try Task.checkCancellation() try Data("query result".utf8).write(to: sibling, options: .atomic) continuation.yield(()) try await Task.sleep(for: .milliseconds(10)) } } var starts = started.makeAsyncIterator() _ = try #require(await starts.next()) try fixture.write("[motion]\nenabled = false\n", atomic: true) let loaded = try await waitForSnapshot(store) { !$0.activeConfiguration.motion.enabled } #expect(loaded.loadState == .loaded && loaded.diagnostics.isEmpty) } } catch { await store.stopWatching() throw error } await store.stopWatching() } @Test func eventDuringReloadSchedulesAnotherBoundedWindow() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let sleep = WatcherSleepGate() let reload = WatcherSleepGate() defer { sleep.finish(); reload.finish() } let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .milliseconds(100), sleep: { try await sleep.sleep($0) }, changed: { let result = await recorder.changed() if await recorder.changes == 2 { do { try await reload.sleep(.zero) } catch is CancellationError { return false } catch { Issue.record(error) return false } } return result }, failed: { await recorder.append($0) }) defer { watcher.cancel() } var sleeps = sleep.starts.makeAsyncIterator() var reloads = reload.starts.makeAsyncIterator() try await recorder.waitForChanges(1) watcher.requestReload() let first = try #require(await sleeps.next()) first.resume() let inFlight = try #require(await reloads.next()) watcher.requestReload() inFlight.resume() let followUp = try #require(await sleeps.next()) #expect(followUp.duration == .milliseconds(100)) followUp.resume() try await recorder.waitForChanges(3) watcher.cancel() await watcher.waitUntilFinished() #expect(await recorder.diagnostics.isEmpty) } @Test func watcherCancellationIsNotReportedAsAFailure() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let recorder = WatcherRecorder() let sleep = WatcherSleepGate() defer { sleep.finish() } var starts = sleep.starts.makeAsyncIterator() var completions = sleep.completions.makeAsyncIterator() let watcher = ConfigFileWatcher( fileURL: fixture.fileURL, debounceInterval: .seconds(60), sleep: { try await sleep.sleep($0) }, changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) defer { watcher.cancel() } try await recorder.waitForChanges(1) watcher.requestReload() let pending = try #require(await starts.next()) #expect(pending.duration == .seconds(60)) watcher.cancel() await watcher.waitUntilFinished() #expect(await completions.next() == true) #expect(await recorder.changes == 1) #expect(await recorder.diagnostics.isEmpty) } @Test func watchedFileResumesAfterSourceTextLoading() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let original = "version = 1" try fixture.write(original) try await fixture.withWatchingStore { store in _ = try await waitForSnapshot(store) { $0.loadState == .loaded } let loaded = await store.load(source: "[motion]\nenabled = false\n") #expect(loaded.activeSource == .sourceText) let resumed = try await waitForSnapshot(store) { $0.activeSource == .file(fixture.fileURL) } #expect(resumed.lastGoodDocument?.source == original) } } @Test func watcherReportsSetupFailureAndCanRestart() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: fixture.fileURL) let store = ConfigStore(fileURL: fixture.fileURL) try await store.startWatching() let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(!failed.diagnostics.isEmpty) #expect(await !store.isWatching) try FileManager.default.removeItem(at: fixture.fileURL) try fixture.write("version = 1") try await store.startWatching() _ = try await waitForSnapshot(store) { $0.loadState == .loaded } await store.stopWatching() } @Test func watcherRejectsNonFileURLs() async throws { let url = try #require(URL(string: "https://example.invalid/parcel.toml")) let store = ConfigStore(fileURL: url) try await store.startWatching() let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } #expect(failed.activeConfiguration == .defaults) #expect(await !store.isWatching) } } private enum StoreTestError: Error { case timedOut case observationEnded case injected } private struct WatcherSleepGate: Sendable { struct Pending: Sendable { let duration: Duration let release: AsyncStream.Continuation func resume() { release.finish() } } private let started = AsyncStream.makeStream() private let completed = AsyncStream.makeStream() var starts: AsyncStream { started.stream } var completions: AsyncStream { completed.stream } func sleep(_ duration: Duration) async throws { let (release, continuation) = AsyncStream.makeStream() defer { continuation.finish() } started.continuation.yield(Pending(duration: duration, release: continuation)) for await _ in release {} completed.continuation.yield(Task.isCancelled) try Task.checkCancellation() } func finish() { started.continuation.finish() completed.continuation.finish() } } private actor WatcherRecorder { private(set) var diagnostics: [ConfigDiagnostic] = [] private(set) var changes = 0 private(set) var sleeps = 0 private let changeEvents = AsyncStream.makeStream() deinit { changeEvents.continuation.finish() } func changed() -> Bool { changes += 1 changeEvents.continuation.yield(changes) return true } func recordSleep() { sleeps += 1 } func sleep(_ duration: Duration) async throws { recordSleep() try await Task.sleep(for: duration) } func append(_ diagnostic: ConfigDiagnostic) { diagnostics.append(diagnostic) changeEvents.continuation.finish() } func waitForChanges(_ count: Int) async throws { if changes >= count { return } try await waitForObservation { [changeEvents] in for await current in changeEvents.stream { if current >= count { return } } throw StoreTestError.observationEnded } } } private struct TemporaryConfigFile: Sendable { let directory: URL var fileURL: URL { directory.appendingPathComponent("parcel.toml") } init() throws { directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) } func write(_ text: String, atomic: Bool = false) throws { try Data(text.utf8).write(to: fileURL, options: atomic ? .atomic : []) } func writeInPlace(_ text: String) throws { let handle = try FileHandle(forWritingTo: fileURL) defer { do { try handle.close() } catch { Issue.record(error) } } try handle.write(contentsOf: Data(text.utf8)) try handle.truncate(atOffset: UInt64(text.utf8.count)) } func withWatchingStore(_ body: @Sendable (ConfigStore) async throws -> Void) async throws { let store = ConfigStore(fileURL: fileURL) try await store.startWatching(debounceInterval: .milliseconds(15)) do { try await body(store) } catch { await store.stopWatching() throw error } await store.stopWatching() } func remove() { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } } private func waitForSnapshot( _ updates: inout AsyncStream.Iterator, matching predicate: (ConfigSnapshot) -> Bool ) async throws -> ConfigSnapshot { while let snapshot = await updates.next() { if predicate(snapshot) { return snapshot } } throw StoreTestError.observationEnded } private func waitForSnapshot( _ store: ConfigStore, matching predicate: @escaping @Sendable (ConfigSnapshot) -> Bool ) async throws -> ConfigSnapshot { let updates = await store.updates() return try await waitForObservation { for await snapshot in updates { if predicate(snapshot) { return snapshot } } throw StoreTestError.observationEnded } } private func waitForObservation( _ observe: @escaping @Sendable () async throws -> Value ) async throws -> Value { try await withThrowingTaskGroup(of: Value.self) { group in defer { group.cancelAll() } group.addTask { try await observe() } group.addTask { try await Task.sleep(for: .seconds(3)) throw StoreTestError.timedOut } return try #require(await group.next()) } }