Owner review 2, R7 asks for renaming and moving after import, on the web panel and the desktop. This is the engine and the server API both UIs build on. - FrameNaming (Core/Naming) is the one naming context and unique-name rule of a frame: imports, uploads and Reorganize now produce identical names (behaviour of the ingest and the import planner unchanged). - RenamePlanner takes a file template: each step counts its renamed frames, shows the first three and the frames version they were planned at, and lists what keeps its name (photos in place outside originals/, never hashed, missing, unreadable sidecar). Names are given in index order with _2, _3 as filing does; XMP companions follow their photo. - MassRenamer renames a step's files under the same leases after its folder moved, checks the frames version, journals .chronos/rename-files.json and moves files in two phases through temporary names so chains and swaps never meet; then sidecar, index (FrameRepository.RenameFilesAsync, both dialects) and journal. A failure puts every file back; a crash is completed by the next writer or the plan's resume, the index following. Plans a paused or cancelled job holds are left to that job. - JobKind.Move gets MoveJobHandler: it plans again and applies only the confirmed plan (fingerprint and frames versions), with progress and checkpoints per sequence. - POST /api/v1/archive/reorganize: dry run with the plan and its fingerprint, otherwise a 202 move job; validated templates, audited, sequenceChanged reorganized events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit aae1c3eb18ea932b4a6251c5e2a282b9295a5785)
154 lines
7.5 KiB
C#
154 lines
7.5 KiB
C#
using System.Collections.Concurrent;
|
||
using Chronos.Core.Archiving;
|
||
using Chronos.Core.Imaging;
|
||
|
||
namespace Chronos.Data.Archiving;
|
||
|
||
/// <summary>Settings shared by the archive services.</summary>
|
||
public sealed record ArchiveServiceOptions
|
||
{
|
||
/// <summary>Decoders for thumbnails and proxies beyond embedded previews and JPEG (WIC on Windows).</summary>
|
||
public ImageDecoder Decoder { get; init; } = new([]);
|
||
|
||
/// <summary>Name written into lease files so a waiting writer can say who holds a sequence.</summary>
|
||
public string Owner { get; init; } = "chronos@" + Environment.MachineName;
|
||
|
||
/// <summary>How long a writer waits for a sequence held by another process before giving up.</summary>
|
||
public TimeSpan LeaseWait { get; init; } = TimeSpan.FromMinutes(2);
|
||
|
||
public TimeSpan LeaseDuration { get; init; } = LeaseFile.DefaultDuration;
|
||
|
||
/// <summary>
|
||
/// Scans queue thumbnails and proxies of the sequences they index without them, as an upload does (the server, whose
|
||
/// clients load both from it: BRIEF §4.3, §14.4). The desktop decodes its thumbnails on demand and makes proxies when
|
||
/// asked.
|
||
/// </summary>
|
||
public bool ImagesAfterScan { get; init; }
|
||
|
||
/// <summary>
|
||
/// Photos a pass works on at once, asked at the start of each sequence (owner review 1, R2: one job runs at a time and
|
||
/// the host's parallelism decides how many photos it processes at once; Settings › Rendering › Parallelism on the
|
||
/// desktop, <c>CHRONOS_PARALLELISM</c> on the server). Default: half the logical cores.
|
||
/// </summary>
|
||
public Func<int> Parallelism { get; init; } = () => DefaultParallelism;
|
||
|
||
/// <summary>
|
||
/// Memory the photos a proxy pass decodes at once may take, in bytes, asked with <see cref="Parallelism"/>: fewer at once
|
||
/// for large originals. Default: a quarter of the memory available, at least 1 GiB.
|
||
/// </summary>
|
||
public Func<long> MemoryBudget { get; init; } = () => DefaultMemoryBudget;
|
||
|
||
/// <summary>
|
||
/// The host's own clean-up steps (the server's uploads sweep, the desktop's cache trim), run by
|
||
/// <see cref="Core.Model.JobKind.Cleanup"/> jobs after the shared ones of <see cref="Housekeeping.CleanupSteps"/> when a
|
||
/// schedule names them (owner review 2, R10). A name the shared steps use already is ignored.
|
||
/// </summary>
|
||
public IReadOnlyList<Housekeeping.ICleanupStep> CleanupSteps { get; init; } = [];
|
||
|
||
/// <summary>
|
||
/// Folder of the copies <see cref="Core.Model.JobKind.Backup"/> jobs make; null: the <c>backups</c> folder next to the
|
||
/// SQLite index (<see cref="DatabaseBackups.DefaultDirectory"/>), where the desktop and the server keep them.
|
||
/// </summary>
|
||
public string? BackupDirectory { get; init; }
|
||
|
||
/// <summary>
|
||
/// Told after a job changed a sequence's folder, title or file names (change <c>reorganized</c>, a Reorganize): a server
|
||
/// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job.
|
||
/// </summary>
|
||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||
|
||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||
|
||
/// <summary>A quarter of the memory available to this process, at least 1 GiB.</summary>
|
||
public static long DefaultMemoryBudget => Math.Max(1L << 30, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 4);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Read-modify-write of sidecars, serialised per sequence: an in-process gate for this process's writers plus a lease
|
||
/// file for writers in other processes on the same share (server and client). Every edit sees the latest sidecar,
|
||
/// with an interrupted ingest batch completed first.
|
||
/// </summary>
|
||
internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||
{
|
||
private readonly ConcurrentDictionary<Guid, SemaphoreSlim> _gates = new();
|
||
|
||
public ArchiveServiceOptions Options => options;
|
||
|
||
/// <summary>Holds the sequence exclusively until disposed.</summary>
|
||
public async Task<IAsyncDisposable> LockAsync(ArchivePaths archive, Guid sequenceId, CancellationToken cancellationToken)
|
||
{
|
||
var gate = _gates.GetOrAdd(sequenceId, _ => new SemaphoreSlim(1, 1));
|
||
await gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||
try
|
||
{
|
||
var lease = await LeaseFile.AcquireAsync(archive.LocksDirectory, $"seq-{sequenceId:N}", options.Owner, options.LeaseWait,
|
||
options.LeaseDuration, cancellationToken).ConfigureAwait(false);
|
||
return new Held(gate, lease);
|
||
}
|
||
catch
|
||
{
|
||
gate.Release();
|
||
throw;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (<see cref="FileRenameJournal"/>),
|
||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||
/// trash (<see cref="FrameRestoreJournal"/>; left for later while its trash entry is busy) and completing an interrupted
|
||
/// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the
|
||
/// next scan reads it.
|
||
/// </summary>
|
||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId, string? heldEntryLease = null)
|
||
{
|
||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||
if (manifest.Id != sequenceId)
|
||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||
if (File.Exists(sequence.FileRenameJournalPath))
|
||
{
|
||
if (FileRenameJournal.Recover(sequence, manifest) is { } renamed)
|
||
{
|
||
ManifestStore.WriteSequence(sequence.ManifestPath, renamed);
|
||
manifest = renamed;
|
||
}
|
||
FileRenameJournal.Delete(sequence);
|
||
}
|
||
FrameRemovalJournal.Recover(sequence, manifest);
|
||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||
{
|
||
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
|
||
manifest = recovered;
|
||
}
|
||
IngestJournal.Delete(sequence);
|
||
return manifest;
|
||
}
|
||
|
||
/// <summary>Applies <paramref name="edit"/> to the sidecar under the lock; a null result writes nothing.</summary>
|
||
public async Task<SequenceManifest> UpdateAsync(ArchivePaths archive, Guid sequenceId, string folder,
|
||
Func<SequenceManifest, SequenceManifest?> edit, CancellationToken cancellationToken)
|
||
{
|
||
var sequence = archive.Sequence(folder);
|
||
await using (await LockAsync(archive, sequenceId, cancellationToken).ConfigureAwait(false))
|
||
{
|
||
var manifest = ReadLocked(sequence, sequenceId);
|
||
if (edit(manifest) is not { } updated) return manifest;
|
||
ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||
return updated;
|
||
}
|
||
}
|
||
|
||
private sealed class Held(SemaphoreSlim gate, LeaseFile lease) : IAsyncDisposable
|
||
{
|
||
public ValueTask DisposeAsync()
|
||
{
|
||
lease.Dispose();
|
||
gate.Release();
|
||
return ValueTask.CompletedTask;
|
||
}
|
||
}
|
||
}
|