Files
Chronos/tests/Titano.Data.Tests/Sqlite/DatabaseBackupsTests.cs
T
Claude 3e146c9f9f feat(settings): make every Settings row real; archive settings, index backups and restore
Settings (UI-01, UI-02, UI-03, UI-09, RF-4):
- New Import, Analysis and Formats pages, in the order of Settings.html. Import holds
  the defaults of new cards (session rules, subfolders, verification, duplicates,
  after-import actions); Analysis the deep-analysis width cap, night and star-field
  thresholds and deep analysis after import or scan; Formats the decode tier of every
  format on this PC with a notice and Store install link per missing codec extension.
- Archive gains thumbnail size and rescan interval; its templates, proxy size and
  thumbnail size are the open archive's own (archive.json) and new archives' defaults.
- Rendering quality, parallelism and background priority now drive the jobs: quality
  maps to preparation size, read-ahead and default flow quality; parallelism sets the
  engine's workers live and caps per-job threads; background priority raises the UI
  thread while Titano is in front.
- Advanced gains Restore (daily backups, dry-run summary, destructive confirmation,
  staged for the next start) and Reset all.
- The naming preview's sample title is a catalog string.

Engine (ENG-03, ENG-04, ENG-06):
- ArchiveService.GetSettingsAsync/UpdateSettingsAsync rewrite archive.json atomically
  under a lease, then the index row; the server endpoint and the desktop use them, and
  the desktop creates archives with Settings › Archive. ThumbnailPolicy in archive.json
  sizes the thumbnails.
- DatabaseBackups: daily VACUUM INTO copies kept x3 on the desktop and on a server on
  SQLite (DatabaseBackupService), staged restore checked and preceded by a fresh copy.
- Maintenance vacuums the SQLite index when 10 % or more is free (dry run reports it).
- JobEngine.SetWorkers; ProcessingOptions.Tune applies host tuning per job.

Archive setup toasts say why in a localized sentence (RF-1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:06:34 +00:00

174 lines
8.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Titano.Core.Model;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.Data.Tests.Sqlite;
/// <summary>
/// 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.
/// </summary>
[Category("sqlite")]
public sealed class DatabaseBackupsTests(TestContext context)
{
/// <summary>A clock the test moves; timers created on it never fire by themselves.</summary>
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<InvalidDataException>(() => 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<InvalidDataException>(() =>
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<IOException>(() => 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");
}
}