Second fix round of owner review 2, phase 4a (planner findings).
- A sequence keeps a folder that differs from its own in case only while no
other folder holds that exact name (RenamePlanner.ExistsExactly, every level
compared exactly). On a case-sensitive file system a stray "Trip (2)" beside
the sequence at "trip (2)" no longer gives a case-only step that MoveFolder
refuses at every archive open: the plan gives "Trip", and a plan whose
target appeared since is refused under the step's leases before anything
moves (or dropped when it resumes). A change of case in an outer level no
longer looks like two folders on Windows.
- A file name longer than 200 characters is shortened before the ".{ext}" the
template ends with, never through it, so a long title never strips the
photo's extension.
- The archive engine's own settings check applies the template rules the
server and the desktop apply (a folder scans skip, a lost extension, names
that repeat), so archive.json can no longer take such a template.
- The server's invalid_template answer names the rule after the field
("fileTemplate:extension") with the desktop's sentence as its message; both
admin panels show it on the field.
- FrameNaming keeps only the naming overloads production uses.
- Comments about Unreadable say the whole sequence stays as it is.
- Tests pin filing against Reorganize: an upload without a capture time, a
card's second session with {session}, a duplicate skipped mid-session, and a
whole folder of two cameras named with the first one's camera.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 50fe59aec1e180daa1733bcb951892a79dceba6c)
242 lines
16 KiB
C#
242 lines
16 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Chronos.Core.Archiving;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Core.Naming;
|
|
using Chronos.Data;
|
|
using Chronos.Data.Archiving;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Data.Repositories;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Jobs;
|
|
using Chronos.Server.Security;
|
|
using Chronos.Server.Storage;
|
|
|
|
namespace Chronos.Server.Api;
|
|
|
|
/// <summary>
|
|
/// <c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and
|
|
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive.
|
|
/// </summary>
|
|
public static class ArchiveEndpoints
|
|
{
|
|
public static void Map(RouteGroupBuilder api)
|
|
{
|
|
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
|
|
archive.MapPost("/reorganize", ReorganizeAsync);
|
|
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
|
|
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
|
|
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
|
|
archive.MapPut("/settings", UpdateAsync);
|
|
archive.MapGet("/stats", async (HttpContext c, ChronosDatabase db, ServerArchive a, VolumeSpace volumes) =>
|
|
Results.Json(await StatsAsync(db, a, volumes, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
|
|
foreach (var (path, kind) in new[] { ("scan", JobKind.Scan), ("rebuild", JobKind.Rebuild), ("verify", JobKind.Verify), ("maintenance", JobKind.Maintenance) })
|
|
{
|
|
archive.MapPost("/" + path, (HttpContext c, Caller caller, ServerArchive a, JobEngineHost host, AuditLog audit) => EnqueueAsync(c, caller, a, host, audit, kind));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Totals, distributions, free space and health of the archive (also shown on the dashboard). The free space is the
|
|
/// space volume's (<see cref="VolumeSpace.Report"/>), with the archive's own volume apart when they differ; an offline
|
|
/// volume reports no figures (0).
|
|
/// </summary>
|
|
public static async Task<ArchiveStatsDto> StatsAsync(ChronosDatabase db, ServerArchive archive, VolumeSpace volumes, CancellationToken cancellationToken)
|
|
{
|
|
var stats = await db.Sequences.GetStatsAsync(archive.Id, cancellationToken);
|
|
var withoutProxies = await db.Sequences.CountAsync(
|
|
new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt }, cancellationToken);
|
|
var storage = volumes.Report(archive.Root);
|
|
return new ArchiveStatsDto(
|
|
stats.Sequences,
|
|
stats.Photos,
|
|
stats.Bytes,
|
|
storage.Space?.FreeBytes ?? 0,
|
|
storage.Space?.TotalBytes ?? 0,
|
|
stats.ByCamera.Count(c => c.Model is not null),
|
|
stats.ByYear.Count > 0 ? stats.ByYear[0].Year : null,
|
|
stats.ByYear.Count > 0 ? stats.ByYear[^1].Year : null,
|
|
[.. stats.ByYear.Select(y => new KeyValueCount(y.Year.ToString(System.Globalization.CultureInfo.InvariantCulture), y.Photos, y.Bytes))],
|
|
[.. stats.ByMonth.Select(m => new KeyValueCount($"{m.Year:D4}-{m.Month:D2}", m.Photos, 0))],
|
|
[.. stats.ByCamera.Select(c => new KeyValueCount(string.Join(' ', new[] { c.Make, c.Model }.Where(v => !string.IsNullOrEmpty(v))), c.Photos, c.Bytes))],
|
|
[.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))],
|
|
withoutProxies,
|
|
stats.Health.Unverified,
|
|
storage.Write?.FreeBytes,
|
|
storage.Write?.TotalBytes,
|
|
storage.FileSystem,
|
|
storage.FromSpacePath);
|
|
}
|
|
|
|
/// <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. 400 <c>bad_request</c> (details <c>name</c>,
|
|
/// <c>proxyLongEdge</c>), 400 <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c> or
|
|
/// <c>fileTemplate</c>, with the rule it breaks); 503 <c>archive_offline</c> while the archive cannot be
|
|
/// 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 Chronos or of another archive; 409 <c>archive_policy</c> when it holds a
|
|
/// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: <c>thumbnailPolicy</c> or
|
|
/// <c>proxyPolicy</c>, the property to correct in the file). Nothing is written.
|
|
/// </summary>
|
|
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, ChronosDatabase db, ServerArchive archive,
|
|
[FromServices] ArchiveService? archives, AuditLog audit)
|
|
{
|
|
var name = request.Name?.Trim();
|
|
if (string.IsNullOrEmpty(name) || name.Length > ArchiveSettings.MaxNameLength) return ApiErrors.BadRequest(context, "bad_request", "name");
|
|
if (string.IsNullOrWhiteSpace(request.FolderTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "folderTemplate");
|
|
if (string.IsNullOrWhiteSpace(request.FileTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "fileTemplate");
|
|
// The rules Reorganize checks: a folder scans never enter, a lost extension or names that repeat are refused alike.
|
|
if (new RenameTemplates(request.FolderTemplate, request.FileTemplate).Check() is { } problem) return InvalidTemplate(context, problem);
|
|
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
|
|
|
|
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
|
|
Archive updated;
|
|
try
|
|
{
|
|
updated = await engine.UpdateSettingsAsync(archive.Id, s => s with
|
|
{
|
|
Name = name,
|
|
Templates = s.Templates with { Folder = request.FolderTemplate, File = request.FileTemplate },
|
|
Proxies = s.Proxies with { LongEdge = request.ProxyLongEdge },
|
|
}, context.RequestAborted);
|
|
}
|
|
catch (LeaseUnavailableException)
|
|
{
|
|
return ApiErrors.Conflict(context, "archive_busy");
|
|
}
|
|
catch (Exception ex) when (ex is InvalidDataException or NewerFormatException)
|
|
{
|
|
return ApiErrors.Conflict(context, "archive_manifest");
|
|
}
|
|
catch (ArgumentException ex)
|
|
{
|
|
// The request's fields were checked above: what fails is a value read from archive.json (a thumbnail size, or a
|
|
// proxy quality, written by hand or by another tool), which the admin corrects in the file, not in this form.
|
|
return ApiErrors.Conflict(context, "archive_policy", ex.ParamName switch
|
|
{
|
|
"thumbnailLongEdge" => "thumbnailPolicy",
|
|
"proxyLongEdge" => "proxyPolicy",
|
|
var other => other,
|
|
});
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
// ArchiveOfflineException included: nothing was written.
|
|
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
|
}
|
|
archive.Current = updated;
|
|
await audit.WriteAsync(caller, context, "archive_settings", "archive", updated.Id.ToString(), $"{updated.FolderTemplate} · {updated.FileTemplate}");
|
|
return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reorganize: folder, file and title templates applied to <c>sequenceIds</c> or, with <c>all</c>, to every sequence of the
|
|
/// archive (BRIEF §12.5). With <c>dryRun</c> the plan, nothing touched: per sequence its folder and title before and after,
|
|
/// the photos renamed with the first of them, and the photos that keep their names and why. Otherwise the request carries
|
|
/// that plan's fingerprint and the server queues a <c>move</c> job (202) that applies exactly that plan, refused when the
|
|
/// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or
|
|
/// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400
|
|
/// <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c>, <c>fileTemplate</c> or
|
|
/// <c>titleTemplate</c>, with the rule it breaks); 404
|
|
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
|
|
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
|
|
/// <c>archive_offline</c>. Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>)
|
|
/// once that sequence's step is journaled (a step that failed half-way, when its retry completes it; a plan the server
|
|
/// completes as it starts, no one: no client is connected yet). Photos a sequence receives between the dry run and the
|
|
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is kept a few
|
|
/// minutes while the index stays as it was (<see cref="ReorganizePlanCache"/>): the same dry run again, and its
|
|
/// confirmation, take it instead of planning again.
|
|
/// </summary>
|
|
private static async Task<IResult> ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
|
|
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans)
|
|
{
|
|
var ct = context.RequestAborted;
|
|
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
|
|
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
|
|
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
|
|
if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates");
|
|
if (templates.Check() is { } problem) return InvalidTemplate(context, problem);
|
|
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
|
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
|
|
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
|
var sequences = request.All ? null : request.SequenceIds;
|
|
// Stamped before planning: a change committed while the plan is made gives the next request another key.
|
|
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, ct), sequences, templates);
|
|
RenamePlan plan;
|
|
try
|
|
{
|
|
plan = await plans.GetOrPlanAsync(key, () => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, ct));
|
|
}
|
|
catch (NestedRenameException ex)
|
|
{
|
|
return ApiErrors.Conflict(context, "nested_target", ex.Target);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
return ApiErrors.NotFound(context, "sequence");
|
|
}
|
|
var fingerprint = plan.Fingerprint();
|
|
if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ReorganizePlanDto);
|
|
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
|
|
if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move));
|
|
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct);
|
|
plans.Forget(key);
|
|
await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(),
|
|
$"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}");
|
|
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 400 <c>invalid_template</c> for a template that cannot be used. The details name its field (<c>fileTemplate</c>); when
|
|
/// it parses but breaks a rule of the archive's templates (<see cref="TemplateRules"/>), the rule follows after a colon
|
|
/// (<c>folderTemplate:reserved_folder</c>, <c>fileTemplate:file_separator</c>, <c>fileTemplate:extension</c>,
|
|
/// <c>fileTemplate:not_unique</c>) and the message says why in the request's language, as the desktop's fields do
|
|
/// (<c>Errors.Template.<Rule></c>); otherwise the message is that the template is not valid.
|
|
/// </summary>
|
|
private static IResult InvalidTemplate(HttpContext context, TemplateProblem problem)
|
|
{
|
|
if (problem.Rule is not { } rule) return ApiErrors.BadRequest(context, "invalid_template", problem.Field);
|
|
var message = Loc.Get("Errors.Template." + rule, RequestCulture.Of(context)) ?? ApiErrors.Message(context, "invalid_template");
|
|
var wire = string.Concat(rule.Select((c, i) => char.IsUpper(c) ? (i > 0 ? "_" : string.Empty) + char.ToLowerInvariant(c) : c.ToString()));
|
|
return Results.Json(new ApiError("invalid_template", message, $"{problem.Field}:{wire}"), ProtocolJson.Default.ApiError,
|
|
statusCode: StatusCodes.Status400BadRequest);
|
|
}
|
|
|
|
/// <summary>The dry run as the API answers it, with each reason something stays as it is in the request's language.</summary>
|
|
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
|
|
{
|
|
var culture = RequestCulture.Of(context);
|
|
return new ReorganizePlanDto(
|
|
[.. plan.Steps.Select(s => new ReorganizeStepDto(s.SequenceId, s.FromFolder, s.ToFolder, s.FromTitle, s.ToTitle, s.Carried, s.FramesVersion,
|
|
s.FileChanges, [.. s.FileSamples.Select(f => new ReorganizeFileDto(f.From, f.To))],
|
|
[.. s.Blocked.Select(b => new ReorganizeBlockedDto(Wire(b.Reason), b.Frames, Loc.Get("Archive.Reorganize.Blocked." + b.Reason, culture) ?? Wire(b.Reason)))]))],
|
|
plan.Steps.Count(s => s.Changes),
|
|
plan.Steps.Sum(s => s.FileChanges),
|
|
plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames)),
|
|
fingerprint);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Wire name of a reason something stays as it is: photos that keep their names (<c>in_place</c>, <c>unhashed</c>,
|
|
/// <c>missing</c>), or the whole sequence (<c>unreadable</c>).
|
|
/// </summary>
|
|
public static string Wire(RenameBlock reason) => reason switch
|
|
{
|
|
RenameBlock.InPlace => "in_place",
|
|
RenameBlock.Unhashed => "unhashed",
|
|
RenameBlock.Missing => "missing",
|
|
_ => "unreadable",
|
|
};
|
|
|
|
private static async Task<IResult> EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind)
|
|
{
|
|
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
|
var job = await host.Engine.EnqueueAsync(kind, [archive.Id], archive.Current.Name, priority: JobPriority.User, createdBy: caller.Id,
|
|
cancellationToken: context.RequestAborted);
|
|
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), JobWire.Kind(kind));
|
|
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
|
}
|
|
|
|
private static ArchiveSettingsDto Settings(Archive a) => new(a.Id, a.Name, a.RootPath, a.FolderTemplate, a.FileTemplate, a.ProxyLongEdge);
|
|
}
|