using System.Collections.Concurrent;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
namespace Titano.Data.Archiving;
/// Settings shared by the archive services.
public sealed record ArchiveServiceOptions
{
/// Decoders for thumbnails and proxies beyond embedded previews and JPEG (WIC on Windows).
public ImageDecoder Decoder { get; init; } = new([]);
/// Name written into lease files so a waiting writer can say who holds a sequence.
public string Owner { get; init; } = "titano@" + Environment.MachineName;
/// How long a writer waits for a sequence held by another process before giving up.
public TimeSpan LeaseWait { get; init; } = TimeSpan.FromMinutes(2);
public TimeSpan LeaseDuration { get; init; } = LeaseFile.DefaultDuration;
///
/// 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.
///
public bool ImagesAfterScan { get; init; }
}
///
/// 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.
///
internal sealed class SequenceWriter(ArchiveServiceOptions options)
{
private readonly ConcurrentDictionary _gates = new();
public ArchiveServiceOptions Options => options;
/// Holds the sequence exclusively until disposed.
public async Task 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;
}
}
///
/// Reads the sidecar of a locked sequence, completing an interrupted ingest batch first.
///
/// The sidecar in the folder belongs to another sequence.
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
{
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
if (manifest.Id != sequenceId)
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
{
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
manifest = recovered;
}
IngestJournal.Delete(sequence);
return manifest;
}
/// Applies to the sidecar under the lock; a null result writes nothing.
public async Task UpdateAsync(ArchivePaths archive, Guid sequenceId, string folder,
Func 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;
}
}
}