using Chronos.Core.Archiving;
using Chronos.Data.Repositories;
namespace Chronos.Server.Api;
///
/// Reorganize's dry runs kept a short while (owner review 2, R7): the same dry run asked again, and the confirmation that
/// follows it, take the plan made then instead of reading every sidecar and photo folder of the selection again (with
/// all, of the whole archive), while the archive's index is as it was then
/// () and for at most . A change made on disk alone,
/// which the index does not have, is not seen by a kept plan: the move job plans again and refuses a plan that no
/// longer matches the archive, so nothing changes that the dry run did not show.
///
public sealed class ReorganizePlanCache(TimeProvider time)
{
/// How long a plan is kept, from when its planning started.
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
/// Plans kept at most (a plan of every sequence holds one step per sequence); the oldest goes first.
public const int Capacity = 8;
private readonly Lock _gate = new();
private readonly Dictionary _plans = [];
///
/// What a plan is kept by: the archive, the stamp of its index, the sequences (all of them, or the ids in the order
/// given, which decides the folder that gets " (2)") and the templates.
///
public readonly record struct Key(Guid ArchiveId, string Stamp, string Sequences, RenameTemplates Templates)
{
/// The sequences of the request; null for every sequence of the archive.
public static Key Of(Guid archiveId, string stamp, IReadOnlyList? sequenceIds, RenameTemplates templates) =>
new(archiveId, stamp, sequenceIds is null ? "*" : string.Join(',', sequenceIds.Select(id => id.ToString("N"))), templates);
}
///
/// The plan kept for , or the one makes now, then kept; a refusal
/// ( throws) is not kept.
///
public async Task GetOrPlanAsync(Key key, Func> plan)
{
ArgumentNullException.ThrowIfNull(plan);
DateTimeOffset started;
lock (_gate)
{
started = time.GetUtcNow();
Expire(started);
if (_plans.TryGetValue(key, out var kept)) return kept.Plan;
}
var made = await plan().ConfigureAwait(false);
lock (_gate)
{
if (!_plans.ContainsKey(key) && _plans.Count >= Capacity) _plans.Remove(_plans.MinBy(p => p.Value.Started).Key);
_plans[key] = (made, started);
}
return made;
}
/// Forgets the plan kept for : its job is queued, and what the job changes gives the index another stamp.
public void Forget(Key key)
{
lock (_gate) _plans.Remove(key);
}
private void Expire(DateTimeOffset now)
{
foreach (var key in _plans.Where(p => now - p.Value.Started >= Lifetime).Select(p => p.Key).ToList()) _plans.Remove(key);
}
}