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

186 lines
10 KiB
C#

using System.Text.Json;
namespace UCVL.VPNPlus;
// Exercises the production aggregator without HTTP, proxies or network changes.
internal static class NodeHealthProbeSelfTest
{
internal static async Task<int> RunAsync()
{
var checks = new Dictionary<string, bool>();
var errors = new Dictionary<string, string>();
async Task Check(string name, Func<Task> test)
{
try { await test(); checks[name] = true; }
catch (Exception error) { checks[name] = false; errors[name] = error.Message; }
}
await Check("http_status_and_codex_requirement_preserved", () => {
Require(NodeHealthProbe.Accepts(0, 200) && NodeHealthProbe.Accepts(0, 204)
&& !NodeHealthProbe.Accepts(0, 201) && !NodeHealthProbe.Accepts(0, 401)
&& NodeHealthProbe.Accepts(1, 401) && !NodeHealthProbe.Accepts(1, 500)
&& NodeHealthProbe.Accepts(2, 499) && !NodeHealthProbe.Accepts(2, 500), "HTTP status policy changed");
Require(NodeHealthProbe.OverallHealthy(new[] { true, false, true })
&& NodeHealthProbe.OverallHealthy(new[] { false, true, true })
&& !NodeHealthProbe.OverallHealthy(new[] { true, true, false })
&& !NodeHealthProbe.OverallHealthy(new[] { false, false, true }), "Codex health predicate changed");
return Task.CompletedTask;
});
await Check("google_and_codex_do_not_wait_for_api", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Required successes did not prove health");
Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled");
});
await Check("api_and_codex_do_not_wait_for_google", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Required successes did not prove health");
Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled");
});
await Check("codex_failure_finishes_with_other_probes_pending", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(false);
Require(!await Finished(result), "Codex failure must prove unhealthy");
Require(fixture.Cancellation.IsCancellationRequested, "Unneeded HTTP probes were not cancelled");
});
await Check("both_independent_failures_do_not_wait_for_codex", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(false); fixture.Api.SetResult(false);
Require(!await Finished(result), "No independent target can prove health");
});
await Check("google_and_api_success_still_waits_for_codex", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Api.SetResult(true);
await StillPending(result);
Require(!fixture.Cancellation.IsCancellationRequested, "Codex was cancelled before its verdict");
fixture.Codex.SetResult(false);
Require(!await Finished(result), "Independent successes cannot mask Codex failure");
});
await Check("codex_success_still_waits_for_independent_proof", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(true);
await StillPending(result);
fixture.Google.SetResult(false); await StillPending(result);
fixture.Api.SetResult(true);
Require(await Finished(result), "An eventual independent success must prove health");
});
await Check("critical_probe_exception_counts_as_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetException(new HttpRequestException("test failure"));
Require(!await Finished(result), "Failed Codex probe must prove unhealthy");
});
await Check("independent_exception_allows_other_independent_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetException(new HttpRequestException("test failure"));
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "One failed independent probe must not hide valid health");
});
await Check("two_independent_exceptions_prove_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetException(new IOException("test failure"));
fixture.Api.SetException(new HttpRequestException("test failure"));
Require(!await Finished(result), "Two failed independent probes must prove unhealthy");
});
await Check("caller_precancellation_is_preserved", async () => {
using var caller = new CancellationTokenSource(); caller.Cancel();
using var fixture = new Probes();
await Cancelled(fixture.Start(caller.Token), caller.Token);
Require(fixture.Cancellation.IsCancellationRequested, "Probe cleanup did not run after cancellation");
});
await Check("caller_cancellation_interrupts_pending_probes", async () => {
using var caller = new CancellationTokenSource();
using var fixture = new Probes();
var result = fixture.Start(caller.Token); caller.Cancel();
await Cancelled(result, caller.Token);
Require(fixture.Cancellation.IsCancellationRequested, "Pending HTTP probes were not cancelled");
});
await Check("late_failure_cannot_change_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established");
fixture.Api.SetException(new HttpRequestException("late unused failure"));
Require(await result, "Late unused failure changed a completed health verdict");
});
await Check("late_success_cannot_change_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(false);
Require(!await Finished(result), "Failure was not established");
fixture.Google.SetResult(true); fixture.Api.SetResult(true);
Require(!await result, "Late successes changed a completed health verdict");
});
await Check("late_caller_cancellation_cannot_change_success", async () => {
using var caller = new CancellationTokenSource();
using var fixture = new Probes();
var result = fixture.Start(caller.Token);
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established"); caller.Cancel();
Require(await result, "Later cancellation changed a completed health verdict");
});
await Check("cancelled_unused_probe_cannot_change_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established");
fixture.Google.SetCanceled(fixture.Cancellation.Token);
Require(await result, "Unused-probe cancellation changed the health verdict");
});
var passed = checks.Values.All(value => value);
var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false,
checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-health-probe-self-test.json"), report);
Console.WriteLine(report);
return passed ? 0 : 1;
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static async Task<bool> Finished(Task<bool> result)
{
try { return await result.WaitAsync(TimeSpan.FromSeconds(1)); }
catch (TimeoutException) { throw new InvalidOperationException("Health verdict waited for an unnecessary pending probe"); }
}
private static async Task StillPending(Task<bool> result)
{
var winner = await Task.WhenAny(result, Task.Delay(40));
Require(winner != result, "Health completed without required evidence");
}
private static async Task Cancelled(Task<bool> result, CancellationToken caller)
{
try { await result.WaitAsync(TimeSpan.FromSeconds(1)); }
catch (OperationCanceledException error) when (caller.IsCancellationRequested && error.CancellationToken == caller) { return; }
throw new InvalidOperationException("Caller cancellation did not propagate with its token");
}
private sealed class Probes : IDisposable
{
private Task<bool>? _running;
internal TaskCompletionSource<bool> Google { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal TaskCompletionSource<bool> Api { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal TaskCompletionSource<bool> Codex { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal CancellationTokenSource Cancellation { get; } = new();
internal Task<bool> Start(CancellationToken caller = default) => _running = NodeHealthProbe.AggregateAsync(
new[] { Google.Task, Api.Task, Codex.Task }, caller, Cancellation.Cancel);
public void Dispose()
{
Google.TrySetResult(false); Api.TrySetResult(false); Codex.TrySetResult(false);
if (_running is null) Cancellation.Dispose();
else _ = _running.ContinueWith(task => { _ = task.Exception; Cancellation.Dispose(); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
}