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:
91 files changed
+2864
-357
No files matched your search
@@ -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>
|
||||
|
||||
@@ -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:<folder></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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Data.Sqlite;
|
||||
|
||||
namespace Titano.Data;
|
||||
|
||||
/// <summary>A copy of the SQLite index made by <see cref="TitanoDatabase.BackupAsync"/>: its file, when it was made and its size.</summary>
|
||||
public sealed record DatabaseBackup(string Path, DateTimeOffset Created, long Bytes);
|
||||
|
||||
/// <summary>What an index holds, shown before a restore replaces one with another.</summary>
|
||||
public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequences, long Photos);
|
||||
|
||||
/// <summary>
|
||||
/// Backups of the SQLite index (BRIEF §6.2): a <c>VACUUM INTO</c> copy made once a day while the host runs (at start
|
||||
/// when the newest copy is a day old, then checked every hour), the three newest kept; and their restore from
|
||||
/// Settings › Advanced. A restore never swaps the file under a running host: the chosen copy is staged next to the
|
||||
/// index and replaces it the next time the host opens it, before anything reads it and after a fresh copy of the index
|
||||
/// it replaces.
|
||||
/// </summary>
|
||||
public static partial class DatabaseBackups
|
||||
{
|
||||
/// <summary>Copies kept (BRIEF §6.2: ×3).</summary>
|
||||
public const int Keep = 3;
|
||||
|
||||
/// <summary>Age of the newest copy from which the next one is due.</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromDays(1);
|
||||
|
||||
/// <summary>How often a running host checks whether a copy is due.</summary>
|
||||
public static readonly TimeSpan CheckInterval = TimeSpan.FromHours(1);
|
||||
|
||||
/// <summary>
|
||||
/// The copies of the index at <paramref name="databasePath"/> in <paramref name="directory"/>, newest first. Their
|
||||
/// names are <c><index name>-yyyyMMdd-HHmmss-fff.db</c> in UTC, as <see cref="SqliteDatabase.BackupAsync"/> writes them.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<DatabaseBackup> List(string directory, string databasePath)
|
||||
{
|
||||
if (!Directory.Exists(directory)) return [];
|
||||
var stem = Path.GetFileNameWithoutExtension(databasePath);
|
||||
var backups = new List<DatabaseBackup>();
|
||||
foreach (var file in Directory.EnumerateFiles(directory, stem + "-*.db"))
|
||||
{
|
||||
var match = Stamp().Match(Path.GetFileName(file));
|
||||
if (!match.Success || !string.Equals(match.Groups["stem"].Value, stem, StringComparison.Ordinal)) continue;
|
||||
if (!DateTime.TryParseExact(match.Groups["at"].Value, "yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var at)) continue;
|
||||
try
|
||||
{
|
||||
backups.Add(new DatabaseBackup(file, new DateTimeOffset(at, TimeSpan.Zero), new FileInfo(file).Length));
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Deleted while listing (pruned by another copy).
|
||||
}
|
||||
}
|
||||
backups.Sort((a, b) => b.Created.CompareTo(a.Created));
|
||||
return backups;
|
||||
}
|
||||
|
||||
/// <summary>True when there is no copy yet or the newest one is at least <see cref="Interval"/> old.</summary>
|
||||
public static bool IsDue(IReadOnlyList<DatabaseBackup> backups, DateTimeOffset now) => backups.Count == 0 || now - backups[0].Created >= Interval;
|
||||
|
||||
/// <summary>
|
||||
/// Makes the daily copy of a SQLite index into <paramref name="directory"/> until <paramref name="cancellationToken"/>
|
||||
/// is cancelled: now when one is due, then whenever an hourly check finds one due. A failed copy is logged and tried
|
||||
/// again at the next check. Returns at once for PostgreSQL, which its own server tools back up.
|
||||
/// </summary>
|
||||
public static async Task RunDailyAsync(TitanoDatabase db, string directory, TimeProvider? time = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (db.Database is not SqliteDatabase { Path: { } path }) return;
|
||||
var clock = time ?? TimeProvider.System;
|
||||
using var timer = new PeriodicTimer(CheckInterval, clock);
|
||||
try
|
||||
{
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
if (IsDue(List(directory, path), clock.GetUtcNow())) await db.BackupAsync(directory, Keep, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("backup", $"The daily index backup into {directory} failed; it is tried again within the hour", ex);
|
||||
}
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Counts what the index holds (the current one, for the restore's comparison).</summary>
|
||||
public static async Task<DatabaseSummary> SummarizeAsync(TitanoDatabase db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var archives = await session.ScalarAsync<long>("SELECT count(*) FROM archives", [], cancellationToken).ConfigureAwait(false);
|
||||
var totals = await session.QuerySingleAsync("SELECT count(*), COALESCE(SUM(frame_count), 0) FROM sequences", [], cancellationToken).ConfigureAwait(false);
|
||||
return new DatabaseSummary(db.SchemaVersion, (int)archives, (int)totals.GetInt64(0), totals.GetInt64(1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The restore's dry run: what <paramref name="backupPath"/> holds, read from a scratch copy in
|
||||
/// <paramref name="scratchDirectory"/> (opened and migrated there, so the backup itself is never written).
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The file is not a readable Titano index.</exception>
|
||||
public static async Task<DatabaseSummary> SummarizeBackupAsync(string backupPath, string scratchDirectory, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var folder = Path.Combine(scratchDirectory, "restore-check-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(folder);
|
||||
try
|
||||
{
|
||||
var copy = Path.Combine(folder, "titano.db");
|
||||
File.Copy(backupPath, copy);
|
||||
try
|
||||
{
|
||||
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(copy), cancellationToken).ConfigureAwait(false);
|
||||
return await SummarizeAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
|
||||
{
|
||||
throw new InvalidDataException("The backup is not a Titano index this build can open.", ex);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Log.Warning("backup", $"The scratch copy in {folder} was not removed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where a staged restore waits for the next start: next to the index, where pruning backups never reaches.</summary>
|
||||
public static string StagedPath(string databasePath) => databasePath + ".restore";
|
||||
|
||||
public static bool HasStagedRestore(string databasePath) => File.Exists(StagedPath(databasePath));
|
||||
|
||||
/// <summary>Copies <paramref name="backupPath"/> beside the index (atomically) to replace it at the next start.</summary>
|
||||
public static async Task StageRestoreAsync(string backupPath, string databasePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var staged = StagedPath(databasePath);
|
||||
var temp = AtomicFile.TempPathFor(staged);
|
||||
try
|
||||
{
|
||||
await using (var source = new FileStream(backupPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous))
|
||||
await using (var target = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous))
|
||||
{
|
||||
await source.CopyToAsync(target, cancellationToken).ConfigureAwait(false);
|
||||
target.Flush(flushToDisk: true);
|
||||
}
|
||||
AtomicFile.Commit(temp, staged);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temp)) File.Delete(temp);
|
||||
}
|
||||
Log.Info("backup", $"Restore of {backupPath} staged for the next start");
|
||||
}
|
||||
|
||||
/// <summary>Drops a staged restore (the user changed their mind, or its preparation failed).</summary>
|
||||
public static void CancelStagedRestore(string databasePath) => File.Delete(StagedPath(databasePath));
|
||||
|
||||
/// <summary>
|
||||
/// Carries out a staged restore on the index the host has just opened, before anything else uses it: the staged copy
|
||||
/// is checked (it opens in a scratch copy and passes <c>quick_check</c>), the index as it is now is copied into
|
||||
/// <paramref name="backupDirectory"/>, and only then is it replaced by the staged copy, migrated to this build's
|
||||
/// schema. False when none was staged.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The staged copy failed its checks; it is set aside as <c>.failed</c> and the index is unchanged.</exception>
|
||||
/// <exception cref="IOException">The index could not be backed up or replaced (also <see cref="UnauthorizedAccessException"/>,
|
||||
/// <see cref="DatabaseException"/>): it is unchanged and the restore stays staged for the next start.</exception>
|
||||
public static async Task<bool> RestoreStagedAsync(TitanoDatabase db, string backupDirectory, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (db.Database is not SqliteDatabase { Path: { } path }) return false;
|
||||
var staged = StagedPath(path);
|
||||
if (!File.Exists(staged)) return false;
|
||||
try
|
||||
{
|
||||
// A copy this build cannot open (damaged, or made by a newer Titano) must never replace a working index.
|
||||
await SummarizeBackupAsync(staged, Path.GetDirectoryName(path) ?? ".", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
File.Move(staged, staged + ".failed", overwrite: true);
|
||||
throw;
|
||||
}
|
||||
// What the index holds up to this start stays recoverable: no restore without a fresh copy first.
|
||||
var before = await db.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
|
||||
await db.RestoreAsync(staged, cancellationToken).ConfigureAwait(false);
|
||||
File.Delete(staged);
|
||||
Log.Info("backup", $"Index restored from the staged copy; the index it replaced is {before}");
|
||||
return true;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^(?<stem>.+)-(?<at>\d{8}-\d{6}-\d{3})\.db$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Stamp();
|
||||
}
|
||||
@@ -29,7 +29,8 @@ public sealed record JobEngineOptions
|
||||
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
|
||||
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
|
||||
/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an <see cref="ISelectiveJobHandler"/>
|
||||
/// declines stay queued for other claimers.
|
||||
/// declines stay queued for other claimers. The number of workers can change while the engine runs
|
||||
/// (<see cref="SetWorkers"/>, Settings › Rendering › Parallelism on the desktop).
|
||||
/// </summary>
|
||||
public sealed class JobEngine : IAsyncDisposable
|
||||
{
|
||||
@@ -48,16 +49,30 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly List<Task> _workers = [];
|
||||
private readonly Lock _workerGate = new();
|
||||
private readonly HashSet<int> _activeWorkers = [];
|
||||
private int _workerTarget;
|
||||
private bool _workersStarted;
|
||||
|
||||
public JobEngine(TitanoDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
|
||||
{
|
||||
_db = db;
|
||||
Options = options ?? new JobEngineOptions();
|
||||
_handlers = handlers.ToDictionary(h => h.Kind);
|
||||
_workerTarget = Options.Workers;
|
||||
}
|
||||
|
||||
public JobEngineOptions Options { get; }
|
||||
|
||||
/// <summary>Workers that claim jobs: <see cref="JobEngineOptions.Workers"/> until <see cref="SetWorkers"/> changes it.</summary>
|
||||
public int Workers
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_workerGate) return _workerTarget;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
@@ -81,13 +96,33 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
Log.Info("jobs", "No job handlers; this engine claims nothing");
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < Options.Workers; i++)
|
||||
lock (_workerGate)
|
||||
{
|
||||
var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}";
|
||||
_workers.Add(Task.Run(() => WorkerLoopAsync(id, _shutdown.Token), CancellationToken.None));
|
||||
_workersStarted = true;
|
||||
for (var i = 0; i < _workerTarget; i++) StartWorker(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the number of workers. More start claiming at once; the surplus ones finish the job they are running
|
||||
/// (never interrupted) and then stop. Before <see cref="StartAsync"/> it only sets how many start.
|
||||
/// </summary>
|
||||
public void SetWorkers(int count)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
|
||||
lock (_workerGate)
|
||||
{
|
||||
if (_workerTarget == count) return;
|
||||
_workerTarget = count;
|
||||
if (_workersStarted)
|
||||
{
|
||||
for (var i = 0; i < count; i++) StartWorker(i);
|
||||
}
|
||||
}
|
||||
Log.Info("jobs", $"Job engine set to {count} worker(s)");
|
||||
Wake();
|
||||
}
|
||||
|
||||
/// <summary>Queues a job and wakes a worker.</summary>
|
||||
public async Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
|
||||
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default)
|
||||
@@ -129,10 +164,17 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task[] workers;
|
||||
lock (_workerGate)
|
||||
{
|
||||
// No worker starts any more: the shutdown token is about to be disposed.
|
||||
_workersStarted = false;
|
||||
workers = [.. _workers];
|
||||
}
|
||||
await _shutdown.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(_workers).ConfigureAwait(false);
|
||||
await Task.WhenAll(workers).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -181,11 +223,34 @@ public sealed class JobEngine : IAsyncDisposable
|
||||
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
|
||||
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
|
||||
/// <summary>Starts worker <paramref name="index"/> unless it runs already; call under <see cref="_workerGate"/>.</summary>
|
||||
private void StartWorker(int index)
|
||||
{
|
||||
if (!_activeWorkers.Add(index)) return;
|
||||
// A single worker keeps the plain id (as before workers could be added); numbered ones get "#n".
|
||||
var id = index == 0 && Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{index}";
|
||||
var shutdown = _shutdown.Token;
|
||||
_workers.Add(Task.Run(() => WorkerLoopAsync(index, id, shutdown), CancellationToken.None));
|
||||
}
|
||||
|
||||
/// <summary>True when worker <paramref name="index"/> is beyond the wanted count; it is then no longer active.</summary>
|
||||
private bool Retires(int index)
|
||||
{
|
||||
lock (_workerGate)
|
||||
{
|
||||
if (index < _workerTarget) return false;
|
||||
_activeWorkers.Remove(index);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Claims and runs jobs until shutdown, or until <see cref="SetWorkers"/> no longer wants this worker.
|
||||
/// Nothing a job or a handler throws ends the worker.</summary>
|
||||
private async Task WorkerLoopAsync(int index, string workerId, CancellationToken shutdown)
|
||||
{
|
||||
while (!shutdown.IsCancellationRequested)
|
||||
{
|
||||
if (Retires(index)) return;
|
||||
Job? job;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -6,9 +6,10 @@ namespace Titano.Data.Processing;
|
||||
|
||||
/// <summary>
|
||||
/// Light analysis queued after work that brings sequences or frames into the index (card import, adoption, scan), so the
|
||||
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3). Nothing is queued
|
||||
/// when the engine cannot run light analysis, and a sequence already waiting in a queued light analysis is not queued
|
||||
/// again (that job runs after the changes that led here).
|
||||
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3); a background deep
|
||||
/// analysis too when the host asks for it. Nothing is queued when the engine cannot run the analysis, and a sequence
|
||||
/// already waiting in a queued analysis of the same kind is not queued again (that job runs after the changes that led
|
||||
/// here).
|
||||
/// </summary>
|
||||
internal static class AnalysisFollowUp
|
||||
{
|
||||
@@ -24,6 +25,21 @@ internal static class AnalysisFollowUp
|
||||
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one background deep analysis of <paramref name="sequenceIds"/> (BRIEF §10.2: background, low priority),
|
||||
/// leaving out the sequences a queued deep analysis already covers.
|
||||
/// </summary>
|
||||
public static async Task QueueDeepAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection<Guid> sequenceIds)
|
||||
{
|
||||
if (sequenceIds.Count == 0) return;
|
||||
var waiting = (await db.Jobs.ListQueuedAsync([JobKind.DeepAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
|
||||
.SelectMany(j => j.TargetIds).ToHashSet();
|
||||
var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
|
||||
if (targets.Count == 0) return;
|
||||
var request = ProcessingJobs.DeepAnalysis(targets, context.Job.TargetLabel) with { Priority = JobPriority.Background };
|
||||
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Sequences of <paramref name="archiveId"/> without a current light analysis (new, adopted, or with frames a scan added).</summary>
|
||||
public static async Task<List<Guid>> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -62,6 +62,17 @@ public sealed record ProcessingOptions
|
||||
|
||||
public RenderOptions Render { get; init; } = RenderOptions.Default;
|
||||
|
||||
/// <summary>
|
||||
/// The host's current tuning, asked at the start of every analysis and render: it returns these options with the
|
||||
/// values the user may change at any time (on the desktop Settings › Rendering and Analysis: memory budget, quality
|
||||
/// profile, parallelism, analysis width and thresholds), so a change applies to the next job. Null: these options as
|
||||
/// they are.
|
||||
/// </summary>
|
||||
public Func<ProcessingOptions, ProcessingOptions>? Tune { get; init; }
|
||||
|
||||
/// <summary>These options with the host's current tuning (<see cref="Tune"/>).</summary>
|
||||
internal ProcessingOptions Current => Tune?.Invoke(this) ?? this;
|
||||
|
||||
/// <summary>Tells <see cref="SequenceChanged"/>; a failure is logged, never passed on to the job.</summary>
|
||||
internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -104,10 +104,13 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
|
||||
IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var file = new DeepAnalysisCheckpointFile(Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName));
|
||||
// The host's analysis parameters as they are now (Settings › Analysis on the desktop). Those that change per-frame
|
||||
// results are part of the checkpoint's fingerprint, so a partial run made with other values starts again.
|
||||
var analysis = options.Current.DeepAnalysis;
|
||||
DeepAnalysisReport report;
|
||||
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder))
|
||||
{
|
||||
report = await DeepAnalyzer.AnalyzeAsync(source, options.DeepAnalysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
|
||||
report = await DeepAnalyzer.AnalyzeAsync(source, analysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
report.Save(folder.AnalysisPath);
|
||||
|
||||
@@ -32,6 +32,8 @@ internal sealed class SequenceRender : IAsyncDisposable
|
||||
/// <param name="analysis">The sequence's deep report, when current: its luminance spares the preparation a decode pass.</param>
|
||||
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options)
|
||||
{
|
||||
// The host's tuning as it is now (memory budget, quality profile): a change applies from the next render.
|
||||
options = options.Current;
|
||||
var metadata = frames.LightFrames();
|
||||
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
|
||||
_processing = options;
|
||||
|
||||
@@ -115,12 +115,43 @@ public sealed class TitanoDatabase : TitanoRepositories, IAsyncDisposable
|
||||
SchemaVersion = await MigrationRunner.MigrateAsync(Database, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQLite only: the size of the database file and the bytes its free pages hold, which <see cref="VacuumAsync"/> gives
|
||||
/// back; null on PostgreSQL, whose autovacuum keeps the tables compact by itself.
|
||||
/// </summary>
|
||||
public async Task<IndexSpace?> SpaceAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Dialect != Dialect.Sqlite) return null;
|
||||
await using var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var pageSize = await session.ScalarAsync<long>("PRAGMA page_size", [], cancellationToken).ConfigureAwait(false);
|
||||
var pages = await session.ScalarAsync<long>("PRAGMA page_count", [], cancellationToken).ConfigureAwait(false);
|
||||
var free = await session.ScalarAsync<long>("PRAGMA freelist_count", [], cancellationToken).ConfigureAwait(false);
|
||||
return new IndexSpace(pages * pageSize, free * pageSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQLite only: rewrites the database without its free pages (<c>VACUUM</c>, BRIEF §12.5 Maintenance). Writers wait
|
||||
/// meanwhile; readers continue on the previous snapshot. Returns the space before and after.
|
||||
/// </summary>
|
||||
public async Task<(IndexSpace Before, IndexSpace After)> VacuumAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
AsSqlite();
|
||||
var before = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
|
||||
await using (var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false))
|
||||
await session.ExecuteScriptAsync("VACUUM", cancellationToken).ConfigureAwait(false);
|
||||
var after = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
|
||||
return (before, after);
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Database.DisposeAsync();
|
||||
|
||||
private SqliteDatabase AsSqlite() =>
|
||||
Database as SqliteDatabase ?? throw new NotSupportedException("Backups of a PostgreSQL database are made with the server's own tools.");
|
||||
}
|
||||
|
||||
/// <summary>Size of an SQLite index file and the bytes of its free pages (reclaimable by a vacuum).</summary>
|
||||
public sealed record IndexSpace(long FileBytes, long ReclaimableBytes);
|
||||
|
||||
/// <summary>Repositories bound to one open transaction.</summary>
|
||||
public sealed class TitanoTransaction : TitanoRepositories, IAsyncDisposable
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user