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

+2 -1
View File
@@ -39,6 +39,7 @@ public sealed class ArchiveImages
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
int built = 0, reused = 0, undecodable = 0;
@@ -58,7 +59,7 @@ public sealed class ArchiveImages
reused++;
continue;
}
if (Render(() => _renderer.Thumbnail(folder, frame, cancellationToken)) is { } image)
if (Render(() => _renderer.Thumbnail(folder, frame, policy, cancellationToken)) is { } image)
{
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
built++;
@@ -19,6 +19,9 @@ public sealed record OrphanReport(IReadOnlyList<SequenceOrphans> Sequences, IRea
}
/// <summary>What a maintenance run removed or changed (or would, in a dry run).</summary>
/// <param name="IndexReclaimable">Bytes of free pages in the SQLite index before the run; null on PostgreSQL (autovacuum) or
/// when a resumed run had passed that step.</param>
/// <param name="IndexReclaimed">Bytes the index vacuum gave back; 0 in a dry run or when too little was free to rewrite the file.</param>
public sealed record MaintenanceReport(
bool DryRun,
IReadOnlyList<string> StaleLeases,
@@ -27,7 +30,9 @@ public sealed record MaintenanceReport(
int DuplicateGroups,
int DuplicateFlagChanges,
int UnindexedFiles,
int MissingFiles);
int MissingFiles,
long? IndexReclaimable = null,
long IndexReclaimed = 0);
/// <summary>Duplicates, orphans and housekeeping of an archive (BRIEF §12.5). Originals are never touched.</summary>
public sealed class ArchiveMaintenance
@@ -41,6 +46,10 @@ public sealed class ArchiveMaintenance
/// <summary>Packs with more reclaimable bytes than this share are compacted.</summary>
private const double CompactionRatio = 0.3;
/// <summary>The SQLite index is vacuumed when at least this share of it is free pages: rewriting a large index for a
/// few pages would hold its writers for nothing.</summary>
internal const double IndexVacuumRatio = 0.1;
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
@@ -99,10 +108,10 @@ public sealed class ArchiveMaintenance
}
/// <summary>Number of maintenance steps (the job checkpoints after each).</summary>
internal const int StepCount = 4;
internal const int StepCount = 5;
/// <summary>Runs the maintenance steps from <paramref name="firstStep"/>: stale leases, leftover temporary files,
/// thumbnail pack compaction, duplicate flags. A dry run only reports.</summary>
/// thumbnail pack compaction, duplicate flags, index vacuum (SQLite). A dry run only reports.</summary>
public async Task<MaintenanceReport> RunAsync(Archive archive, bool dryRun, int firstStep, Func<int, ValueTask> stepDone,
CancellationToken cancellationToken = default)
{
@@ -111,6 +120,8 @@ public sealed class ArchiveMaintenance
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
IReadOnlyList<string> leases = [], temps = [], packs = [];
int groups = 0, flagChanges = 0;
long? reclaimable = null;
long reclaimed = 0;
for (var step = firstStep; step < StepCount; step++)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -128,11 +139,27 @@ public sealed class ArchiveMaintenance
case 3:
(groups, flagChanges) = await FlagDuplicatesAsync(archive, paths, dryRun, cancellationToken).ConfigureAwait(false);
break;
case 4:
(reclaimable, reclaimed) = await VacuumIndexAsync(dryRun, cancellationToken).ConfigureAwait(false);
break;
}
await stepDone(step + 1).ConfigureAwait(false);
}
var orphans = await FindOrphansAsync(archive, cancellationToken).ConfigureAwait(false);
return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles);
return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles, reclaimable, reclaimed);
}
/// <summary>
/// The SQLite index's free pages, given back by a vacuum when they are at least <see cref="IndexVacuumRatio"/> of the
/// file (BRIEF §12.5 "SQLite vacuum"); nothing on PostgreSQL, whose autovacuum does it.
/// </summary>
private async Task<(long? Reclaimable, long Reclaimed)> VacuumIndexAsync(bool dryRun, CancellationToken cancellationToken)
{
if (await _db.SpaceAsync(cancellationToken).ConfigureAwait(false) is not { } space) return (null, 0);
if (dryRun || space.ReclaimableBytes == 0 || space.ReclaimableBytes < space.FileBytes * IndexVacuumRatio) return (space.ReclaimableBytes, 0);
var (before, after) = await _db.VacuumAsync(cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"Index vacuumed: {before.FileBytes} → {after.FileBytes} bytes");
return (space.ReclaimableBytes, long.Max(0, before.FileBytes - after.FileBytes));
}
/// <summary>Staging copies and atomic-write temporaries left behind by crashes (never originals).</summary>
+118 -9
View File
@@ -3,6 +3,7 @@ using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
@@ -10,12 +11,15 @@ namespace Titano.Data.Archiving;
/// <summary>
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and
/// restore them, query duplicates and orphans, and
/// or adopt an archive, read and change its settings, plan and apply mass renames, plan imports and card erases, delete
/// sequences into the trash and restore them, query duplicates and orphans, and
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
/// </summary>
public sealed class ArchiveService : IJobHandlerProvider
{
/// <summary>Lease serialising read-modify-write of <c>archive.json</c> between the processes sharing an archive.</summary>
private const string SettingsLease = "archive-settings";
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
@@ -61,19 +65,33 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
public async Task<Archive> CreateAsync(string root, string name, LayoutTemplates? templates = null, ProxyPolicy? proxies = null,
CancellationToken cancellationToken = default)
public Task<Archive> CreateAsync(string root, string name, LayoutTemplates? templates = null, ProxyPolicy? proxies = null,
CancellationToken cancellationToken = default) =>
CreateAsync(root, new ArchiveSettings(name, templates ?? new LayoutTemplates(), proxies ?? new ProxyPolicy(), new ThumbnailPolicy()), cancellationToken);
/// <summary>
/// Makes <paramref name="root"/> a new, empty archive with <paramref name="settings"/> and indexes it. A blank name
/// becomes the folder's name; a longer one than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
/// </summary>
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
/// <exception cref="ArgumentException">A template or policy is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
public async Task<Archive> CreateAsync(string root, ArchiveSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
var paths = new ArchivePaths(root);
var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
settings = settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Titano archive.");
Directory.CreateDirectory(paths.MetaDirectory);
var manifest = new ArchiveManifest
{
Id = Guid.CreateVersion7(),
Name = name,
Name = settings.Name.Trim(),
Created = DateTimeOffset.UtcNow,
LayoutTemplates = templates ?? new LayoutTemplates(),
ProxyPolicy = proxies ?? new ProxyPolicy(),
LayoutTemplates = settings.Templates,
ProxyPolicy = settings.Proxies,
ThumbnailPolicy = settings.Thumbnails,
};
ManifestStore.WriteArchive(paths.ManifestPath, manifest);
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
@@ -112,6 +130,73 @@ public sealed class ArchiveService : IJobHandlerProvider
: CreateAsync(root, name ?? Path.GetFileName(paths.Root), null, null, cancellationToken);
}
/// <summary>
/// <see cref="AdoptAsync(string, string?, CancellationToken)"/> for a folder that may become a new archive with
/// <paramref name="defaults"/> (templates and policies; the folder's name when its name is blank). An existing
/// archive keeps its own settings.
/// </summary>
public Task<Archive> AdoptAsync(string root, ArchiveSettings defaults, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(defaults);
return File.Exists(new ArchivePaths(root).ManifestPath) ? OpenAsync(root, cancellationToken) : CreateAsync(root, defaults, cancellationToken);
}
/// <summary>
/// The settings in the archive's <c>archive.json</c>; those of the index (with the default thumbnail policy, which only
/// the file keeps) while the file cannot be read.
/// </summary>
public async Task<ArchiveSettings> GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
try
{
if (File.Exists(paths.ManifestPath)) return ArchiveSettings.Of(ManifestStore.ReadArchive(paths.ManifestPath));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
}
/// <summary>
/// Changes an archive's settings in its <c>archive.json</c> (the source of truth, BRIEF §7), then in the index.
/// <paramref name="edit"/> receives the settings read from the file under the archive's settings lease, so a server and
/// a client sharing the archive never undo each other's change; the file is replaced atomically. Folders and files
/// already in the archive keep their names: templates and policies apply to the next imports, proxies and thumbnails.
/// </summary>
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another process kept the archive's settings busy.</exception>
public async Task<Archive> UpdateSettingsAsync(Guid archiveId, Func<ArchiveSettings, ArchiveSettings> edit, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(edit);
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
ArchiveManifest manifest;
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SettingsLease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
cancellationToken).ConfigureAwait(false))
{
var current = ManifestStore.ReadArchive(paths.ManifestPath);
if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}.");
var settings = edit(ArchiveSettings.Of(current));
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
manifest = current with
{
Name = settings.Name.Trim(),
LayoutTemplates = settings.Templates,
ProxyPolicy = settings.Proxies,
ThumbnailPolicy = settings.Thumbnails,
};
if (manifest != current) ManifestStore.WriteArchive(paths.ManifestPath, manifest);
}
Log.Info("archive", $"Settings of {paths.Root}: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}, thumbnails {manifest.ThumbnailPolicy.LongEdge}");
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
}
public static ArchiveAvailability GetAvailability(Archive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.RootPath));
/// <summary>Changes title, tags, rating and notes in the sidecar and the index together (settings version + 1).</summary>
@@ -242,11 +327,35 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
/// <summary>
/// The settings an archive keeps in <c>archive.json</c> (BRIEF §7, §8.5): its name, the naming templates of new imports
/// and the policies of the proxies and thumbnails built from now on.
/// </summary>
public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, ProxyPolicy Proxies, ThumbnailPolicy Thumbnails)
{
public const int MaxNameLength = 100;
public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy);
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary>
public string? Problem()
{
if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name";
if (string.IsNullOrWhiteSpace(Templates.Folder) || !PathTemplate.Parse(Templates.Folder).IsValid) return "folderTemplate";
if (string.IsNullOrWhiteSpace(Templates.File) || !PathTemplate.Parse(Templates.File).IsValid) return "fileTemplate";
if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge";
if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge";
return null;
}
}
/// <summary>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
public static class ArchiveJobs
{
public static ArchiveJobRequest Scan(Archive archive, bool full = false) =>
new(JobKind.Scan, [archive.Id], archive.Name, Json(new ScanParameters(full), ArchiveJobJson.Default.ScanParameters), JobPriority.User);
/// <param name="deepAnalysis">Also queue a background deep analysis of the sequences the scan indexes (see <see cref="ScanParameters"/>).</param>
public static ArchiveJobRequest Scan(Archive archive, bool full = false, bool deepAnalysis = false) =>
new(JobKind.Scan, [archive.Id], archive.Name, Json(new ScanParameters(full, deepAnalysis), ArchiveJobJson.Default.ScanParameters), JobPriority.User);
public static ArchiveJobRequest Rebuild(Archive archive) => new(JobKind.Rebuild, [archive.Id], archive.Name, null, JobPriority.User);
@@ -6,7 +6,9 @@ using Titano.Core.Model;
namespace Titano.Data.Archiving.Jobs;
/// <summary><see cref="JobKind.Scan"/>: target = the archive.</summary>
public sealed record ScanParameters(bool Full);
/// <param name="DeepAnalysis">The sequences the scan brings into the index (or whose frames it changes) also get a deep
/// analysis in the background, after their light one (Settings › Analysis on the desktop).</param>
public sealed record ScanParameters(bool Full, bool DeepAnalysis = false);
/// <summary><see cref="JobKind.Verify"/>: target = the archive; null sequences = all of them.</summary>
public sealed record VerifyParameters(IReadOnlyList<Guid>? SequenceIds);
@@ -7,7 +7,8 @@ namespace Titano.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Maintenance"/>: stale leases, leftover temporary files, thumbnail pack compaction, duplicate
/// flags, then an orphan count. Checkpoint: the number of steps done.
/// flags, the SQLite index vacuum (its reclaimable size in a dry run), then an orphan count. Checkpoint: the number of
/// steps done.
/// </summary>
internal sealed class MaintenanceJobHandler(TitanoDatabase db, ArchiveMaintenance maintenance) : IJobHandler
{
@@ -24,6 +25,11 @@ internal sealed class MaintenanceJobHandler(TitanoDatabase db, ArchiveMaintenanc
if (dryRun) context.Log(Loc.L("Archive.Log.DryRun"));
context.Log(Loc.L("Archive.Log.MaintenanceDone", report.StaleLeases.Count, report.TemporaryFiles.Count, report.CompactedPacks.Count,
report.DuplicateFlagChanges));
if (report.IndexReclaimed > 0) context.Log(Loc.L("Archive.Log.IndexVacuumed", Megabytes(report.IndexReclaimed)));
else if (report.IndexReclaimable is { } reclaimable) context.Log(Loc.L("Archive.Log.IndexReclaimable", Megabytes(reclaimable)));
context.Log(Loc.L("Archive.Log.Orphans", report.UnindexedFiles, report.MissingFiles));
}
/// <summary>"12.4 MB" in the language of the log.</summary>
private static string Megabytes(long bytes) => Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0.#", Loc.Culture));
}
@@ -18,7 +18,7 @@ internal static class JobArchive
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it.
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks.
/// </summary>
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind) : IJobHandler
{
@@ -29,9 +29,8 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild
: ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false)).Full ? ScanMode.Full
: ScanMode.Incremental;
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false));
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild : parameters.Full ? ScanMode.Full : ScanMode.Incremental;
var resume = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) ? checkpoint[Prefix.Length..] : null;
var summary = await indexer.ScanAsync(archive, mode, resume, async p =>
{
@@ -42,7 +41,10 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
// A resumed scan may have indexed its folders before the interruption.
if (summary.Indexed > 0 || resume is not null)
await AnalysisFollowUp.QueueAsync(db, context, await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
.ConfigureAwait(false);
{
var unanalysed = await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false);
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
}
}
}