using Titano.Core.Model; using Titano.Data.Repositories; using Titano.Testing; namespace Titano.Data.Tests.Sqlite; /// /// BRIEF §6.2: a VACUUM INTO copy of the SQLite index once a day, the newest three kept, and a restore from Settings › /// Advanced that waits for the next start, checks the copy first and never replaces a working index with a broken one. /// [Category("sqlite")] public sealed class DatabaseBackupsTests(TestContext context) { /// A clock the test moves; timers created on it never fire by themselves. private sealed class ManualClock(DateTimeOffset now) : TimeProvider { public DateTimeOffset Now { get; set; } = now; public override DateTimeOffset GetUtcNow() => Now; } private async Task<(TitanoDatabase Db, string Path)> OpenAsync(string name = "titano.db") { var path = System.IO.Path.Combine(context.CreateTempDirectory("db"), name); return (await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation), path); } private static Task AddArchiveAsync(TitanoDatabase db, string name) => db.Archives.UpsertAsync(new Archive { Id = Guid.CreateVersion7(), Name = name, RootPath = "/archives/" + name, Created = DateTimeOffset.UtcNow }); [Test] public async Task ListsTheCopiesOfThisIndexNewestFirst() { var directory = context.CreateTempDirectory("backups"); File.WriteAllText(Path.Combine(directory, "titano-20261010-030000-000.db"), "a"); File.WriteAllText(Path.Combine(directory, "titano-20261012-030000-000.db"), "bb"); File.WriteAllText(Path.Combine(directory, "titano-20261011-030000-000.db"), "ccc"); File.WriteAllText(Path.Combine(directory, "other-20261013-030000-000.db"), "x"); File.WriteAllText(Path.Combine(directory, "titano-notes.db"), "x"); var backups = DatabaseBackups.List(directory, "/data/titano.db"); Assert.SequenceEqual(["titano-20261012-030000-000.db", "titano-20261011-030000-000.db", "titano-20261010-030000-000.db"], backups.Select(b => Path.GetFileName(b.Path))); Assert.Equal(new DateTimeOffset(2026, 10, 12, 3, 0, 0, TimeSpan.Zero), backups[0].Created); Assert.Equal(2L, backups[0].Bytes); Assert.Empty(DatabaseBackups.List(Path.Combine(directory, "missing"), "/data/titano.db")); } [Test] public void ACopyIsDueWhenTheNewestIsADayOld() { var now = new DateTimeOffset(2026, 10, 12, 9, 0, 0, TimeSpan.Zero); Assert.True(DatabaseBackups.IsDue([], now)); Assert.False(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-23), 1)], now)); Assert.True(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-24), 1)], now)); } [Test] public async Task TheDailyCopyIsMadeAtStartOnlyWhenDue() { var (db, _) = await OpenAsync(); await using var _ = db; var directory = context.CreateTempDirectory("backups"); var clock = new ManualClock(DateTimeOffset.UtcNow); // No copy yet: one is made at once, then the loop waits for its hourly check until stopped. using (var stop = new CancellationTokenSource()) { var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token); var until = DateTime.UtcNow.AddSeconds(20); while (Directory.GetFiles(directory, "*.db").Length == 0 && DateTime.UtcNow < until) await Task.Delay(20); await stop.CancelAsync(); await loop.WaitAsync(TimeSpan.FromSeconds(20)); } Assert.Count(1, Directory.GetFiles(directory, "*.db")); // A fresh copy exists: starting again makes none. using (var stop = new CancellationTokenSource()) { var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token); await Task.Delay(300); await stop.CancelAsync(); await loop.WaitAsync(TimeSpan.FromSeconds(20)); } Assert.Count(1, Directory.GetFiles(directory, "*.db")); } [Test] public async Task AStagedRestoreReplacesTheIndexAtTheNextOpen() { var (db, path) = await OpenAsync(); var directory = context.CreateTempDirectory("backups"); await AddArchiveAsync(db, "kept"); var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation); await AddArchiveAsync(db, "added later"); Assert.Equal(new DatabaseSummary(db.SchemaVersion, 2, 0, 0), await DatabaseBackups.SummarizeAsync(db, context.Cancellation)); // The dry run reads the copy without touching it. var bytes = await File.ReadAllBytesAsync(backup, context.Cancellation); var summary = await DatabaseBackups.SummarizeBackupAsync(backup, context.CreateTempDirectory("scratch"), context.Cancellation); Assert.Equal(1, summary.Archives); Assert.SequenceEqual(bytes, await File.ReadAllBytesAsync(backup, context.Cancellation)); await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation); Assert.True(DatabaseBackups.HasStagedRestore(path)); await db.DisposeAsync(); // The next start: the index as it was is copied first, then it is the chosen copy and the staged file is gone. await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation); Assert.True(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation)); Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name)); Assert.False(DatabaseBackups.HasStagedRestore(path)); var copies = DatabaseBackups.List(directory, path); Assert.Count(2, copies); var replaced = await DatabaseBackups.SummarizeBackupAsync(copies[0].Path, context.CreateTempDirectory("scratch"), context.Cancellation); Assert.Equal(2, replaced.Archives); Assert.False(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation), "nothing staged any more"); } [Test] public async Task ABrokenStagedCopyIsSetAsideAndTheIndexKept() { var (db, path) = await OpenAsync(); await using var _ = db; await AddArchiveAsync(db, "current"); await File.WriteAllTextAsync(DatabaseBackups.StagedPath(path), "this is not a database", context.Cancellation); var backups = context.CreateTempDirectory("backups"); await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(db, backups, context.Cancellation)); Assert.False(DatabaseBackups.HasStagedRestore(path)); Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed"); Assert.Empty(DatabaseBackups.List(backups, path)); Assert.SequenceEqual(["current"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name)); await Assert.ThrowsAsync(() => DatabaseBackups.SummarizeBackupAsync(DatabaseBackups.StagedPath(path) + ".failed", context.CreateTempDirectory("scratch"), context.Cancellation)); } [Test] public async Task CancellingAStagedRestoreKeepsTheIndex() { var (db, path) = await OpenAsync(); await using var _ = db; var directory = context.CreateTempDirectory("backups"); var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation); await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation); DatabaseBackups.CancelStagedRestore(path); Assert.False(DatabaseBackups.HasStagedRestore(path)); Assert.False(await DatabaseBackups.RestoreStagedAsync(db, directory, context.Cancellation)); Assert.FileExists(backup); } [Test] public async Task ARestoreWaitsWhenTheIndexCannotBeBackedUpFirst() { var (db, path) = await OpenAsync(); await using var _ = db; var backup = await db.BackupAsync(context.CreateTempDirectory("backups"), DatabaseBackups.Keep, context.Cancellation); await AddArchiveAsync(db, "since the backup"); await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation); // The backups folder cannot be created: a file is in its way. var blocked = Path.Combine(context.CreateTempDirectory("blocked"), "backups"); await File.WriteAllTextAsync(blocked, "not a folder", context.Cancellation); await Assert.ThrowsAsync(() => DatabaseBackups.RestoreStagedAsync(db, blocked, context.Cancellation)); Assert.SequenceEqual(["since the backup"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name)); Assert.True(DatabaseBackups.HasStagedRestore(path), "the restore stays staged for the next start"); } }