namespace Titano.Data.Processing;
///
/// Delivers the synchronous progress reports of the engine (analysis, render stages) to an asynchronous sink (job
/// context, render-node protocol) one after the other, in report order. Await before a
/// checkpoint or the end of the work to observe the deliveries.
///
internal sealed class ProgressChain(Func sink)
{
private readonly Lock _gate = new();
private Task _pending = Task.CompletedTask;
/// A progress receiver mapping its reports to done, total and message.
public IProgress For(Func map) => new Forward(this, map);
public Task FlushAsync()
{
lock (_gate) return _pending;
}
private void Post(long done, long total, string? message)
{
lock (_gate) _pending = AfterAsync(_pending, done, total, message);
}
private async Task AfterAsync(Task previous, long done, long total, string? message)
{
await previous.ConfigureAwait(false);
await sink(done, total, message).ConfigureAwait(false);
}
private sealed class Forward(ProgressChain chain, Func map) : IProgress
{
public void Report(T value)
{
var (done, total, message) = map(value);
chain.Post(done, total, message);
}
}
}