using Febe.Core.Library; using Febe.Tests.Support; using Microsoft.Data.Sqlite; namespace Febe.Tests.Library; [TestClass] public sealed class DailyBackupTests { [TestMethod] public async Task MakesOneConsistentCopyPerLocalDay() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); await db.Accounts.AddAsync(Make.Account("marta.demo")); // 23:30 UTC on 12 October is already the 13th in Rome. var clock = new ManualClock(new DateTimeOffset(2026, 10, 12, 23, 30, 0, TimeSpan.Zero)); var backup = new DailyBackup(db.Maintenance, clock, temp.Combine("dati", "copie")); var first = await backup.RunAsync(); Assert.IsNotNull(first.Created); Assert.AreEqual(new DateOnly(2026, 10, 13), first.Created.Day); Assert.AreEqual("febe-2026-10-13.sqlite", Path.GetFileName(first.Created.Path)); using (var connection = new SqliteConnection($"Data Source={first.Created.Path};Mode=ReadOnly;Pooling=False")) { connection.Open(); using var command = connection.CreateCommand(); command.CommandText = "SELECT username FROM account"; Assert.AreEqual("marta.demo", command.ExecuteScalar()); } await db.Accounts.AddAsync(Make.Account("luca.demo")); clock.Now = clock.Now.AddHours(12); var second = await backup.RunAsync(); Assert.IsNull(second.Created, "La copia del giorno c'è già."); Assert.HasCount(1, backup.List()); Assert.IsEmpty(Directory.GetFiles(backup.Folder, "*.part")); } [TestMethod] public async Task KeepsSevenDays() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var folder = temp.Combine("dati", "copie"); Directory.CreateDirectory(folder); var today = new DateOnly(2026, 10, 13); for (var i = 1; i <= 10; i++) { await File.WriteAllTextAsync(Path.Combine(folder, DailyBackup.FileNameFor(today.AddDays(-i))), "vecchia"); } await File.WriteAllTextAsync(Path.Combine(folder, "appunti.txt"), "non toccare"); var clock = new ManualClock(LibraryTimes.Noon(today)); var interrupted = Path.Combine(folder, "febe-2026-10-12.sqlite.abcd1234.part"); await File.WriteAllTextAsync(interrupted, "copia interrotta"); File.SetLastWriteTimeUtc(interrupted, clock.Now.UtcDateTime.AddDays(-1)); var writing = Path.Combine(folder, "febe-2026-10-13.sqlite.ef567890.part"); await File.WriteAllTextAsync(writing, "copia in corso"); File.SetLastWriteTimeUtc(writing, clock.Now.UtcDateTime.AddMinutes(-2)); var backup = new DailyBackup(db.Maintenance, clock, folder); var result = await backup.RunAsync(); Assert.IsNotNull(result.Created); var kept = backup.List().Select(b => b.Day).ToList(); Assert.HasCount(7, kept); Assert.AreEqual(today, kept[0]); Assert.AreEqual(today.AddDays(-6), kept[^1]); Assert.HasCount(5, result.Removed); // four old copies and the interrupted one Assert.IsFalse(File.Exists(interrupted)); Assert.IsTrue(File.Exists(writing), "A temporary copy written minutes ago may belong to a copy still running."); Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt"))); } /// /// «Fai una copia adesso» clicked twice, or clicked while the 3:20 copy runs: the copies take turns, and neither /// one removes the temporary file of the other. /// [TestMethod] public async Task TwoCopiesAtTheSameTimeBothSucceed() { using var temp = new TempFolder(); var folder = temp.Combine("dati", "copie"); var clock = new ManualClock(LibraryTimes.Noon(new DateOnly(2026, 10, 13))); var database = new SlowBackups(); var first = new DailyBackup(database, clock, folder).RunNowAsync(); await database.FirstStarted.Task.WaitAsync(TimeSpan.FromSeconds(10)); var second = new DailyBackup(database, clock, folder).RunNowAsync(); await Task.WhenAny(second, Task.Delay(500)); // without turns, the second copy finishes here and its retention runs database.ReleaseFirst.SetResult(); var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(10)); Assert.IsTrue(results.All(r => r.Created is not null)); Assert.AreEqual(1, database.MaxConcurrent, "One copy of a folder at a time."); Assert.HasCount(1, Directory.GetFiles(folder, "*.sqlite")); Assert.IsEmpty(Directory.GetFiles(folder, "*.part")); } /// VACUUM INTO stand-in: the first copy waits until the test lets it finish. private sealed class SlowBackups : Core.Storage.IDatabaseMaintenance { private int _calls; private int _running; private int _max; public TaskCompletionSource FirstStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource ReleaseFirst { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public int MaxConcurrent => Volatile.Read(ref _max); public string DatabasePath => "febe.sqlite"; public int SchemaVersion => 1; public async Task BackupToAsync(string destinationFile, CancellationToken ct = default) { var running = Interlocked.Increment(ref _running); int seen; while ((seen = Volatile.Read(ref _max)) < running && Interlocked.CompareExchange(ref _max, running, seen) != seen) { } try { await File.WriteAllTextAsync(destinationFile, "copia", ct); if (Interlocked.Increment(ref _calls) == 1) { FirstStarted.SetResult(); await ReleaseFirst.Task.WaitAsync(ct); } } finally { Interlocked.Decrement(ref _running); } } public Task CheckIntegrityAsync(CancellationToken ct = default) => Task.FromResult(true); public Task OptimizeAsync(CancellationToken ct = default) => Task.CompletedTask; } [TestMethod] public void RecognizesOnlyItsOwnFileNames() { Assert.AreEqual(new DateOnly(2026, 1, 2), DailyBackup.TryParseDay("febe-2026-01-02.sqlite")); Assert.IsNull(DailyBackup.TryParseDay("febe-2026-13-02.sqlite")); Assert.IsNull(DailyBackup.TryParseDay("febe.sqlite")); Assert.IsNull(DailyBackup.TryParseDay("altro-2026-01-02.sqlite")); Assert.IsNull(DailyBackup.TryParseDay("febe-2026-01-02.sqlite.part")); } [TestMethod] public async Task TheDatabaseRefusesToOverwriteACopy() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var target = temp.Combine("copia.sqlite"); await db.Maintenance.BackupToAsync(target); await Assert.ThrowsExactlyAsync(() => db.Maintenance.BackupToAsync(target)); Assert.IsTrue(await db.Maintenance.CheckIntegrityAsync()); await db.Maintenance.OptimizeAsync(); } private static class LibraryTimes { public static DateTimeOffset Noon(DateOnly day) => Core.Domain.LocalCalendar.FromLocal(day.ToDateTime(new TimeOnly(12, 0)), TestZones.Rome); } }