39 lines
1.7 KiB
C#
39 lines
1.7 KiB
C#
namespace UCVL.VPNPlus;
|
|
|
|
internal static class StartupLearningWarmup
|
|
{
|
|
// The readiness callback starts only transport proof. The setup owner keeps
|
|
// its lifecycle lock until DNS/network setup succeeds; rule commits wait on
|
|
// that existing lock. Setup time never spends the post-setup learning budget.
|
|
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
|
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null)
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
using var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
|
CancellationTokenSource? learning = null;
|
|
Task? work = null;
|
|
try
|
|
{
|
|
await setup(epoch => {
|
|
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
|
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
|
learning.Token.ThrowIfCancellationRequested();
|
|
work = learn(learning.Token);
|
|
});
|
|
token.ThrowIfCancellationRequested();
|
|
if (work is null) return;
|
|
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
|
await work;
|
|
token.ThrowIfCancellationRequested();
|
|
}
|
|
finally
|
|
{
|
|
// A failed setup must leave no outstanding proof/commit task. Drain
|
|
// cancellation without replacing the original setup/learning error.
|
|
learning?.Cancel();
|
|
if (work is not null) try { await work; } catch { }
|
|
learning?.Dispose();
|
|
}
|
|
}
|
|
}
|