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
31 changes: 31 additions & 0 deletions AppDataStorage.Test/AppDataTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,37 @@
Assert.IsTrue(appData.IsSaveQueued(), "A save queued after the last save must be outstanding whatever the clock reads.");
}

[TestMethod]
public void TestDisposeWritesAQueuedSaveWhenTheClockHasNotAdvancedSinceTheLastSave()
{
TestAppData appData = CreateTestAppDataWithContent("before");
appData.Save();
appData.LastSaveTime = DateTime.MaxValue;
appData.Data = "after";
appData.QueueSave();

appData.Dispose();

TestAppData? onDisk = JsonSerializer.Deserialize<TestAppData>(AppData.FileSystem.File.ReadAllText(appData.FilePath), AppData.JsonSerializerOptions);
Assert.AreEqual("after", onDisk?.Data, "Dispose should write the queued save whatever the clock read at the last save.");
}

[TestMethod]
public async Task TestSaveIfRequiredSavesAfterTheDebounceWhenTheWallClockStepsBack()
{
using TestAppData appData = CreateTestAppDataWithContent(TestDataString);
appData.QueueSave();

// Stand in for the wall clock being set back an hour after the queue: on the wall clock the
// queue is now an hour in the future, and the time since it is negative until the hour passes.
appData.SaveQueuedTime = DateTime.UtcNow + TimeSpan.FromHours(1);
await Task.Delay(appData.SaveDebounceTime + TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);

Check warning on line 431 in AppDataStorage.Test/AppDataTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_AppDataStorage&issues=AaE6OSomPo8ZZaibn7xm&open=AaE6OSomPo8ZZaibn7xm&pullRequest=350

appData.SaveIfRequired();

AssertFileExists(appData.FilePath, "The debounce should elapse on real time, not on a wall clock that was set back.");
}

[TestMethod]
public void TestSaveClearsQueuedSave()
{
Expand Down
16 changes: 15 additions & 1 deletion AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ktsu.AppDataStorage;

using System.Diagnostics;
using System.IO.Abstractions;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -261,6 +262,7 @@
lock (AppData<T>.Lock)
{
appData.SaveQueuedTime = DateTime.UtcNow;
appData.SaveQueuedTimestamp = Stopwatch.GetTimestamp();
appData.HasQueuedSave = true;
appData.EnsureDisposeOnExit();
}
Expand Down Expand Up @@ -442,6 +444,17 @@
/// </summary>
internal DateTime SaveQueuedTime { get; set; } = DateTime.MinValue;

/// <summary>
/// Gets or sets the <see cref="Stopwatch.GetTimestamp"/> reading taken when the save was queued.
/// </summary>
/// <remarks>
/// The debounce is measured from this rather than from <see cref="SaveQueuedTime"/>, because the wall
/// clock can be set back by an NTP correction, a manual change or a VM resume. Measured on the wall
/// clock, the time since the queue then stays negative, and <c>SaveIfRequired</c> holds the save back
/// for as long as the clock went back. The stopwatch only moves forward.
/// </remarks>
internal long SaveQueuedTimestamp { get; set; }

/// <summary>
/// Gets or sets a value indicating whether a save has been queued and not yet written.
/// </summary>
Expand Down Expand Up @@ -471,10 +484,10 @@
/// </summary>
#if NET9_0_OR_GREATER
[JsonIgnore]
public static Lock Lock { get; } = new();

Check warning on line 487 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 487 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 487 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 487 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 490 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 490 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 490 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 490 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 490 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 490 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 @@ -489,7 +502,8 @@
{
lock (Lock)
{
return (DateTime.UtcNow - SaveQueuedTime) > SaveDebounceTime;
double elapsedSeconds = (double)(Stopwatch.GetTimestamp() - SaveQueuedTimestamp) / Stopwatch.Frequency;
return elapsedSeconds > SaveDebounceTime.TotalSeconds;
}
}

Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ data.Save();

- Files stored in `%APPDATA%/{AppDomain.FriendlyName}/` as `{class_name_snake_case}.json`
- Thread-safe with lock objects (uses `Lock` type on .NET 9+, `object` on earlier versions)
- Debounced saves via `QueueSave()` / `SaveIfRequired()` (3-second debounce)
- Debounced saves via `QueueSave()` / `SaveIfRequired()` (3-second debounce, timed with `Stopwatch.GetTimestamp()` so a wall-clock step back cannot hold a save back)
- 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 to `.tmp`, backup existing, move `.tmp` to final
Expand Down
Loading