using System.Diagnostics;
namespace Febe.Tests.Support;
///
/// Waits by condition and timings that a loaded runner does not fail by chance (#46). A wait returns as soon as its
/// condition holds; its limit only bounds a hang, so it is generous. A timing keeps the best of repeated runs: load only
/// adds time, so the minimum is the cost of the operation itself.
///
internal static class TestWait
{
/// The default hang guard of a condition wait.
public static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
/// Polls until it holds; fails with after the limit.
public static Task UntilAsync(Func condition, string what, TimeSpan? limit = null, CancellationToken ct = default) =>
UntilAsync(() => Task.FromResult(condition()), what, limit, ct);
/// Polls until it holds; fails with after the limit.
public static async Task UntilAsync(Func> condition, string what, TimeSpan? limit = null, CancellationToken ct = default)
{
var patience = limit ?? Patience;
var watch = Stopwatch.StartNew();
while (!await condition())
{
if (watch.Elapsed > patience)
{
Assert.Fail($"Tempo scaduto ({patience.TotalSeconds:0} s): {what}.");
}
await Task.Delay(20, ct);
}
}
///
/// Times after one warm-up run, at least three times and then until the best time is under
/// or the budget ( runs, of wall time)
/// runs out. A load spike only delays the result; an operation that is really slower stays over the bound.
///
public static async Task> BestTimeAsync(
Func> run, double boundMs, int maxRuns = 15, TimeSpan? budget = null, CancellationToken ct = default)
{
var limit = budget ?? TimeSpan.FromSeconds(20);
var result = await run(); // warm the caches
var best = double.MaxValue;
var runs = 0;
var wall = Stopwatch.StartNew();
while (runs < 3 || (best >= boundMs && runs < maxRuns && wall.Elapsed < limit))
{
ct.ThrowIfCancellationRequested();
if (runs >= 3)
{
await Task.Delay(100, ct); // let a burst of load pass before trying again
}
var watch = Stopwatch.StartNew();
result = await run();
best = Math.Min(best, watch.Elapsed.TotalMilliseconds);
runs++;
}
return new Timing(best, runs, result);
}
}
/// The best time of , how many runs it took and the last result.
internal readonly record struct Timing(double BestMs, int Runs, T Result);