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

@@ -164,6 +164,125 @@ public sealed class SettingsLogicTests
Assert.Null(EncoderUse.Codecs([]));
}
[Test]
public void ThePreviewTitleSpeaksTheInterfaceLanguage()
{
// The sample's title is a catalog string read on every preview (so a language switch shows at once), not English text.
Assert.Equal("Harbour sunset", NamingPreview.FirstNames("{title}", "{n:0000}")[0].Split('/')[0]);
Assert.Equal("Harbour sunset", NamingPreview.SampleFrames[0].Title);
Assert.False(ReferenceEquals(NamingPreview.SampleFrames, NamingPreview.SampleFrames), "built on each call");
var italian = Loc.Get("Settings.Naming.SampleTitle", CultureInfo.GetCultureInfo("it"));
Assert.True(italian is { Length: > 0 } && italian != "Harbour sunset", italian);
}
[Test]
public void TheQualityProfileTunesTheJobs()
{
var settings = new Titano.App.Infrastructure.AppSettings { Quality = Titano.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Titano.Data.Processing.ProcessingOptions();
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, @"C:\cache", 8, 2), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((1024, Titano.Core.Project.FlowQualitySetting.Best), (best.Render.AnalysisLongEdge, best.Render.DefaultFlowQuality));
Assert.Equal(int.Min(3, Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.MaxDegreeOfParallelism), best.DeepAnalysis.MaxDegreeOfParallelism);
settings.Quality = Titano.App.Infrastructure.QualityProfile.Fast;
settings.MemoryBudgetGb = null;
settings.Parallelism = null;
var fast = ProcessingTuning.Apply(basis, settings, 32L << 30, 16, @"C:\cache");
Assert.Equal((8L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((256, Titano.Core.Project.FlowQualitySetting.Draft), (fast.Render.AnalysisLongEdge, fast.Render.DefaultFlowQuality));
Assert.Equal(512, ProcessingTuning.PreparationLongEdge(Titano.App.Infrastructure.QualityProfile.Balanced));
}
[Test]
public void ParallelismAutoLeavesFourCoresToTheInterface()
{
Assert.Equal(12, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(2));
Assert.Equal(12, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
[Test]
public void TheAnalysisSettingsBecomeTheDeepAnalysisParameters()
{
var defaults = new Titano.App.Infrastructure.AppSettings().DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
// The defaults of Settings › Analysis are the engine's own: nothing changes until the user does.
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.Fingerprint(), defaults.Fingerprint());
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.StarFieldDensity, defaults.StarFieldDensity);
var tuned = new Titano.App.Infrastructure.AppSettings { AnalysisLongEdge = 1024, NightBrightnessPercent = 12.5, StarFieldDensity = 60 }
.DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
Assert.Equal((1024, -3.0, 60.0), (tuned.MaxAnalysisLongEdge, tuned.DarkLogLuminance, tuned.StarFieldDensity));
}
[Test]
public void NewCardsStartFromSettingsImport()
{
var settings = new Titano.App.Infrastructure.AppSettings
{
ImportSessionGapMinutes = 90,
ImportMinimumFrames = 20,
ImportSubfolders = false,
ImportVerify = false,
ImportDuplicates = Titano.Core.Import.DuplicatePolicy.ImportAgain,
ImportAfter = Titano.Data.Archiving.AfterImport.DeleteImported,
ImportEject = false,
DeepAnalysisAfterImport = false,
};
var profile = settings.ImportProfile("{year}", "{name}");
Assert.Equal(("{year}", "{name}", 90, 20), (profile.FolderTemplate, profile.FileTemplate, profile.SessionGapMinutes, profile.MinimumSessionFrames));
Assert.Equal((false, false, false, false), (profile.IncludeSubfolders, profile.VerifyCopies, profile.Eject, profile.DeepAnalysis));
Assert.Equal((Titano.Core.Import.DuplicatePolicy.ImportAgain, Titano.Data.Archiving.AfterImport.DeleteImported), (profile.Duplicates, profile.AfterImport));
// Untouched settings give the brief's card defaults.
Assert.Equal(new Titano.Data.Archiving.CardProfile(), new Titano.App.Infrastructure.AppSettings().ImportProfile(TemplateDefaults.Folder, TemplateDefaults.File));
}
[Test]
public void NewArchivesTakeSettingsArchive()
{
var settings = new Titano.App.Infrastructure.AppSettings { FolderTemplate = "{year}", FileTemplate = "{name}", ProxyLongEdge = 2560, ThumbnailLongEdge = 480 };
var archive = settings.ArchiveDefaults();
Assert.Equal(("{year}", "{name}", 2560, 480), (archive.Templates.Folder, archive.Templates.File, archive.Proxies.LongEdge, archive.Thumbnails.LongEdge));
Assert.Null((new Titano.App.Infrastructure.AppSettings().ArchiveDefaults() with { Name = "Archive" }).Problem());
}
[Test]
public void SettingsSurviveARoundTripWithTheNewSections()
{
var settings = new Titano.App.Infrastructure.AppSettings { ThumbnailLongEdge = 640, ScanIntervalMinutes = 30, NightBrightnessPercent = 3.5, DeepAnalysisAfterScan = true };
var copy = Titano.App.Infrastructure.AppSettings.Parse(settings.ToJson())!;
Assert.Equal((640, 30, 3.5, true), (copy.ThumbnailLongEdge, copy.ScanIntervalMinutes, copy.NightBrightnessPercent, copy.DeepAnalysisAfterScan));
}
[Test]
public void BackgroundPriorityRaisesTheInterfaceOnlyInFront()
{
Assert.Equal(ThreadPriority.AboveNormal, InterfacePriority.For(enabled: true, active: true));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: true, active: false));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
Assert.Equal(("JPEG XL", "CR3", "3FR"), (FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.JpegXl), FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.Cr3),
FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.ThreeFr)));
var heif = Titano.Core.Windows.Codecs.StoreExtension.Get(Titano.Core.Windows.Codecs.StoreExtensionKind.HeifImage);
var format = Titano.Core.Imaging.Decoders.DecoderFactory.DescribeFormats(Titano.Core.Imaging.Decoders.DecoderFactory.CreateClient(null))
.First(f => f.Format.Format == Titano.Core.Imaging.ImageFileFormat.Heif).Format;
var row = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.EmbeddedPreview, "managed", [heif]));
Assert.Equal(("Preview only", "Titano", heif.ProductName), (row.TierText, row.DecoderText, row.NeedsText));
Assert.Equal(Titano.Ui.Controls.StatusKind.Warning, row.TierKind);
Assert.Equal("HEIF: Preview only", row.Announcement);
var missing = new MissingExtensionViewModel(heif, new Titano.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(heif.ProductName + " missing", missing.Text);
var none = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.Unavailable, null, []));
Assert.Equal(("Not supported", "—", "—", false), (none.TierText, none.DecoderText, none.NeedsText, none.HasNeeds));
}
[Test]
public void EnumDrivenKeysExistInEveryRequiredLanguage()
{
@@ -96,6 +96,61 @@ public sealed class SettingsScreenSmokeTests
Assert.True(ServerSession.ForgetRequest(certificate.FullFingerprint).IsDestructive);
});
[Test]
public Task ImportAnalysisAndFormatsAreRealSettings() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var settings = shell.Settings;
// The open archive's own thumbnail size (archive.json) is what Settings › Archive shows.
var archive = Assert.NotNull(await Titano.App.Archiving.CurrentArchive.FindAsync(shell.Services.Database!, shell.Services.Settings.LastArchivePath));
var manifestPath = new Titano.Core.Archiving.ArchivePaths(archive.RootPath).ManifestPath;
var manifest = Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath);
Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, manifest with { ThumbnailPolicy = new Titano.Core.Archiving.ThumbnailPolicy { LongEdge = 240 } });
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
await WaitAsync(() => settings.SelectedThumbnailSize.Value == 240, "the archive's thumbnail size is shown");
await app.ExpectAsync<SettingsView>("settings-archive");
settings.SelectedThumbnailSize = settings.ThumbnailSizes.Single(s => s.Value == 480);
await WaitAsync(() => Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge == 480, "written into archive.json");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
// Import: the defaults of new cards.
settings.Page = SettingsPage.Import;
await app.ExpectAsync<SettingsView>("settings-import");
settings.SessionGap.Text = "90";
Assert.True(settings.SessionGap.Commit());
settings.IsFormatCard = true;
Assert.Equal((90, Titano.Data.Archiving.AfterImport.FormatCard), (shell.Services.Settings.ImportSessionGapMinutes, shell.Services.Settings.ImportAfter));
Assert.True(settings.CanResetSection);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(("45", true), (settings.SessionGap.Text, settings.IsKeepCard));
// Analysis: thresholds in the language's own decimals, checked against their range.
settings.Page = SettingsPage.Analysis;
await app.ExpectAsync<SettingsView>("settings-analysis");
Assert.Equal(6.25.ToString("0.##", System.Globalization.CultureInfo.CurrentCulture), settings.NightBrightness.Text);
settings.NightBrightness.Text = "80";
Assert.True(settings.NightBrightness.HasErrors, "beyond 50 %");
settings.NightBrightness.Revert();
settings.DeepAnalysisAfterScan = true;
Assert.True(shell.Services.Settings.DeepAnalysisAfterScan);
// Formats: the tier of every format and a notice with Install per missing extension.
settings.Page = SettingsPage.Formats;
await WaitAsync(() => settings.Formats.Count > 0 && !settings.IsDetectingFormats, "formats listed");
await app.ExpectAsync<SettingsView>("settings-formats");
Assert.Count(3, settings.MissingExtensions);
var installs = app.FindAll<Button>().Where(b => b.IsVisible && b.Content as string == Loc.L("Settings.Formats.Install")).ToList();
Assert.Count(3, installs);
Assert.True(installs.All(b => AutomationProperties.GetName(b).StartsWith(Loc.L("Settings.Formats.InstallName", string.Empty), StringComparison.Ordinal)), "named after the extension");
Assert.Contains(settings.Formats, f => f.Row.Tier == Titano.Core.Imaging.DecodeTier.Native);
Assert.False(settings.CanResetSection, "Formats only shows this PC");
installs[0].Command.Execute(null);
});
[Test]
public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
@@ -166,6 +221,17 @@ public sealed class SettingsScreenSmokeTests
Assert.Equal(FlowDirection.LeftToRight, main.FlowDirection);
});
/// <summary>Waits (on the UI thread, letting it run) until <paramref name="condition"/> holds.</summary>
private static async Task WaitAsync(Func<bool> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(20);
while (!condition())
{
Assert.True(DateTime.UtcNow < until, what);
await Task.Delay(50);
}
}
private static TextBox Field(ScreenSmokeTests.SampleApp app, string name) =>
app.FindAll<TextBox>().First(t => t.IsVisible && AutomationProperties.GetName(t) == name);
@@ -154,4 +154,29 @@ public sealed class ManifestStoreTests(TestContext context)
Assert.Contains("syncPolicy", File.ReadAllText(path));
Assert.Equal("Studio", ManifestStore.ReadArchive(path).Name);
}
[Test]
public void TheThumbnailSizeIsTheArchivesOwnAndDefaultsTo320()
{
// An archive.json written before the thumbnail policy existed reads with the BRIEF §8.5 default.
var path = Path.Combine(context.CreateTempDirectory(), "archive.json");
File.WriteAllText(path, $$"""
{ "schemaVersion": 1, "id": "{{Guid.CreateVersion7()}}", "name": "Main", "created": "2026-10-02T09:00:00+00:00" }
""");
var read = ManifestStore.ReadArchive(path);
Assert.Equal((320, 80), (read.ThumbnailPolicy.LongEdge, read.ThumbnailPolicy.Quality));
ManifestStore.WriteArchive(path, read with { ThumbnailPolicy = read.ThumbnailPolicy with { LongEdge = 480 } });
Assert.Contains("\"thumbnailPolicy\"", File.ReadAllText(path));
Assert.Equal(480, ManifestStore.ReadArchive(path).ThumbnailPolicy.LongEdge);
File.WriteAllText(path, $$"""
{ "schemaVersion": 1, "id": "{{Guid.CreateVersion7()}}", "name": "Main", "thumbnailPolicy": { "longEdge": 240 } }
""");
Assert.Equal((240, 80), (ManifestStore.ReadArchive(path).ThumbnailPolicy.LongEdge, ManifestStore.ReadArchive(path).ThumbnailPolicy.Quality));
Assert.True(ThumbnailPolicy.IsValidLongEdge(160) && ThumbnailPolicy.IsValidLongEdge(1024));
Assert.False(ThumbnailPolicy.IsValidLongEdge(100) || ThumbnailPolicy.IsValidLongEdge(2048));
Assert.True(ProxyPolicy.IsValidLongEdge(ProxyPolicy.Disabled) && ProxyPolicy.IsValidLongEdge(ProxyPolicy.FullSize) && ProxyPolicy.IsValidLongEdge(1920));
Assert.False(ProxyPolicy.IsValidLongEdge(100) || ProxyPolicy.IsValidLongEdge(10_000));
}
}
@@ -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);
}
}
@@ -252,6 +252,65 @@ public sealed class JobEngineTests(TestContext context)
Assert.Empty((await db.Jobs.ListAsync(null, JobKind.LightAnalyse)).Items);
}
[Test]
public async Task TheNumberOfWorkersChangesWhileTheEngineRuns()
{
await using var db = await OpenAsync();
var running = 0;
var started = 0;
var release = new SemaphoreSlim(0);
var handler = new CallbackHandler(JobKind.Thumbs, async c =>
{
Interlocked.Increment(ref running);
Interlocked.Increment(ref started);
try
{
await release.WaitAsync(c.Cancellation);
}
finally
{
Interlocked.Decrement(ref running);
}
});
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var jobs = new List<Job>();
for (var i = 0; i < 6; i++) jobs.Add(await engine.EnqueueAsync(JobKind.Thumbs, []));
async Task UntilAsync(Func<bool> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(10);
while (!condition())
{
Assert.True(DateTime.UtcNow < until, what);
await Task.Delay(20);
}
}
// One worker: one job at a time.
await UntilAsync(() => Volatile.Read(ref running) == 1, "the first job runs");
await Task.Delay(300);
Assert.Equal(1, Volatile.Read(ref running));
// Three workers: two more jobs start at once, and no fourth.
engine.SetWorkers(3);
Assert.Equal(3, engine.Workers);
await UntilAsync(() => Volatile.Read(ref running) == 3, "three jobs run together");
await Task.Delay(300);
Assert.Equal(3, Volatile.Read(ref running));
// Back to one: the running jobs finish undisturbed, then a single worker carries on.
engine.SetWorkers(1);
release.Release(3);
await UntilAsync(() => Volatile.Read(ref started) == 4 && Volatile.Read(ref running) == 1, "one job after the three");
await Task.Delay(300);
Assert.Equal((4, 1), (Volatile.Read(ref started), Volatile.Read(ref running)));
release.Release(3);
foreach (var job in jobs) await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Throws<ArgumentOutOfRangeException>(() => engine.SetWorkers(0));
}
[Test]
public async Task HandlerFailureMarksJobFailedWithMessage()
{
@@ -82,6 +82,33 @@ public sealed class AnalysisFollowUpTests(TestContext context)
Assert.True(ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
}
[Test]
public async Task AScanAskedForDeepAnalysisQueuesItInTheBackgroundForNewSequencesOnly()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true, deepAnalysis: true));
await fx.WaitForAsync(scan.Id, JobState.Done);
var deep = (await fx.Db.Jobs.ListAsync(null, JobKind.DeepAnalyse, cancellationToken: fx.Ct)).Items.Single();
Assert.Equal(JobPriority.Background, deep.Priority);
Assert.NotNull(await SingleLightJobAsync(fx));
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
var sequence = (await fx.Db.Sequences.GetAsync(done.TargetIds.Single(), fx.Ct))!;
Assert.Equal("Roof", sequence.Folder);
Assert.True(sequence.Status.HasFlag(SequenceStatus.AnalyzedDeep), "analysed in depth");
// A scan that indexes nothing new asks for nothing; a scan without the option never does.
var again = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true, deepAnalysis: true));
await fx.WaitForAsync(again.Id, JobState.Done);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Lake");
var plain = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive));
await fx.WaitForAsync(plain.Id, JobState.Done);
Assert.Count(1, (await fx.Db.Jobs.ListAsync(null, JobKind.DeepAnalyse, cancellationToken: fx.Ct)).Items);
}
[Test]
public async Task ASequenceWaitingForLightAnalysisIsNotQueuedAgain()
{
@@ -112,6 +112,29 @@ public sealed class AnalysisJobTests(TestContext context)
Assert.Contains(Loc.L("Advisor.Log.Presets", string.Empty), done.LogTail);
}
[Test]
public async Task EachDeepAnalysisTakesTheHostsTuningOfThatMoment()
{
// The desktop's Settings › Analysis: the width cap the user sets now applies to the next analysis.
var cap = 40;
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with
{
Tune = basis => basis with { DeepAnalysis = basis.DeepAnalysis with { MinAnalysisLongEdge = 16, MaxAnalysisLongEdge = cap } },
});
var first = await fx.AddAsync(Flickering(10), "A");
var second = await fx.AddAsync(Flickering(10), "B");
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([first.Id]));
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(40, DeepAnalysisReport.Load(fx.Folder(first).AnalysisPath).AnalysisLongEdge);
cap = 32;
job = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([second.Id]));
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(32, DeepAnalysisReport.Load(fx.Folder(second).AnalysisPath).AnalysisLongEdge);
}
[Test]
public async Task ASequenceThatFailsDoesNotStopTheOthersAndARetryRedoesOnlyIt()
{
@@ -0,0 +1,173 @@
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");
}
}
@@ -129,4 +129,39 @@ public sealed class AdminTests(TestContext context)
using var stats = await admin.GetAsync("/api/v1/archive/stats");
await stats.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task ArchiveSettingsAreWrittenToArchiveJsonAndSurviveARestart()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
var changed = archive with { Name = "Studio", FolderTemplate = "{year}/{camera}", FileTemplate = "{name}", ProxyLongEdge = -1 };
using (var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed, ProtocolJson.Default.ArchiveSettingsDto))
await put.ExpectAsync(HttpStatusCode.OK);
// archive.json is the truth (BRIEF §7): the proxy jobs read it, and the next start registers the archive from it.
var manifest = Titano.Core.Archiving.ManifestStore.ReadArchive(new Titano.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath);
Assert.Equal(("Studio", "{year}/{camera}", "{name}", -1), (manifest.Name, manifest.LayoutTemplates.Folder, manifest.LayoutTemplates.File, manifest.ProxyPolicy.LongEdge));
var restarted = await Titano.Server.Storage.ServerArchive.OpenAsync(server.Database, server.Options, context.Cancellation);
Assert.Equal(("Studio", "{name}", -1), (restarted.Current.Name, restarted.Current.FileTemplate, restarted.Current.ProxyLongEdge));
using var again = await admin.GetAsync("/api/v1/archive/settings");
Assert.Equal(changed, await again.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto));
// The archive drive is gone: nothing is written and the admin hears why.
var path = new Titano.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath;
File.Move(path, path + ".away");
try
{
using var offline = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await offline.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
}
finally
{
File.Move(path + ".away", path);
}
Assert.Equal(-1, Titano.Core.Archiving.ManifestStore.ReadArchive(path).ProxyPolicy.LongEdge);
}
}
@@ -42,6 +42,25 @@ public sealed class ArchiveModuleTests(TestContext context)
}
}
[Test]
public async Task AServerOnSqliteBacksUpItsIndexOnStart()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var backups = Path.Combine(server.Options.DataPath, "backups");
// No copy yet, so the first one is made at once (BRIEF §6.2), named after the index it copies.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (!Directory.Exists(backups) || Directory.GetFiles(backups, "*.db").Length == 0)
{
Assert.True(DateTime.UtcNow < until, "no backup of the index");
await Task.Delay(50);
}
var path = Assert.NotNull(((Titano.Data.Sqlite.SqliteDatabase)server.Database.Database).Path);
var backup = Titano.Data.DatabaseBackups.List(backups, path).Single();
var summary = await Titano.Data.DatabaseBackups.SummarizeBackupAsync(backup.Path, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(server.Database.SchemaVersion, summary.SchemaVersion);
}
private static byte[] Photo()
{
const int width = 96, height = 64;