using System.Collections.Concurrent;
using System.Threading.Channels;
using Chronos.Core.Archiving;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
namespace Chronos.Server.Storage;
///
/// Brings a sequence's projects in step soon after its settings were written outside the projects (owner review 2, R8): an
/// older client's or a desktop sync's PATCH /sequences/{id}, an analysis's Auto values, a conversion. Main takes them
/// as an external version at once (), and connected clients hear
/// projectChanged without waiting for the next project call, which would catch up all the same. Only a sequence that
/// has its Main project already: Main is made when the projects are first read, never for every sequence an analysis or a
/// sync touches. One sequence at a time in the background; a sequence asked for again while it waits is caught up once; one
/// another writer holds is tried again a few times, then left to that next call. Nothing happens without the archive engine
/// (a test host without it).
///
public sealed class ProjectCatchUp(IServiceProvider services, ILogger logger) : BackgroundService
{
/// The waits before each new try of a sequence another writer holds.
private static readonly TimeSpan[] Retries = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2)];
private readonly Channel<(Guid Id, int Attempt)> _queue = Channel.CreateUnbounded<(Guid Id, int Attempt)>(new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary _waiting = new();
private CancellationToken _stopping;
/// Catches the projects of up soon (at once when nothing waits).
public void Touch(Guid sequenceId) => Enqueue(sequenceId, 0);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_stopping = stoppingToken;
try
{
await foreach (var (id, attempt) in _queue.Reader.ReadAllAsync(stoppingToken))
{
_waiting.TryRemove(id, out _);
await CatchUpAsync(id, attempt, stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// The server stops: what waits is caught up by the next project call.
}
}
private void Enqueue(Guid id, int attempt)
{
if (_waiting.TryAdd(id, 0)) _queue.Writer.TryWrite((id, attempt));
}
private async Task CatchUpAsync(Guid id, int attempt, CancellationToken cancellationToken)
{
if (services.GetService() is not { } archives) return;
try
{
if (await services.GetRequiredService().Projects.GetMainAsync(id, cancellationToken) is null) return;
await archives.Projects.CatchUpAsync(id, cancellationToken);
}
catch (LeaseUnavailableException) when (attempt < Retries.Length)
{
_ = RetryLaterAsync(id, attempt);
}
catch (Exception ex) when (ex is ProjectException or ArchiveOfflineException or SequenceFolderMovedException or LeaseUnavailableException)
{
// The sequence is gone, its archive offline or its folder elsewhere, or it stayed busy: the next project call catches up.
logger.LogDebug("The projects of sequence {Sequence} are caught up later: {Reason}", id, ex.Message);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "The projects of sequence {Sequence} could not be caught up", id);
}
}
private async Task RetryLaterAsync(Guid id, int attempt)
{
try
{
await Task.Delay(Retries[attempt], _stopping);
Enqueue(id, attempt + 1);
}
catch (OperationCanceledException)
{
// Stopping.
}
}
}