namespace UCVL.VPNPlus; internal static class TailnetEndpointConfirmationSelfTest { internal static async Task> CheckAsync() { var checks = new Dictionary(); var calls = 0; var reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 2), CancellationToken.None); checks["first_fast_tcp_failure_followed_by_success_is_reachable"] = reachable && calls == 2; calls = 0; reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 3), CancellationToken.None); checks["two_fast_tcp_failures_followed_by_success_do_not_switch"] = reachable && calls == 3; calls = 0; reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => { calls++; return Task.FromResult(false); }, CancellationToken.None); checks["three_fast_tcp_failures_are_one_failed_round"] = !reachable && calls == 3; calls = 0; reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => ++calls == 1 ? Task.FromException(new IOException("fixture TCP failure")) : Task.FromResult(true), CancellationToken.None); checks["one_tcp_exception_does_not_force_fallback"] = reachable && calls == 2; calls = 0; reachable = await TailnetEndpointConfirmation.ProbeAsync(async token => { calls++; await Task.Delay(TimeSpan.FromMilliseconds(4_300), token); return true; }, CancellationToken.None); checks["slow_tcp_connection_can_succeed_within_first_probe_budget"] = reachable && calls == 1; calls = 0; reachable = await TailnetEndpointConfirmation.ProbeAsync(token => { calls++; token.WaitHandle.WaitOne(TimeSpan.FromSeconds(2)); return Task.FromResult(false); }, CancellationToken.None, TimeSpan.FromMilliseconds(30)); checks["expired_tcp_round_does_not_start_another_attempt"] = !reachable && calls == 1; var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => pending.Task, CancellationToken.None, TimeSpan.FromMilliseconds(30)); checks["uncooperative_tcp_callback_has_bounded_deadline"] = !reachable; using var caller = new CancellationTokenSource(); caller.Cancel(); var cancelled = false; try { await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(true), caller.Token); } catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; } checks["caller_cancellation_is_not_a_failed_tcp_probe"] = cancelled; using var race = new CancellationTokenSource(); cancelled = false; try { await TailnetEndpointConfirmation.ProbeAsync(_ => { race.Cancel(); return Task.FromResult(true); }, race.Token); } catch (OperationCanceledException error) { cancelled = error.CancellationToken == race.Token; } checks["cancelled_successful_tcp_probe_cannot_publish_old_result"] = cancelled; return checks; } }