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:
63 files changed
+484
-179
No files matched your search
@@ -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
|
||||
|
||||
@@ -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><name>-replaced-<stamp>.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();
|
||||
}
|
||||
Reference in new issue
Block a user