feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s

- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 21:58:39 +01:00
1 parent 9aa818ed47
commit 7e4a3b481d
416 files changed
+15304 -1572

No files matched your search

+123 -17
View File
@@ -2,6 +2,7 @@ using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data.Archiving.Jobs;
@@ -73,8 +74,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
/// <see cref="JobEngine"/>.
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7,
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
/// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
@@ -90,6 +91,7 @@ public sealed class ArchiveService : IJobHandlerProvider
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
new EmptyTrashJobHandler(_db, Trash),
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
];
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
@@ -103,13 +105,14 @@ public sealed class ArchiveService : IJobHandlerProvider
/// 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>
/// <exception cref="ArgumentException">A template or policy is invalid (<see cref="ArgumentException.ParamName"/> names it;
/// <see cref="TemplateRuleException"/> for a template that breaks a rule).</exception>
public async Task<Archive> CreateAsync(string root, ArchiveSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
var paths = new ArchivePaths(root);
settings = WithUsableName(settings, paths);
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
settings.Validate();
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Chronos archive.");
Directory.CreateDirectory(paths.MetaDirectory);
var manifest = new ArchiveManifest
@@ -127,7 +130,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>
/// Registers an existing archive (or relinks a moved one: same id, new root) and completes renames a crash
/// interrupted. An offline archive is registered as it was last seen.
/// interrupted (each sequence they change is told to <see cref="ArchiveServiceOptions.SequenceChanged"/>); one that
/// cannot be completed yet is logged and waits for the next open. An offline archive is registered as it was last seen.
/// </summary>
public async Task<Archive> OpenAsync(string root, CancellationToken cancellationToken = default)
{
@@ -138,9 +142,9 @@ public sealed class ArchiveService : IJobHandlerProvider
{
await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException)
{
// The journal stays; the next open tries again. The archive itself is usable meanwhile.
// The journal stays; the next open tries again. The archive itself is usable meanwhile (a server starts all the same).
Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex);
}
return archive;
@@ -209,9 +213,12 @@ public sealed class ArchiveService : IJobHandlerProvider
/// 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.
/// as <see cref="CreateAsync(string, ArchiveSettings, CancellationToken)"/> does, instead of failing every edit. Likewise
/// a template the file holds that breaks a rule of the archive's templates (saved before the rules existed) stays as it
/// is through an edit of anything else: only a template the edit gives is held to them (<see cref="ArchiveSettings.Problem"/>).
/// </summary>
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it;
/// <see cref="TemplateRuleException"/> for a template that breaks a rule).</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)
@@ -228,7 +235,8 @@ public sealed class ArchiveService : IJobHandlerProvider
if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}.");
// 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);
// A template the file already holds stays as it is, rules or not: only one the edit gives is held to them.
settings.Validate(current.LayoutTemplates);
var manifest = current with
{
Name = settings.Name.Trim(),
@@ -267,9 +275,9 @@ public sealed class ArchiveService : IJobHandlerProvider
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequenceId);
var inStep = await Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
for (var attempt = 1; ; attempt++)
@@ -303,6 +311,25 @@ public sealed class ArchiveService : IJobHandlerProvider
}
}
/// <summary>
/// Runs <paramref name="write"/> under the lease of <paramref name="sequence"/>, with its index row read under it (null
/// when the sequence left the index). A Reorganize moves a folder, its row and the paths of the renders inside it under
/// that lease, so a writer that files into the folder and records what it filed (a render a client or render node sends)
/// does both where the sequence is then, never in a folder it left, and what it records follows a later move.
/// </summary>
/// <exception cref="ArgumentException">The sequence's archive is not in the index.</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than the lease wait.</exception>
public async Task<T> UnderLeaseAsync<T>(Sequence sequence, Func<Sequence?, Task<T>> write, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(write);
var paths = new ArchivePaths((await LoadArchiveAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)).RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
return await write(await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
}
public Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
Maintenance.FindDuplicatesAsync(archiveId, cancellationToken);
@@ -351,7 +378,23 @@ public sealed class ArchiveService : IJobHandlerProvider
await Renamer.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, folderTemplate, titleTemplate,
cancellationToken).ConfigureAwait(false);
public async Task ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
/// <summary>
/// The dry run of a Reorganize (owner review 2, R7): <paramref name="templates"/> over <paramref name="sequenceIds"/>, or
/// over every sequence of the archive (by folder) when null. Apply it in a job (<see cref="ArchiveJobs.Reorganize"/>) or
/// with <see cref="ApplyRenameAsync"/>.
/// </summary>
/// <exception cref="ArgumentException">The archive is unknown, or a sequence is not in it.</exception>
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
public async Task<RenamePlan> PlanReorganizeAsync(Guid archiveId, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(templates);
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)];
return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false);
}
public async Task<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
.ConfigureAwait(false);
@@ -497,17 +540,62 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
&& Proxies.LongEdge == archive.ProxyLongEdge;
}
/// <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()
/// <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. A template has to be usable
/// (<see cref="RenameTemplates.Check"/>), and one given anew is held to the rules it meets wherever it is typed
/// (<see cref="TemplateRules"/>): a folder template may not write a level scans never enter, and a file template must
/// keep the photo's extension, tell a session's photos apart and hold no slash.
/// </summary>
/// <param name="stored">The templates archive.json holds before an edit: one the edit leaves as it is, saved before the
/// rules existed (0.1.0-rc.5 and earlier), never fails an edit of another setting. Null holds both to every rule (a new
/// archive).</param>
public string? Problem(LayoutTemplates? stored = null)
{
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 (CheckTemplates(stored) is { } template) return template.Field;
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>
/// The first template that cannot be used (<see cref="Problem"/>), with the rule it breaks
/// (<see cref="TemplateProblem.Rule"/>); null when both can. A rule broken by a template <paramref name="stored"/>
/// already holds does not count.
/// </summary>
public TemplateProblem? CheckTemplates(LayoutTemplates? stored = null)
{
if (string.IsNullOrWhiteSpace(Templates.Folder)) return new TemplateProblem("folderTemplate", null);
if (string.IsNullOrWhiteSpace(Templates.File)) return new TemplateProblem("fileTemplate", null);
static TemplateProblem? Given(RenameTemplates template, bool kept) => template.Check() is { } problem && (problem.Rule is null || !kept) ? problem : null;
return Given(new RenameTemplates(Folder: Templates.Folder), Templates.Folder == stored?.Folder)
?? Given(new RenameTemplates(File: Templates.File), Templates.File == stored?.File);
}
/// <summary>Refuses these settings when a field is invalid (<see cref="Problem"/>).</summary>
/// <exception cref="TemplateRuleException">A template breaks a rule of the archive's templates.</exception>
/// <exception cref="ArgumentException">Another field is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
internal void Validate(LayoutTemplates? stored = null)
{
if (Problem(stored) is not { } field) return;
if (CheckTemplates(stored) is { Rule: { } rule } template && template.Field == field) throw new TemplateRuleException(field, rule);
throw new ArgumentException($"The archive setting {field} is invalid.", field);
}
}
/// <summary>
/// An archive setting's template breaks a rule of the archive's templates (<see cref="TemplateRules"/>): the message says
/// which in one sentence (<c>Errors.Template.&lt;Rule&gt;</c>, in the language of the moment it was refused), and
/// <see cref="ParamName"/> names the template by its API name (<c>folderTemplate</c>, <c>fileTemplate</c>).
/// </summary>
public sealed class TemplateRuleException(string field, string rule) : ArgumentException(Loc.L("Errors.Template." + rule))
{
// Not the base's: its message would end in "(Parameter '…')".
public override string? ParamName { get; } = field;
/// <summary>The rule broken (<see cref="TemplateProblem.Rule"/>).</summary>
public string Rule { get; } = rule;
}
/// <summary>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
@@ -567,6 +655,24 @@ public static class ArchiveJobs
JobPriority.User);
}
/// <summary>
/// <see cref="JobKind.Move"/>: applies the Reorganize <paramref name="plan"/> (the dry run of <paramref name="templates"/>,
/// <see cref="ArchiveService.PlanReorganizeAsync"/>) as confirmed, refused when the archive changed since
/// (<see cref="MoveJobParameters"/>; owner review 2, R7).
/// </summary>
public static ArchiveJobRequest Reorganize(Archive archive, RenamePlan plan, RenameTemplates templates)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(templates);
// The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again.
var steps = plan.Steps.Select(s => s.SequenceId).ToHashSet();
var sequences = plan.Subjects.Where(steps.Contains).Select(id => new MoveSequence(id)).ToList();
return new(JobKind.Move, [archive.Id], archive.Name,
Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters),
JobPriority.User);
}
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);