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
This commit is contained in:
Claude committed 2026-10-12 10:06:34 +00:00
1 parent c11c996bc6
commit 3e146c9f9f
91 files changed
+2864 -357

No files matched your search

@@ -0,0 +1,159 @@
using System.Text.Json.Nodes;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.Data.Tests.Archiving;
/// <summary>
/// An archive's settings live in its archive.json (BRIEF §7): changing them rewrites the file atomically and the index
/// row, survives a reopen (which registers the archive from the file again), and the proxy and thumbnail jobs use them.
/// </summary>
[Category("archive")]
public sealed class ArchiveSettingsTests(TestContext context)
{
[Test]
public async Task ChangedSettingsReachArchiveJsonTheIndexAndAReopen()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var updated = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with
{
Name = " Studio ",
Templates = s.Templates with { Folder = "{year}/{camera}", File = "{name}" },
Proxies = s.Proxies with { LongEdge = 2560 },
Thumbnails = s.Thumbnails with { LongEdge = 480 },
}, fx.Ct);
Assert.Equal(("Studio", "{year}/{camera}", "{name}", 2560), (updated.Name, updated.FolderTemplate, updated.FileTemplate, updated.ProxyLongEdge));
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
Assert.Equal(fx.Archive.Id, manifest.Id);
Assert.Equal(("Studio", "{year}/{camera}", "{name}"), (manifest.Name, manifest.LayoutTemplates.Folder, manifest.LayoutTemplates.File));
Assert.Equal((2560, 480), (manifest.ProxyPolicy.LongEdge, manifest.ThumbnailPolicy.LongEdge));
var row = (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!;
Assert.Equal(("Studio", "{year}/{camera}", 2560), (row.Name, row.FolderTemplate, row.ProxyLongEdge));
Assert.Empty(Directory.GetFiles(fx.Paths.MetaDirectory, "*.tmp"));
// A restart registers the archive from archive.json again: the change stays.
var reopened = await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct);
Assert.Equal(("Studio", "{name}", 2560), (reopened.Name, reopened.FileTemplate, reopened.ProxyLongEdge));
var settings = await fx.Service.GetSettingsAsync(fx.Archive.Id, fx.Ct);
Assert.Equal(480, settings.Thumbnails.LongEdge);
}
[Test]
public async Task AnEditKeepsWhatAnotherProcessChangedAndUnknownFields()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
// A newer Titano (or the server) wrote a field this build does not know, and changed the proxy size.
var json = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!.AsObject();
json["futureOption"] = 42;
json["proxyPolicy"]!["longEdge"] = 1280;
await File.WriteAllTextAsync(fx.Paths.ManifestPath, json.ToJsonString(), fx.Ct);
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct);
var written = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!;
Assert.Equal(42, (int)written["futureOption"]!);
Assert.Equal(1280, (int)written["proxyPolicy"]!["longEdge"]!);
Assert.Equal("{date}_{n:0000}", (string)written["layoutTemplates"]!["file"]!);
}
[Test]
public async Task InvalidSettingsAreRefusedAndNothingIsWritten()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var before = await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct);
var template = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct));
Assert.Equal("folderTemplate", template.ParamName);
var proxies = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
Assert.Equal("proxyLongEdge", proxies.ParamName);
var thumbnails = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Thumbnails = s.Thumbnails with { LongEdge = 5000 } }, fx.Ct));
Assert.Equal("thumbnailLongEdge", thumbnails.ParamName);
var name = await Assert.ThrowsAsync<ArgumentException>(() => fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Name = " " }, fx.Ct));
Assert.Equal("name", name.ParamName);
Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct));
}
[Test]
public async Task AnOfflineArchiveIsNotChangedAndItsIndexSettingsAreShown()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 1280 } }, fx.Ct);
// The drive is unplugged: archive.json is out of reach.
File.Move(fx.Paths.ManifestPath, fx.Paths.ManifestPath + ".away");
await Assert.ThrowsAsync<ArchiveOfflineException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct));
var shown = await fx.Service.GetSettingsAsync(fx.Archive.Id, fx.Ct);
Assert.Equal((1280, FrameImageRenderer.ThumbnailLongEdge), (shown.Proxies.LongEdge, shown.Thumbnails.LongEdge));
}
[Test]
public async Task ANewArchiveTakesTheDefaultsAndAnExistingOneKeepsItsOwn()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var defaults = new ArchiveSettings(string.Empty, new LayoutTemplates { Folder = "{camera}/{date}", File = "{time}_{n}" },
new ProxyPolicy { LongEdge = ProxyPolicy.Disabled }, new ThumbnailPolicy { LongEdge = 640 });
var root = Path.Combine(context.CreateTempDirectory("new"), "Mountains");
Directory.CreateDirectory(root);
var created = await fx.Service.AdoptAsync(root, defaults, fx.Ct);
var manifest = ManifestStore.ReadArchive(new ArchivePaths(root).ManifestPath);
Assert.Equal(("Mountains", "{camera}/{date}", "{time}_{n}"), (created.Name, manifest.LayoutTemplates.Folder, manifest.LayoutTemplates.File));
Assert.Equal((ProxyPolicy.Disabled, 640), (manifest.ProxyPolicy.LongEdge, manifest.ThumbnailPolicy.LongEdge));
// The fixture's archive already exists: adopting it again opens it with its own settings.
var existing = await fx.Service.AdoptAsync(fx.Archive.RootPath, defaults, fx.Ct);
Assert.Equal((fx.Archive.Id, fx.Archive.FolderTemplate), (existing.Id, existing.FolderTemplate));
Assert.Equal(1920, ManifestStore.ReadArchive(fx.Paths.ManifestPath).ProxyPolicy.LongEdge);
}
[Test]
public async Task ProxyAndThumbnailJobsFollowTheArchiveSettings()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var folder = Path.Combine(fx.Paths.Root, "Harbour");
Directory.CreateDirectory(folder);
for (var i = 0; i < 3; i++)
await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), Photo(ArchiveFixture.Start.AddSeconds(2 * i), i), fx.Ct);
await fx.ScanAsync(ScanMode.Full);
var sequence = (await fx.Db.Sequences.GetAsync((await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Single().Id, fx.Ct))!;
var paths = fx.Paths.Sequence(sequence.Folder);
// No proxies for this archive: the proxy job builds none.
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = ProxyPolicy.Disabled } }, fx.Ct);
var proxies = await fx.Service.Images.BuildProxiesAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((0, 0), (proxies.Built, proxies.Reused));
Assert.False(Directory.Exists(paths.Proxies) && Directory.EnumerateFiles(paths.Proxies).Any(), "no proxy written");
// Small thumbnails: every one fits the archive's long edge.
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Thumbnails = s.Thumbnails with { LongEdge = ThumbnailPolicy.MinLongEdge } }, fx.Ct);
var thumbnails = await fx.Service.Images.BuildThumbnailsAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(3, thumbnails.Built);
using var pack = ThumbPackReader.Open(paths.ThumbsPackPath);
Assert.Count(3, pack.Entries);
Assert.True(pack.Entries.Values.All(e => int.Max(e.Width, e.Height) == ThumbnailPolicy.MinLongEdge), "thumbnails at the archive's size");
}
/// <summary>A 480×320 JPEG with its capture time: larger than every thumbnail size.</summary>
private static byte[] Photo(DateTime captured, int seed)
{
using var image = new ImageBuffer(480, 320);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = (seed + 1) * 0.2f * (i % 480) / 480f;
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = "Canon", Model = "Canon EOS R5", CapturedAt = captured, Iso = 100 });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
}
@@ -0,0 +1,80 @@
using System.Globalization;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.Data.Tests.Archiving;
/// <summary>Maintenance vacuums the SQLite index (BRIEF §12.5 "SQLite vacuum"); a dry run only reports the reclaimable space.</summary>
[Category("archive")]
public sealed class IndexMaintenanceTests(TestContext context)
{
[Test]
public async Task ADryRunReportsTheFreePagesAndARunGivesThemBack()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await FreeSpaceAsync(fx.Db, fx.Ct);
var before = (await fx.Db.SpaceAsync(fx.Ct))!;
Assert.True(before.ReclaimableBytes >= before.FileBytes * 0.3, $"free pages made ({before.ReclaimableBytes} of {before.FileBytes})");
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((before.ReclaimableBytes, 0L), (dry.IndexReclaimable, dry.IndexReclaimed));
Assert.Equal(before.ReclaimableBytes, (await fx.Db.SpaceAsync(fx.Ct))!.ReclaimableBytes);
var run = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Greater(run.IndexReclaimed, 0L);
var after = (await fx.Db.SpaceAsync(fx.Ct))!;
Assert.Equal(0L, after.ReclaimableBytes);
Assert.Less(after.FileBytes, before.FileBytes);
// The index still answers after the rewrite.
Assert.NotNull(await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task AFewFreePagesAreNotWorthARewrite()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var space = (await fx.Db.SpaceAsync(fx.Ct))!;
Assert.True(space.ReclaimableBytes < space.FileBytes * ArchiveMaintenance.IndexVacuumRatio, "a fresh index has almost no free pages");
var run = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((space.ReclaimableBytes, 0L), (run.IndexReclaimable, run.IndexReclaimed));
}
[Test]
public async Task TheMaintenanceJobLogsTheVacuum()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await FreeSpaceAsync(fx.Db, fx.Ct);
var engine = await fx.StartEngineAsync();
var dry = await engine.EnqueueAsync(ArchiveJobs.Maintenance(fx.Archive, dryRun: true), cancellationToken: fx.Ct);
var dryDone = await fx.WaitForAsync(dry.Id, JobState.Done);
Assert.True(HasLine(dryDone.LogTail, "Archive.Log.IndexReclaimable"), dryDone.LogTail ?? "no log");
Assert.False(HasLine(dryDone.LogTail, "Archive.Log.IndexVacuumed"), "a dry run rewrites nothing");
var run = await engine.EnqueueAsync(ArchiveJobs.Maintenance(fx.Archive), cancellationToken: fx.Ct);
var runDone = await fx.WaitForAsync(run.Id, JobState.Done);
Assert.Equal(5L, runDone.ProgressTotal);
Assert.True(HasLine(runDone.LogTail, "Archive.Log.IndexVacuumed"), runDone.LogTail ?? "no log");
Assert.Equal(0L, (await fx.Db.SpaceAsync(fx.Ct))!.ReclaimableBytes);
}
/// <summary>A log line made from the one-argument sentence <paramref name="key"/>, whatever its size argument.</summary>
private static bool HasLine(string? log, string key)
{
var parts = Loc.L(key, "\0").Split('\0');
return (log ?? string.Empty).Split('\n').Any(l => l.Contains(parts[0], StringComparison.Ordinal) && l.TrimEnd().EndsWith(parts[1].TrimEnd(), StringComparison.Ordinal));
}
/// <summary>Writes about 2 MB of rows and deletes them: SQLite keeps the pages as free pages until a vacuum.</summary>
internal static async Task FreeSpaceAsync(TitanoDatabase db, CancellationToken cancellationToken)
{
var filler = new string('x', 4000);
for (var i = 0; i < 500; i++)
await db.Settings.SetJsonAsync(SettingScope.App, null, "filler." + i.ToString(CultureInfo.InvariantCulture), "\"" + filler + "\"", cancellationToken);
for (var i = 0; i < 500; i++) await db.Settings.DeleteAsync(SettingScope.App, null, "filler." + i.ToString(CultureInfo.InvariantCulture), cancellationToken);
}
}