Files
ucvl-zonghengjia-open-source/windows/StartupLearningWarmup.cs
T

68 lines
2.8 KiB
C#
Raw Permalink Normal View History

namespace UCVL.VPNPlus;
internal static class StartupLearningWarmup
{
// The readiness callback starts only transport learning. The setup owner
// keeps its lifecycle lock until DNS/network setup succeeds; rule commits
// wait on that existing lock. Once setup is ready, learning continues in a
// bounded observed task and no longer delays the mandatory proxy proof.
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null,
Action<Exception?>? onBackgroundCompleted = null)
{
token.ThrowIfCancellationRequested();
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)
?? throw new InvalidOperationException("Startup learning did not return a task.");
});
token.ThrowIfCancellationRequested();
if (work is null)
{
learning?.Dispose();
budget.Dispose();
return;
}
learning!.Token.ThrowIfCancellationRequested();
budget.CancelAfter(TimeSpan.FromSeconds(15));
_ = ObserveBackgroundAsync(work, learning, budget, onBackgroundCompleted);
}
catch
{
// 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();
budget.Dispose();
throw;
}
}
private static async Task ObserveBackgroundAsync(Task work, CancellationTokenSource learning,
CancellationTokenSource budget, Action<Exception?>? onCompleted)
{
Exception? failure = null;
try
{
await work.ConfigureAwait(false);
}
catch (OperationCanceledException) when (learning.IsCancellationRequested) { }
catch (Exception error) { failure = error; }
finally
{
try { learning.Cancel(); } catch { }
learning.Dispose();
budget.Dispose();
try { onCompleted?.Invoke(failure); } catch { }
}
}
}