using Titano.Core.Project;
namespace Titano.App.Editor;
///
/// Writes the editor's project shortly after the last change: one write at a time, always the newest project, never
/// cancelled half way (a write is a file plus an index row). A failed write keeps the project pending and is retried
/// with a growing delay (2 s doubling up to ) until it is stored, so nothing is dropped
/// while the archive is offline or busy. skips the wait and reports whether everything is
/// stored after one more attempt. Runs on the context that scheduled the first write (the UI thread).
///
public sealed class ProjectSaver(Func save, TimeSpan delay)
{
public static readonly TimeSpan MaxRetryDelay = TimeSpan.FromMinutes(1);
private readonly Lock _gate = new();
private readonly List> _flushes = [];
private ProjectSettings? _pending;
private bool _running;
private bool _flushRequested;
private int _failures;
private CancellationTokenSource? _wait;
/// A write failed: the exception and how many writes in a row failed (1 for the first of a streak).
public event Action? Failed;
/// A change waits for its write, is being written, or failed and waits for its retry.
public bool HasPendingChanges
{
get
{
lock (_gate) return _running;
}
}
/// Why the pending change could not be stored; null when the last write succeeded.
public Exception? LastError { get; private set; }
public void Schedule(ProjectSettings project)
{
ArgumentNullException.ThrowIfNull(project);
TaskCompletionSource start;
lock (_gate)
{
_pending = project;
if (_running) return;
_running = true;
start = new TaskCompletionSource();
_ = LoopAsync(start.Task);
}
// The loop starts outside the lock: with nothing to wait for it would otherwise save while holding it.
start.SetResult();
}
/// Stores what is pending now, without the delay.
/// True when everything is stored; false when the attempt failed (the change stays pending and is retried).
public Task FlushAsync()
{
lock (_gate)
{
if (!_running) return Task.FromResult(true);
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_flushes.Add(done);
_flushRequested = true;
_wait?.Cancel();
return done.Task;
}
}
private async Task LoopAsync(Task started)
{
await started;
var wait = delay;
while (true)
{
CancellationTokenSource? timer = null;
lock (_gate)
{
if (!_flushRequested && wait > TimeSpan.Zero) timer = _wait = new CancellationTokenSource();
}
if (timer is not null)
{
try
{
await Task.Delay(wait, timer.Token);
}
catch (OperationCanceledException)
{
}
lock (_gate) _wait = null;
timer.Dispose();
}
ProjectSettings next;
lock (_gate)
{
_flushRequested = false;
if (_pending is null)
{
_running = false;
Complete(true);
return;
}
next = _pending;
_pending = null;
}
int failures;
try
{
await save(next);
lock (_gate) _failures = 0;
LastError = null;
// A change made during the write is written right after it.
wait = TimeSpan.Zero;
continue;
}
catch (Exception ex)
{
lock (_gate)
{
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
_pending ??= next;
failures = ++_failures;
Complete(false);
}
LastError = ex;
wait = TimeSpan.FromSeconds(double.Min(MaxRetryDelay.TotalSeconds, double.Pow(2, failures)));
Failed?.Invoke(ex, failures);
}
}
}
private void Complete(bool stored)
{
foreach (var flush in _flushes) flush.TrySetResult(stored);
_flushes.Clear();
}
}