Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions AppDataStorage.Test/DollarPropertyTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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).
/// </summary>
[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<VariableSettings>
{
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<string, string> 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<JsonException>(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));
}
}
70 changes: 69 additions & 1 deletion AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
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;

Expand Down Expand Up @@ -93,6 +94,68 @@
}
}

/// <summary>
/// Throws before a save writes a document that the load path could not read back.
/// </summary>
/// <remarks>
/// <see cref="ReferenceHandler.Preserve"/> writes a dictionary key that starts with <c>$</c>, such as
/// <c>"$HOME"</c>, 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.
/// </remarks>
/// <typeparam name="T">The type of the app data.</typeparam>
/// <param name="jsonString">The document about to be written.</param>
/// <exception cref="JsonException">Thrown when the document cannot be deserialized as <typeparamref name="T"/>.</exception>
internal static void EnsureReadsBack<T>(string jsonString) where T : AppData<T>, new()
{
try
{
JsonSerializer.Deserialize<T>(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);
}
}

/// <summary>
/// Removes a top-level <c>"$schema"</c> property, which a user adds by hand for editor validation.
/// </summary>
/// <remarks>
/// Under <see cref="ReferenceHandler.Preserve"/> System.Text.Json rejects any unknown property that
/// starts with <c>$</c>, though it ignores other unknown properties. Without this, adding
/// <c>"$schema"</c> 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.
/// </remarks>
/// <param name="jsonString">The document read from disk.</param>
/// <returns>The document without its top-level <c>"$schema"</c> property.</returns>
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;
}

/// <summary>
/// The type that first used each settings file, per file system, so two types never share one file.
/// </summary>
Expand Down Expand Up @@ -688,10 +751,10 @@
/// </summary>
#if NET9_0_OR_GREATER
[JsonIgnore]
public static Lock Lock { get; } = new();

Check warning on line 754 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 754 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 754 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 754 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#else
[JsonIgnore]
public static object Lock { get; } = new();

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 757 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#endif

internal bool IsSaveQueued()
Expand All @@ -714,12 +777,17 @@
/// <summary>
/// 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.
/// </summary>
/// <exception cref="JsonException">
/// Thrown, before anything is written, when the saved file could not be loaded again, such as for a
/// dictionary key that starts with <c>$</c>. The file on disk keeps its last good contents.
/// </exception>
public void Save()
{
lock (Lock)
{
AppData.ClaimFile<T>(FilePath);
string jsonString = JsonSerializer.Serialize(this, typeof(T), AppData.JsonSerializerOptions);
AppData.EnsureReadsBack<T>(jsonString);
AppData.WriteText((T)this, jsonString);
LastSaveTime = DateTime.UtcNow;
HasQueuedSave = false;
Expand Down Expand Up @@ -844,7 +912,7 @@

try
{
newAppData = JsonSerializer.Deserialize<T>(jsonString, AppData.JsonSerializerOptions)
newAppData = JsonSerializer.Deserialize<T>(AppData.WithoutSchemaProperty(jsonString), AppData.JsonSerializerOptions)
?? throw new JsonException("Deserialized settings file to null.");
newAppData.Root = root;
newAppData.Subdirectory = subdirectory;
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ copy.Save();
- Lazy singleton access via `Get()` backed by `Lazy<T>`
- `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.<timestamp>`, not overwritten
- Process exit handler ensures queued saves are flushed via `IDisposable`

Expand Down
Loading