fix(settings): restore before the index opens; archive rows edit only their archive; parallelism follows the brief

Index restore (ENG-06, UI-09):
- A staged restore now runs on the files before the index is opened, so it also
  recovers an index that no longer opens; Settings > Advanced > Restore works
  without an open index (the current one is shown as unreadable).
- The staged copy passes PRAGMA quick_check (before migration, in a scratch copy)
  ahead of any backup: a damaged copy is set aside as .failed and never renews the
  daily copies. The index it replaces is kept as a VACUUM INTO copy, or, when it
  cannot be read, copied whole with its WAL as titano-replaced-<stamp>.db outside the
  rotation. The staged file is renamed over the index, so it is never applied twice.
- Archive > Maintenance gains Restore database..., which opens Settings > Advanced.

Archive settings (UI-03, ENG-03):
- An archive.json with an empty or overlong name (drive roots) can be edited again:
  the name read is made usable as at creation.
- Proxy and thumbnail sizes outside the presets (an admin's 3840) are listed and
  shown with their number.
- Changing the archive folder retargets the rows: an archive there is registered
  and rescanned; with none, the rows edit only the defaults of new archives. The
  rows never fall back to another archive of the index.
- Reset all and Import settings no longer rewrite the shared archive.json; Archive >
  Reset section asks first, naming the archive.
- PUT /api/v1/archive/settings: 409 archive_busy on a lease conflict, 409
  archive_manifest for a damaged, newer or foreign archive.json (was 500).

Parallelism (UI-02):
- Auto is the job engine's default, half the logical cores (BRIEF 14.6), with each
  job's own decode and analysis threads; a value the user sets is the number of
  workers and caps those threads. The memory budget is shared: each job's frame
  window gets budget / workers.

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 11:06:27 +00:00
1 parent 3e146c9f9f
commit 56aa4da674
63 files changed
+484 -179

No files matched your search

+8 -2
View File
@@ -10,8 +10,14 @@ public static class CurrentArchive
{
if (archives.Count == 0) return null;
if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
var wanted = Normalize(lastRoot);
return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase)) ?? archives[0];
return At(archives, lastRoot) ?? archives[0];
}
/// <summary>The archive indexed at <paramref name="root"/>; null when none is (Settings › Archive never edits another one).</summary>
public static Core.Model.Archive? At(IReadOnlyList<Core.Model.Archive> archives, string root)
{
var wanted = Normalize(root);
return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase));
}
public static async Task<Core.Model.Archive?> FindAsync(TitanoDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
+12 -8
View File
@@ -188,7 +188,7 @@ public sealed class AppServices : IAsyncDisposable
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
}
/// <summary>Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: cores minus four).</summary>
/// <summary>Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
public int Parallelism => ProcessingTuning.Parallelism(Settings, System.Environment.ProcessorCount);
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
@@ -206,10 +206,12 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
/// Advanced replaced it), starts the job engine and the daily backups.
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
/// and the daily backups.
/// </summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
{
await RestoreStagedAsync(databasePath, ct);
try
{
Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
@@ -221,7 +223,6 @@ public sealed class AppServices : IAsyncDisposable
Log.Error("app", "The index could not be opened", ex);
return;
}
await RestoreStagedAsync(Database, ct);
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
Devices.Start();
@@ -286,15 +287,18 @@ public sealed class AppServices : IAsyncDisposable
}
}
/// <summary>A restore staged in Settings › Advanced replaces the index before anything reads it (<see cref="StagedRestore"/>).</summary>
private async Task RestoreStagedAsync(TitanoDatabase database, CancellationToken ct)
/// <summary>
/// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an
/// index that no longer opens (<see cref="StagedRestore"/>).
/// </summary>
private async Task RestoreStagedAsync(string databasePath, CancellationToken ct)
{
try
{
if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(database, Environment.BackupDirectory, ct), ct))
if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(databasePath, Environment.BackupDirectory, ct), ct))
{
StagedRestore = StagedRestoreResult.Restored;
Log.Info("app", $"Index restored (schema {database.SchemaVersion})");
Log.Info("app", $"Index at {databasePath} restored from the staged copy");
}
}
catch (InvalidDataException ex)
@@ -302,7 +306,7 @@ public sealed class AppServices : IAsyncDisposable
StagedRestore = StagedRestoreResult.Unreadable;
Log.Error("app", "The staged index copy failed its checks; it was set aside and the index kept", ex);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or DllNotFoundException)
{
StagedRestore = StagedRestoreResult.Deferred;
Log.Error("app", "The staged index restore could not run; the index was kept and the restore stays staged", ex);
+1 -1
View File
@@ -125,7 +125,7 @@ public sealed class AppSettings
/// <summary>Frame memory budget in GB; null = Auto (a quarter of installed memory).</summary>
public int? MemoryBudgetGb { get; set; }
/// <summary>Worker threads; null = Auto (cores minus four, at least one).</summary>
/// <summary>Jobs run at once, also capping their decode and analysis threads; null = Auto (half the logical cores, at least one, with the jobs' own thread counts).</summary>
public int? Parallelism { get; set; }
public bool BackgroundPriority { get; set; } = true;
@@ -68,11 +68,12 @@ public static class ArchiveActions
}
/// <summary>
/// Why creating or opening an archive failed: the archive's own sentences for files, access and the index
/// (<see cref="ArchiveFailures"/>), otherwise <see cref="Shell.ErrorText"/> (a catalog sentence, or "Something went wrong").
/// Why creating, opening or changing an archive failed: the archive's own sentences for files (an unreadable
/// archive.json included), access and the index (<see cref="ArchiveFailures"/>), otherwise <see cref="Shell.ErrorText"/>
/// (a catalog sentence, or "Something went wrong").
/// </summary>
public static string Cause(Exception ex) =>
ex is IOException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
ex is IOException or InvalidDataException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
}
/// <summary>Archive roots offered by default and their free space.</summary>
+1
View File
@@ -85,6 +85,7 @@
<MenuItem Header="{l:Loc Archive.Maintenance.DryRun}" Command="{Binding MaintenanceDryRunCommand}" ToolTip="{l:Loc Tooltips.Archive.MaintenanceDryRun}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Proxies}" Command="{Binding RebuildProxiesCommand}" ToolTip="{Binding RebuildProxiesToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Backup}" Command="{Binding BackupCommand}" ToolTip="{l:Loc Tooltips.Archive.Backup}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Restore}" Command="{Binding RestoreCommand}" ToolTip="{l:Loc Tooltips.Archive.Restore}" />
<MenuItem Header="{l:Loc Archive.Maintenance.Trash}" Command="{Binding TrashCommand}" ToolTip="{l:Loc Tooltips.Archive.Trash}" ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Archive.Maintenance.Relink}" Command="{Binding RelinkCommand}" ToolTip="{l:Loc Tooltips.Archive.Relink}" ToolTipService.ShowOnDisabled="True" />
@@ -83,6 +83,11 @@ public sealed class ArchiveViewModel : SectionViewModel
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
BackupCommand = new AsyncRelayCommand(BackupAsync, () => Services.Database is not null);
RestoreCommand = new RelayCommand(() =>
{
Shell.Settings.Page = Titano.App.Settings.SettingsPage.Advanced;
Shell.Navigate(SectionKey.Settings);
});
MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, _archive!.Name, force: true), All()), IsOnline);
@@ -176,6 +181,10 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a daily copy is compared and restored (§6.2).</summary>
public ICommand RestoreCommand { get; }
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
+2 -2
View File
@@ -283,11 +283,11 @@
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding Parallelism.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Parallelism}" ToolTip="{Binding Parallelism.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Rendering.Parallelism}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding CoresText}" Margin="12,0,0,0" />
<Border Style="{StaticResource Pill.Auto}" Margin="12,0,0,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Settings.ParallelismAuto}"
<Border Style="{StaticResource Pill.Auto}" Margin="12,0,0,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Settings.WorkersAuto}"
Visibility="{Binding IsParallelismAuto, Converter={StaticResource BoolToVisibility}}">
<TextBlock Style="{StaticResource Text.AutoPill}" Text="{Binding ParallelismAutoText}" />
</Border>
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.ParallelismReset}"
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.WorkersReset}"
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
Visibility="{Binding IsParallelismAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.InterfacePriority}"
+109 -30
View File
@@ -80,6 +80,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
Save();
UpdateArchiveFree();
_ = RetargetArchiveAsync();
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
@@ -334,12 +335,13 @@ public sealed class SettingsViewModel : SectionViewModel
private set => Set(ref _previewNames, value);
}
/// <summary>BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose.</summary>
/// <summary>
/// BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose. A size the
/// archive got elsewhere (the admin panel also offers 3840) is listed with its number, never shown as another size.
/// </summary>
public IReadOnlyList<SettingsOption<int>> ProxySizes =>
[
new(1280, "1280"),
new(1920, "1920"),
new(2560, "2560"),
.. Sizes([1280, 1920, 2560], _s.ProxyLongEdge is ProxyPolicy.FullSize or ProxyPolicy.Disabled ? null : _s.ProxyLongEdge),
new(ProxyPolicy.FullSize, Loc.L("Settings.Archive.FullSize")),
new(ProxyPolicy.Disabled, Loc.L("Settings.Archive.NoProxies")),
];
@@ -347,7 +349,7 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>The open archive's proxy size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedProxySize
{
get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
get => ProxySizes.First(p => p.Value == _s.ProxyLongEdge);
set
{
if (value is null || value.Value == _s.ProxyLongEdge) return;
@@ -358,12 +360,13 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
public IReadOnlyList<SettingsOption<int>> ThumbnailSizes => [.. new[] { 240, 320, 480, 640 }.Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
/// <summary>240, 320 (default), 480 or 640; another size of the archive (160 to 1024 are valid) is listed with its number.</summary>
public IReadOnlyList<SettingsOption<int>> ThumbnailSizes => Sizes([240, 320, 480, 640], _s.ThumbnailLongEdge);
/// <summary>The open archive's thumbnail size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedThumbnailSize
{
get => ThumbnailSizes.FirstOrDefault(p => p.Value == _s.ThumbnailLongEdge) ?? ThumbnailSizes[1];
get => ThumbnailSizes.First(p => p.Value == _s.ThumbnailLongEdge);
set
{
if (value is null || value.Value == _s.ThumbnailLongEdge) return;
@@ -549,7 +552,7 @@ public sealed class SettingsViewModel : SectionViewModel
public int LogicalCores => Environment.ProcessorCount;
/// <summary>Auto: cores minus four so the UI stays responsive.</summary>
/// <summary>Auto: half the logical cores, the job engine's default (BRIEF §14.6).</summary>
public int ParallelismAuto => ProcessingTuning.ParallelismAuto(LogicalCores);
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
@@ -713,7 +716,8 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>A restore waits for the next start of Titano.</summary>
public bool IsRestoreStaged => DatabaseBackups.HasStagedRestore(Shell.Services.Environment.DatabasePath);
private bool CanRestore => !_isRestoring && _selectedBackup is not null && Shell.Services.Database is not null && !IsRestoreStaged;
/// <summary>Also while the index cannot be opened: that is the case a restore exists for (BRIEF §6.2).</summary>
private bool CanRestore => !_isRestoring && _selectedBackup is not null && !IsRestoreStaged;
public ICommand RestoreDatabaseCommand { get; }
public ICommand CancelRestoreCommand { get; }
@@ -840,14 +844,17 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>
/// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is
/// offline) unless a field holds an edit; they also become the defaults of new archives.
/// offline) unless a field holds an edit; they also become the defaults of new archives. The open archive is the one
/// at the archive folder of this PC, never another one of the index: with none registered there, the rows edit only
/// this PC's defaults.
/// </summary>
private async Task LoadArchiveAsync()
{
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return;
try
{
var archive = await CurrentArchive.FindAsync(db, _s.LastArchivePath);
var registered = await db.Archives.ListAsync();
var archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : CurrentArchive.Pick(registered, null);
_archive = archive;
if (archive is null) return;
var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id));
@@ -860,6 +867,9 @@ public sealed class SettingsViewModel : SectionViewModel
_s.ProxyLongEdge = settings.Proxies.LongEdge;
_s.ThumbnailLongEdge = settings.Thumbnails.LongEdge;
if (changed) Save();
// The lists first: a size the archive got elsewhere joins them before it is selected.
OnPropertyChanged(nameof(ProxySizes));
OnPropertyChanged(nameof(ThumbnailSizes));
OnPropertyChanged(nameof(SelectedProxySize));
OnPropertyChanged(nameof(SelectedThumbnailSize));
UpdatePreview();
@@ -879,9 +889,12 @@ public sealed class SettingsViewModel : SectionViewModel
if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return;
try
{
_archive = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
// The archive folder may have changed meanwhile: the rows then belong to another archive.
if (_archive?.Id == updated.Id) _archive = updated;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
or DatabaseException)
{
Log.Warning("settings", "The archive settings were not saved", ex);
Shell.Notify(Loc.L("Settings.Archive.NotSaved"), ArchiveActions.Cause(ex), isError: true);
@@ -889,7 +902,7 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
/// <summary>All of Settings › Archive into the open archive (after a reset or an import of settings).</summary>
/// <summary>Every archive row into the open archive: Archive › Reset section, after the user confirmed it for that archive.</summary>
private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with
{
Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate },
@@ -897,6 +910,45 @@ public sealed class SettingsViewModel : SectionViewModel
Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge },
});
/// <summary>
/// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given
/// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives.
/// Later edits never reach the archive shown before.
/// </summary>
private async Task RetargetArchiveAsync()
{
_archive = null;
if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives)
{
try
{
var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null);
if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("settings", $"The archive at {root} could not be opened", ex);
Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true);
}
}
await LoadArchiveAsync();
}
/// <summary>
/// Archive › Reset section with an archive open writes the defaults into that archive's archive.json, which the server
/// and the other PCs share: the user confirms it for that archive by name first.
/// </summary>
private bool ConfirmArchiveReset(Archive archive) => Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Archive.ResetTitle", archive.Name),
Message = Loc.L("Settings.Archive.ResetMessage"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepArchiveSettings"),
ActionText = Loc.L("Settings.Archive.ResetAction"),
ActionToolTip = Loc.L("Tooltips.Settings.ResetArchiveConfirm"),
IsDestructive = true,
});
private void OnServerChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
LoadCertificates();
@@ -911,6 +963,13 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
}
/// <summary>The preset sizes in order, with <paramref name="current"/> among them when it is none of them.</summary>
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int? current)
{
var values = current is { } size && !presets.Contains(size) ? presets.Append(size) : presets;
return [.. values.Order().Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
}
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
private static string? ValidateInt(string text, int min, int max) =>
@@ -1104,24 +1163,24 @@ public sealed class SettingsViewModel : SectionViewModel
}
/// <summary>
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now; after the user's
/// destructive confirmation the copy is staged beside the index for the next start, where the index as it is then is
/// backed up first (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning
/// to three copies). Nothing replaces the index while Titano runs.
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now (shown as unreadable
/// when the index did not open, the case a restore exists for); after the user's destructive confirmation the copy is
/// staged beside the index for the next start, where the index as it is then is kept first and replaced before it is
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning to three
/// copies). Nothing replaces the index while Titano runs.
/// </summary>
private async Task RestoreDatabaseAsync()
{
if (_selectedBackup is not { } option || Shell.Services.Database is not { } db) return;
if (_selectedBackup is not { } option) return;
var backup = option.Backup;
var environment = Shell.Services.Environment;
_isRestoring = true;
CommandManager.InvalidateRequerySuggested();
try
{
DatabaseSummary current, restored;
DatabaseSummary restored;
try
{
current = await DatabaseBackups.SummarizeAsync(db);
restored = await Task.Run(() => DatabaseBackups.SummarizeBackupAsync(backup.Path, environment.DataDirectory));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException or DatabaseException)
@@ -1130,13 +1189,28 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Errors.Backup.Unreadable"), isError: true);
return;
}
DatabaseSummary? current = null;
if (Shell.Services.Database is { } db)
{
try
{
current = await DatabaseBackups.SummarizeAsync(db);
}
catch (DatabaseException ex)
{
// A damaged index may open and still fail to count: it is shown as unreadable, and the restore remains possible.
Log.Warning("settings", "The current index could not be summarized", ex);
}
}
var currentLine = current is { } now
? Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(now.Sequences), Formatting.Count(now.Photos))
: Loc.L("Settings.Advanced.RestoreUnreadable");
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.RestoreTitle", option.Label),
Message = Loc.L("Settings.Advanced.RestoreMessage"),
Detail = string.Join(Environment.NewLine,
Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)),
Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(current.Sequences), Formatting.Count(current.Photos))),
Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)), currentLine),
IsDetailMonospaced = false,
DetailToolTip = Formatting.LeftToRight(backup.Path),
SafeText = Loc.L("Settings.Storage.Keep"),
@@ -1193,6 +1267,9 @@ public sealed class SettingsViewModel : SectionViewModel
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
// The rows are the open archive's own: resetting them changes it for everyone sharing it, so only when confirmed.
var open = _archive;
if (open is not null && !ConfirmArchiveReset(open)) return;
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
@@ -1201,7 +1278,7 @@ public sealed class SettingsViewModel : SectionViewModel
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
_ = PushArchiveSettingsAsync();
if (open is not null) _ = PushArchiveSettingsAsync();
break;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
@@ -1264,9 +1341,10 @@ public sealed class SettingsViewModel : SectionViewModel
}
/// <summary>
/// Advanced › Reset: every preference back to its default after a destructive confirmation. What identifies this PC's
/// data and session stays: the archive folder, the server, its session and trusted certificates, the window and the
/// first-run choice. The open archive takes the default templates and sizes.
/// Advanced › Reset: every preference of this PC back to its default after a destructive confirmation. What identifies
/// this PC's data and session stays: the archive folder, the server, its session and trusted certificates, the window
/// and the first-run choice. The open archive's own settings (archive.json, shared with the server and other PCs) are
/// not touched: the Archive rows show them again (with no archive open, they show the reset defaults of new archives).
/// </summary>
private void ResetAll()
{
@@ -1294,7 +1372,7 @@ public sealed class SettingsViewModel : SectionViewModel
JobsClearedAt = _s.JobsClearedAt,
};
ApplyAll(defaults);
_ = PushArchiveSettingsAsync();
_ = LoadArchiveAsync();
Log.Info("settings", "Every setting reset to its default");
Shell.Notify(Loc.L("Settings.Advanced.ResetDone"));
}
@@ -1363,8 +1441,9 @@ public sealed class SettingsViewModel : SectionViewModel
imported.Window = _s.Window;
imported.FirstRunCompleted = _s.FirstRunCompleted;
ApplyAll(imported);
// The imported templates and sizes become the open archive's, as when typed in Settings › Archive.
_ = PushArchiveSettingsAsync();
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_ = RetargetArchiveAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
+17 -12
View File
@@ -31,38 +31,43 @@ public static class ProcessingTuning
/// <summary>Frames decoded ahead of the render position, per quality profile (Best keeps more in flight, within the budget).</summary>
public static int ReadAhead(QualityProfile quality) => quality == QualityProfile.Best ? 8 : 4;
/// <summary>Auto parallelism: logical cores minus four, so the interface stays responsive (at least one).</summary>
public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores - 4);
/// <summary>Auto parallelism: the job engine's default, half the logical cores (BRIEF §14.6), at least one.</summary>
public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores / 2);
/// <summary>Workers and threads this PC's jobs use: the user's value, or Auto.</summary>
/// <summary>Workers of this PC's job engine: the user's value, or Auto.</summary>
public static int Parallelism(AppSettings settings, int logicalCores) => settings.Parallelism is { } n and > 0 ? n : ParallelismAuto(logicalCores);
/// <summary>The frame memory budget in bytes: the user's GB, or Auto (a quarter of <paramref name="installedBytes"/>).</summary>
/// <summary>The frame memory budget of this PC in bytes: the user's GB, or Auto (a quarter of <paramref name="installedBytes"/>).</summary>
public static long MemoryBudget(AppSettings settings, long installedBytes) =>
settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : long.Max(1L << 30, installedBytes / 4);
/// <summary><paramref name="basis"/> with the user's current Rendering and Analysis settings.</summary>
/// <summary>
/// <paramref name="basis"/> with the user's current Rendering and Analysis settings. The memory budget is shared by the
/// jobs that can run at once: each job's frame window gets its share (budget ÷ workers). Auto keeps the engine's own
/// thread counts per job; a value the user set also caps the background decodes and the deep analysis's threads.
/// </summary>
public static ProcessingOptions Apply(ProcessingOptions basis, AppSettings settings, long installedBytes, int logicalCores, string spillDirectory)
{
var parallelism = Parallelism(settings, logicalCores);
var workers = Parallelism(settings, logicalCores);
int? cap = settings.Parallelism is { } n and > 0 ? n : null;
var analysis = settings.DeepAnalysis(basis.DeepAnalysis);
return basis with
{
FrameWindow = basis.FrameWindow with
{
MemoryBudget = MemoryBudget(settings, installedBytes),
MemoryBudget = long.Max(1, MemoryBudget(settings, installedBytes) / workers),
SpillDirectory = spillDirectory,
Ahead = ReadAhead(settings.Quality),
MaxConcurrentLoads = int.Clamp(parallelism, 1, basis.FrameWindow.MaxConcurrentLoads),
MaxConcurrentLoads = cap is { } loads ? int.Clamp(loads, 1, basis.FrameWindow.MaxConcurrentLoads) : basis.FrameWindow.MaxConcurrentLoads,
},
Render = basis.Render with
{
AnalysisLongEdge = PreparationLongEdge(settings.Quality),
DefaultFlowQuality = FlowQuality(settings.Quality),
},
DeepAnalysis = settings.DeepAnalysis(basis.DeepAnalysis) with
{
MaxDegreeOfParallelism = int.Clamp(parallelism, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism),
},
DeepAnalysis = cap is { } threads
? analysis with { MaxDegreeOfParallelism = int.Clamp(threads, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism) }
: analysis,
};
}
}
+15 -3
View File
@@ -79,8 +79,7 @@ public sealed class ArchiveService : IJobHandlerProvider
{
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 };
settings = WithUsableName(settings, paths);
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);
@@ -166,6 +165,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <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.
/// A blank or overlong name in the file (archives made at a drive root, or before names were checked) is made usable
/// as <see cref="CreateAsync(string, ArchiveSettings, CancellationToken)"/> does, instead of failing every edit.
/// </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>
@@ -182,7 +183,8 @@ public sealed class ArchiveService : IJobHandlerProvider
{
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));
// The name read is made usable before the edit sees it; a name the edit sets is checked as given.
var settings = edit(WithUsableName(ArchiveSettings.Of(current), paths));
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
manifest = current with
{
@@ -296,6 +298,16 @@ public sealed class ArchiveService : IJobHandlerProvider
await Imports.PlanEraseAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cardId, sourceRoot, progress,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// <paramref name="settings"/> with a name an archive can keep: a blank one becomes the folder's name (the root itself
/// for a drive root), one longer than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
/// </summary>
private static ArchiveSettings WithUsableName(ArchiveSettings settings, ArchivePaths paths)
{
var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
return settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
}
private async Task<Archive> RegisterAsync(ArchivePaths paths, ArchiveManifest manifest, CancellationToken cancellationToken)
{
var archive = new Archive
+63 -19
View File
@@ -16,8 +16,8 @@ public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequen
/// 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.
/// index and replaces it at the next start, before the host opens the index (so it also recovers an index that no
/// longer opens), once the index it replaces has been kept.
/// </summary>
public static partial class DatabaseBackups
{
@@ -101,10 +101,11 @@ public static partial class DatabaseBackups
}
/// <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).
/// The restore's dry run and check: what <paramref name="backupPath"/> holds, read from a scratch copy in
/// <paramref name="scratchDirectory"/> (so the backup itself is never written) that first passes
/// <c>PRAGMA quick_check</c>, then opens and migrates.
/// </summary>
/// <exception cref="InvalidDataException">The file is not a readable Titano index.</exception>
/// <exception cref="InvalidDataException">The file is not a sound Titano index this build can open.</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]);
@@ -115,6 +116,8 @@ public static partial class DatabaseBackups
File.Copy(backupPath, copy);
try
{
// Before the migration writes to it: a damaged page in a table the counts never read must not pass.
await CheckIntegrityAsync(copy, cancellationToken).ConfigureAwait(false);
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(copy), cancellationToken).ConfigureAwait(false);
return await SummarizeAsync(db, cancellationToken).ConfigureAwait(false);
}
@@ -167,22 +170,25 @@ public static partial class DatabaseBackups
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.
/// Carries out a staged restore before the host opens the index at <paramref name="databasePath"/>, so it also
/// recovers an index that no longer opens. The staged copy is checked first (<see cref="SummarizeBackupAsync"/>:
/// <c>quick_check</c>, open, migration). The index as it is now is kept in <paramref name="backupDirectory"/>: as a
/// fresh <c>VACUUM INTO</c> copy among the daily ones, or, when it cannot be read, copied there whole (with its WAL) as
/// <c>&lt;name&gt;-replaced-&lt;stamp&gt;.db</c>, outside the rotation, so it never pushes a good copy out. Only then is
/// the staged copy renamed over the index: the rename consumes it, so it is never applied twice. The host's open then
/// migrates it 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)
/// <exception cref="IOException">The index could not be kept or replaced (also <see cref="UnauthorizedAccessException"/>):
/// the restore stays staged for the next start.</exception>
public static async Task<bool> RestoreStagedAsync(string databasePath, string backupDirectory, CancellationToken cancellationToken = default)
{
if (db.Database is not SqliteDatabase { Path: { } path }) return false;
var path = Path.GetFullPath(databasePath);
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.
// A copy this build cannot open (damaged, or made by a newer Titano) must never replace the index.
await SummarizeBackupAsync(staged, Path.GetDirectoryName(path) ?? ".", cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException)
@@ -190,14 +196,52 @@ public static partial class DatabaseBackups
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}");
// What the index holds up to this start stays recoverable: no restore without keeping it first.
var kept = File.Exists(path) ? await KeepAsync(path, backupDirectory, cancellationToken).ConfigureAwait(false) : null;
// A WAL left behind belongs to the replaced file and would be replayed onto the restored one.
File.Delete(path + "-wal");
File.Delete(path + "-shm");
AtomicFile.Commit(staged, path);
Log.Info("backup", kept is null ? "Index restored from the staged copy" : $"Index restored from the staged copy; the index it replaced is {kept}");
return true;
}
/// <summary>
/// The index about to be replaced, kept in <paramref name="backupDirectory"/>: a <c>VACUUM INTO</c> copy when it opens,
/// else the file itself with its WAL, set aside under a name the pruning of the daily copies never matches.
/// </summary>
private static async Task<string> KeepAsync(string path, string backupDirectory, CancellationToken cancellationToken)
{
try
{
await using var current = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), cancellationToken).ConfigureAwait(false);
return await current.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
{
Log.Warning("backup", $"The index at {path} cannot be read; it is set aside whole", ex);
}
Directory.CreateDirectory(backupDirectory);
var target = Path.Combine(backupDirectory, string.Create(CultureInfo.InvariantCulture,
$"{Path.GetFileNameWithoutExtension(path)}-replaced-{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}.db"));
// Copied, not moved: should the swap fail, the index stays where the next start looks for it.
File.Copy(path, target);
// SQLite finds a WAL by the database's name: copied alongside, the file set aside keeps its last transactions.
if (File.Exists(path + "-wal")) File.Copy(path + "-wal", target + "-wal");
return target;
}
/// <summary><c>PRAGMA quick_check</c> of the SQLite file at <paramref name="path"/>, opened without migrating it.</summary>
/// <exception cref="InvalidDataException">The check reported damage.</exception>
/// <exception cref="DatabaseException">The file is not a database SQLite can read.</exception>
private static async Task CheckIntegrityAsync(string path, CancellationToken cancellationToken)
{
await using var database = DatabaseFactory.Open(DatabaseOptions.Sqlite(path));
await using var session = await database.OpenAsync(cancellationToken).ConfigureAwait(false);
var result = await session.ScalarAsync<string>("PRAGMA quick_check", [], cancellationToken).ConfigureAwait(false);
if (result != "ok") throw new InvalidDataException($"The copy failed its integrity check: {result}");
}
[GeneratedRegex(@"^(?<stem>.+)-(?<at>\d{8}-\d{6}-\d{3})\.db$", RegexOptions.CultureInvariant)]
private static partial Regex Stamp();
}
+7 -2
View File
@@ -66,7 +66,8 @@ public static class ArchiveEndpoints
/// <summary>
/// Writes the name, templates and proxy policy into the archive's <c>archive.json</c> through the archive engine (so a
/// restart and the proxy jobs see them), then into the index. 503 <c>archive_offline</c> while the archive cannot be
/// written; 409 <c>sequence_busy</c> while another process holds its settings.
/// written; 409 <c>archive_busy</c> while another process holds its settings; 409 <c>archive_manifest</c> when its
/// archive.json is damaged, written by a newer Titano or of another archive (nothing is written).
/// </summary>
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, AuditLog audit)
@@ -92,7 +93,11 @@ public static class ArchiveEndpoints
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "sequence_busy");
return ApiErrors.Conflict(context, "archive_busy");
}
catch (Exception ex) when (ex is InvalidDataException or NewerFormatException)
{
return ApiErrors.Conflict(context, "archive_manifest");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{