diff --git a/AppDataStorage.Test/DollarPropertyTests.cs b/AppDataStorage.Test/DollarPropertyTests.cs new file mode 100644 index 0000000..2b8bf01 --- /dev/null +++ b/AppDataStorage.Test/DollarPropertyTests.cs @@ -0,0 +1,133 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.AppDataStorage.Test; + +using System.IO.Abstractions.TestingHelpers; +using System.Text.Json; + +using ktsu.Semantics.Paths; + +/// +/// Property names that start with '$' are reference metadata to System.Text.Json under +/// ReferenceHandler.Preserve, so it writes them but refuses to read them. A save must not write a file +/// the next load would archive as corrupt, and a hand-added "$schema" must not reset every setting +/// (ktsu-dev/AppDataStorage#376). +/// +[TestClass] +public sealed class DollarPropertyTests +{ + [ClassInitialize] + public static void ClassSetup(TestContext testContext) => AppData.ConfigureForTesting(() => new MockFileSystem()); + + [TestInitialize] + public void SetupTest() => AppData.ClearCachedFileSystem(); + + private static AbsoluteDirectoryPath Root(string name) => + AbsoluteDirectoryPath.Create(OperatingSystem.IsWindows() ? "C:/" : "/") / RelativeDirectoryPath.Create(name); + + private static string[] Archived(AbsoluteFilePath filePath) => + AppData.FileSystem.Directory.GetFiles(filePath.AbsoluteDirectoryPath.ToString(), $"{Path.GetFileName(filePath.ToString())}.corrupt.*"); + + public sealed class VariableSettings : AppData + { + public string Theme { get; set; } = "Light"; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "A get-only collection does not load back (ktsu-dev/AppDataStorage#341), so a settings dictionary needs a setter.")] + public Dictionary Variables { get; set; } = []; + } + + [TestMethod] + [DataRow("$HOME", "home")] + [DataRow("$schema", "schema")] + [DataRow("$id", "id")] + public void SaveRefusesADollarKeyAndKeepsTheLastGoodFile(string key, string directory) + { + AbsoluteDirectoryPath root = Root($"dollar_key_{directory}"); + AbsoluteFilePath filePath; + using (VariableSettings settings = VariableSettings.LoadOrCreateIn(root)) + { + filePath = settings.FilePath; + settings.Theme = "Dark"; + settings.Save(); + + settings.Variables[key] = "/home/me"; + Assert.ThrowsExactly(settings.Save, "A save the next load could not read must throw."); + } + + using VariableSettings reloaded = VariableSettings.LoadOrCreateIn(root); + Assert.AreEqual("Dark", reloaded.Theme, "The last good save must still load."); + Assert.IsEmpty(reloaded.Variables, "The refused save must not have reached the file."); + Assert.IsEmpty(Archived(filePath), "Nothing should have been archived as corrupt."); + } + + [TestMethod] + public void OrdinaryDictionaryKeysStillRoundTrip() + { + AbsoluteDirectoryPath root = Root("ordinary_keys"); + using (VariableSettings settings = VariableSettings.LoadOrCreateIn(root)) + { + settings.Variables["HOME"] = "/home/me"; + settings.Variables["a$b"] = "x"; + settings.Save(); + } + + using VariableSettings reloaded = VariableSettings.LoadOrCreateIn(root); + Assert.AreEqual("/home/me", reloaded.Variables["HOME"]); + Assert.AreEqual("x", reloaded.Variables["a$b"], "Only a leading '$' is metadata."); + } + + [TestMethod] + public void HandAddedSchemaPropertyLoads() + { + AbsoluteDirectoryPath root = Root("hand_added_schema"); + AbsoluteFilePath filePath; + using (VariableSettings settings = VariableSettings.LoadOrCreateIn(root)) + { + filePath = settings.FilePath; + } + + AppData.FileSystem.File.WriteAllText(filePath, """{"$schema":"./settings.schema.json","Theme":"Dark","Variables":{"HOME":"/home/me"}}"""); + + using VariableSettings reloaded = VariableSettings.LoadOrCreateIn(root); + Assert.AreEqual("Dark", reloaded.Theme, "A hand-added $schema must not reset the settings."); + Assert.AreEqual("/home/me", reloaded.Variables["HOME"]); + Assert.IsEmpty(Archived(filePath), "A hand-added $schema must not get the file archived as corrupt."); + } + + [TestMethod] + public void SchemaPropertyBeforePreservedReferenceMetadataLoads() + { + AbsoluteDirectoryPath root = Root("schema_before_id"); + AbsoluteFilePath filePath; + using (VariableSettings settings = VariableSettings.LoadOrCreateIn(root)) + { + filePath = settings.FilePath; + settings.Theme = "Dark"; + settings.Save(); + } + + string saved = AppData.FileSystem.File.ReadAllText(filePath); + Assert.StartsWith("{", saved.TrimStart()); + AppData.FileSystem.File.WriteAllText(filePath, "{\"$schema\":\"./s.json\"," + saved.TrimStart()[1..]); + + using VariableSettings reloaded = VariableSettings.LoadOrCreateIn(root); + Assert.AreEqual("Dark", reloaded.Theme, "A $schema ahead of the file's own $id must still load."); + Assert.IsEmpty(Archived(filePath)); + } + + [TestMethod] + public void NestedSchemaKeyIsStillUnreadable() + { + AbsoluteDirectoryPath root = Root("nested_schema"); + AbsoluteFilePath filePath; + using (VariableSettings settings = VariableSettings.LoadOrCreateIn(root)) + { + filePath = settings.FilePath; + } + + AppData.FileSystem.File.WriteAllText(filePath, """{"Theme":"Dark","Variables":{"$schema":"x"}}"""); + + using VariableSettings reloaded = VariableSettings.LoadOrCreateIn(root); + Assert.AreEqual("Light", reloaded.Theme, "Only the top-level $schema is an editor hint; a nested one is still unreadable."); + Assert.HasCount(1, Archived(filePath)); + } +} diff --git a/AppDataStorage/AppData.cs b/AppDataStorage/AppData.cs index cdb249c..9497ad3 100644 --- a/AppDataStorage/AppData.cs +++ b/AppDataStorage/AppData.cs @@ -10,6 +10,7 @@ namespace ktsu.AppDataStorage; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; @@ -93,6 +94,68 @@ internal static void UseNonPublicSettersOfAppDataProperties(JsonTypeInfo typeInf } } + /// + /// Throws before a save writes a document that the load path could not read back. + /// + /// + /// writes a dictionary key that starts with $, such as + /// "$HOME", but rejects it when reading. Because the load path archives a file it cannot read and + /// falls back to defaults, such a save would succeed and the next launch would silently reset every + /// setting (ktsu-dev/AppDataStorage#376). Reading the document back here turns that data loss into an + /// error at save time, while the file on disk is still the last good copy. + /// + /// The type of the app data. + /// The document about to be written. + /// Thrown when the document cannot be deserialized as . + internal static void EnsureReadsBack(string jsonString) where T : AppData, new() + { + try + { + JsonSerializer.Deserialize(jsonString, JsonSerializerOptions)?.Dispose(); + } + catch (Exception ex) when (ex is JsonException or ArgumentException or FormatException or NotSupportedException) + { + throw new JsonException( + $"{typeof(T).Name} was not saved, because the saved file could not be loaded again: {ex.Message} " + + "A dictionary key that starts with '$' is the usual cause.", + ex); + } + } + + /// + /// Removes a top-level "$schema" property, which a user adds by hand for editor validation. + /// + /// + /// Under System.Text.Json rejects any unknown property that + /// starts with $, though it ignores other unknown properties. Without this, adding + /// "$schema" would get the whole file archived as corrupt and every setting reset to its + /// default (ktsu-dev/AppDataStorage#376). A document that cannot be parsed is returned unchanged, so it + /// fails in the deserializer as before. + /// + /// The document read from disk. + /// The document without its top-level "$schema" property. + internal static string WithoutSchemaProperty(string jsonString) + { + if (!jsonString.Contains("\"$schema\"")) + { + return jsonString; + } + + try + { + if (JsonNode.Parse(jsonString) is JsonObject root && root.Remove("$schema")) + { + return root.ToJsonString(); + } + } + catch (Exception ex) when (ex is JsonException or ArgumentException or InvalidOperationException) + { + // Not a readable object: leave it to the deserializer, which archives it as corrupt. + } + + return jsonString; + } + /// /// The type that first used each settings file, per file system, so two types never share one file. /// @@ -714,12 +777,17 @@ internal bool IsDoubounceTimeElapsed() /// /// Saves the app data to the file system. If the file already exists, it is backed up first in case the save fails the original file is not lost. /// + /// + /// Thrown, before anything is written, when the saved file could not be loaded again, such as for a + /// dictionary key that starts with $. The file on disk keeps its last good contents. + /// public void Save() { lock (Lock) { AppData.ClaimFile(FilePath); string jsonString = JsonSerializer.Serialize(this, typeof(T), AppData.JsonSerializerOptions); + AppData.EnsureReadsBack(jsonString); AppData.WriteText((T)this, jsonString); LastSaveTime = DateTime.UtcNow; HasQueuedSave = false; @@ -844,7 +912,7 @@ private static T LoadOrCreate(AbsoluteDirectoryPath? root, RelativeDirectoryPath try { - newAppData = JsonSerializer.Deserialize(jsonString, AppData.JsonSerializerOptions) + newAppData = JsonSerializer.Deserialize(AppData.WithoutSchemaProperty(jsonString), AppData.JsonSerializerOptions) ?? throw new JsonException("Deserialized settings file to null."); newAppData.Root = root; newAppData.Subdirectory = subdirectory; diff --git a/CLAUDE.md b/CLAUDE.md index b19daab..e78eba6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,6 +73,7 @@ copy.Save(); - Lazy singleton access via `Get()` backed by `Lazy` - `LoadOrCreate()` reads the file into a new instance on every call and never returns the `Get()` singleton, so the two do not see each other's edits. The static `QueueSave()` / `SaveIfRequired()` act on `Get()` only - `LoadOrCreate()` overloads support custom subdirectories and file names; `LoadOrCreateIn()` takes an absolute root directory +- `Save()` reads the serialized document back before writing it and throws `JsonException` if it cannot, since `ReferenceHandler.Preserve` writes `$`-prefixed dictionary keys it then refuses to read. A hand-added top-level `"$schema"` is dropped before deserializing, so it loads rather than being archived as corrupt (ktsu-dev/AppDataStorage#376) - Corrupt file recovery: an unreadable, empty or missing main file falls back to `.tmp`, then `.bk`, then creates a fresh instance. An empty main file is archived as `.empty.`, not overwritten - Process exit handler ensures queued saves are flushed via `IDisposable`