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
139 changes: 139 additions & 0 deletions AppDataStorage.Test/FileCollisionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.AppDataStorage.Test
{
using System.IO.Abstractions.TestingHelpers;

using ktsu.Semantics.Paths;

/// <summary>
/// The default file name is the simple type name, so two types with the same name, or two closed
/// generics of one class, resolve to one file. Each would load the other's file and save over it, so
/// the second type to use the file must be refused (ktsu-dev/AppDataStorage#336).
/// </summary>
[TestClass]
public sealed class FileCollisionTests
{
[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);

[TestMethod]
public void SameNamedTypesInDifferentNamespacesAreRefused()
{
AbsoluteDirectoryPath root = Root("same_named_types");
using (CollisionPluginA.Settings a = CollisionPluginA.Settings.LoadOrCreateIn(root))
{
a.ApiKey = "secret-A";
a.Save();
}

InvalidOperationException ex = Assert.ThrowsExactly<InvalidOperationException>(() => CollisionPluginB.Settings.LoadOrCreateIn(root));
Assert.Contains("CollisionPluginA.Settings", ex.Message, "The message should name the type already using the file.");
Assert.Contains("CollisionPluginB.Settings", ex.Message, "The message should name the type that was refused.");

using CollisionPluginA.Settings reloaded = CollisionPluginA.Settings.LoadOrCreateIn(root);
Assert.AreEqual("secret-A", reloaded.ApiKey, "The first type's data must be untouched.");
}

[TestMethod]
public void ClosedGenericsOfOneClassAreRefused()
{
AbsoluteDirectoryPath root = Root("closed_generics");
using (CollisionGeneric<int> ints = CollisionGeneric<int>.LoadOrCreateIn(root))
{
ints.Save();
}

InvalidOperationException ex = Assert.ThrowsExactly<InvalidOperationException>(() => CollisionGeneric<string>.LoadOrCreateIn(root));
Assert.Contains("CollisionGeneric<System.Int32>", ex.Message);
Assert.Contains("CollisionGeneric<System.String>", ex.Message);
}

[TestMethod]
public void SaveIsRefusedForASecondTypeToo()
{
AbsoluteDirectoryPath root = Root("refused_save");
using CollisionPluginA.Settings a = CollisionPluginA.Settings.LoadOrCreateIn(root);
using CollisionPluginB.Settings b = new() { Root = root };

Assert.ThrowsExactly<InvalidOperationException>(b.Save, "A save must not reach a file another type uses.");
}

[TestMethod]
public void TheSameTypeCanLoadAndSaveRepeatedly()
{
AbsoluteDirectoryPath root = Root("same_type_twice");
using (CollisionPluginA.Settings first = CollisionPluginA.Settings.LoadOrCreateIn(root))
{
first.ApiKey = "one";
first.Save();
}

using CollisionPluginA.Settings second = CollisionPluginA.Settings.LoadOrCreateIn(root);
second.ApiKey = "two";
second.Save();
Assert.AreEqual("two", CollisionPluginA.Settings.LoadOrCreateIn(root).ApiKey);
}

[TestMethod]
public void SameNamedTypesWithTheirOwnFileNamesCoexist()
{
AbsoluteDirectoryPath root = Root("own_file_names");
using CollisionPluginA.Settings a = CollisionPluginA.Settings.LoadOrCreateIn(root);
using CollisionPluginB.Settings b = CollisionPluginB.Settings.LoadOrCreateIn(root, FileName.Create("plugin_b.json"));
a.ApiKey = "secret-A";
a.Save();
b.Volume = 7;
b.Save();

Assert.AreEqual("secret-A", CollisionPluginA.Settings.LoadOrCreateIn(root).ApiKey);
Assert.AreEqual(7, CollisionPluginB.Settings.LoadOrCreateIn(root, FileName.Create("plugin_b.json")).Volume);
}

[TestMethod]
public void TheSamePathOnAnotherFileSystemIsAnotherFile()
{
AbsoluteDirectoryPath root = Root("other_file_system");
using (CollisionPluginA.Settings a = CollisionPluginA.Settings.LoadOrCreateIn(root))
{
a.Save();
}

AppData.UseFileSystemOnThisThread(new MockFileSystem());
using (CollisionPluginB.Settings b = CollisionPluginB.Settings.LoadOrCreateIn(root))
{
b.Volume = 7;
b.Save();
}

Assert.AreEqual(7, CollisionPluginB.Settings.LoadOrCreateIn(root).Volume, "On its own file system, the second type owns the path.");
}
}

public sealed class CollisionGeneric<TValue> : AppData<CollisionGeneric<TValue>>
{
public TValue? Value { get; set; }
}
}

namespace ktsu.AppDataStorage.Test.CollisionPluginA
{
public sealed class Settings : AppData<Settings>
{
public string ApiKey { get; set; } = string.Empty;
}
}

namespace ktsu.AppDataStorage.Test.CollisionPluginB
{
public sealed class Settings : AppData<Settings>
{
public int Volume { get; set; } = 50;
}
}
69 changes: 69 additions & 0 deletions AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
using System.Diagnostics;
using System.IO.Abstractions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -91,6 +93,71 @@
}
}

/// <summary>
/// The type that first used each settings file, per file system, so two types never share one file.
/// </summary>
/// <remarks>
/// Keyed by file system as well as path, because each test thread gets its own mock file system and
/// the same path there is a different file.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "ConditionalWeakTable has no collection initializer on netstandard2.0, so [] does not compile there.")]
private static readonly ConditionalWeakTable<IFileSystem, Dictionary<string, Type>> FileOwners = new();

/// <summary>
/// Records that <typeparamref name="T"/> uses <paramref name="filePath"/>, and throws if a different type
/// already does.
/// </summary>
/// <remarks>
/// The default file name is the simple type name in snake case, so <c>PluginA.Settings</c> and
/// <c>PluginB.Settings</c>, or <c>Gen&lt;int&gt;</c> and <c>Gen&lt;string&gt;</c>, resolve to the same file.
/// Each type holds its own lock, and each would load the other's file without error and save over it,
/// silently wiping the other's data (ktsu-dev/AppDataStorage#336). The default name is not changed,
/// because that would move existing users' data. A collision is an error instead, raised the first
/// time the second type loads or saves.
/// </remarks>
/// <typeparam name="T">The type of the app data.</typeparam>
/// <param name="filePath">The settings file the type is about to read or write.</param>
/// <exception cref="InvalidOperationException">Thrown when a different type already uses <paramref name="filePath"/>.</exception>
internal static void ClaimFile<T>(AbsoluteFilePath filePath) where T : AppData<T>, new()
{
Dictionary<string, Type> owners = FileOwners.GetValue(FileSystem, _ => new(PathComparer));
string key = filePath.ToString();
lock (owners)
{
if (!owners.TryGetValue(key, out Type? owner))
{
owners[key] = typeof(T);
return;
}

if (owner != typeof(T))
{
throw new InvalidOperationException(
$"{Describe(typeof(T))} cannot use '{key}', because {Describe(owner)} already uses it. " +
"Two app data types with the same name share a default file name. Give one of them its own file " +
"with the LoadOrCreate(fileName) or LoadOrCreate(subdirectory) overloads.");
}
}
}

/// <summary>
/// File names are case-insensitive on Windows and, by default, on macOS.
/// </summary>
private static StringComparer PathComparer =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal;

/// <summary>
/// Names a type with its namespace and generic arguments, which is what tells two colliding types apart.
/// </summary>
/// <param name="type">The type to name.</param>
/// <returns>The readable full name.</returns>
private static string Describe(Type type) =>
type.IsGenericType
? $"{type.Namespace}.{type.Name.Split('`')[0]}<{string.Join(", ", type.GetGenericArguments().Select(Describe))}>"
: type.FullName ?? type.Name;

/// <summary>
/// Calls a setter through reflection, throwing what the setter throws rather than the
/// <see cref="TargetInvocationException"/> reflection wraps it in.
Expand Down Expand Up @@ -621,10 +688,10 @@
/// </summary>
#if NET9_0_OR_GREATER
[JsonIgnore]
public static Lock Lock { get; } = new();

Check warning on line 691 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 691 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 691 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 691 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 694 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 694 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 694 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 694 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 694 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 694 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 @@ -651,6 +718,7 @@
{
lock (Lock)
{
AppData.ClaimFile<T>(FilePath);
string jsonString = JsonSerializer.Serialize(this, typeof(T), AppData.JsonSerializerOptions);
AppData.WriteText((T)this, jsonString);
LastSaveTime = DateTime.UtcNow;
Expand Down Expand Up @@ -765,6 +833,7 @@
FileNameOverride = fileName,
};

AppData.ClaimFile<T>(newAppData.FilePath);
string jsonString = AppData.ReadText(newAppData);

if (string.IsNullOrEmpty(jsonString))
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ copy.Save();
- Whether a save is outstanding is the `HasQueuedSave` flag, set by `QueueSave()` and cleared by a successful `Save()`. It is not `SaveQueuedTime > LastSaveTime`: `DateTime.UtcNow` advances in whole microseconds on macOS, so a queue straight after a save can read the same instant and would be dropped
- Automatic backup files (`.bk` suffix) with timestamped collision handling
- Safe write pattern: write `.tmp` and flush it to disk, then `File.Replace` it over the final file (keeping `.bk` until done), or move it into place when there is no final file yet
- Each settings file belongs to the first `AppData<T>` type that loads or saves it, per file system. A different type that resolves to the same path (two `Settings` classes in different namespaces, or `Gen<int>` and `Gen<string>`) throws `InvalidOperationException` naming both, instead of silently sharing the file (ktsu-dev/AppDataStorage#336)
- 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
Expand Down
Loading