diff --git a/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs new file mode 100644 index 0000000..27488c3 --- /dev/null +++ b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Net.Sockets; +using PhoneBox.Agent; +using Xunit; + +public sealed class QuotaConnectTests +{ + [Fact] + public void Ipv4AddressesAreTriedBeforeIpv6ButKeepTheirOrder() + { + // api.anthropic.com resolves to an IPv6 address first; on networks where IPv6 is advertised but not + // routable, .NET failed with "Socket is not connected" instead of using the IPv4 address after it. + var addresses = new[] + { + IPAddress.Parse("2607:6bc0::10"), IPAddress.Parse("160.79.104.10"), + IPAddress.Parse("fe80::1"), IPAddress.Parse("10.0.0.2"), + }; + + var ordered = QuotaMonitor.Ipv4First(addresses).Select(a => a.ToString()).ToArray(); + + Assert.Equal(["160.79.104.10", "10.0.0.2", "2607:6bc0::10", "fe80::1"], ordered); + } + + [Fact] + public async Task ConnectsToAnIpv4Listener() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var accept = listener.AcceptTcpClientAsync(); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await using var stream = await QuotaMonitor.ConnectIpv4First(new DnsEndPoint("127.0.0.1", port), cts.Token); + using var server = await accept; + + await stream.WriteAsync(new byte[] { 42 }, cts.Token); + var buffer = new byte[1]; + Assert.Equal(1, await server.GetStream().ReadAsync(buffer, cts.Token)); + Assert.Equal(42, buffer[0]); + } + + [Fact] + public async Task FailsWithAnHttpErrorWhenNothingListens() + { + var free = new TcpListener(IPAddress.Loopback, 0); + free.Start(); + var port = ((IPEndPoint)free.LocalEndpoint).Port; + free.Stop(); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await Assert.ThrowsAsync(async () => + await QuotaMonitor.ConnectIpv4First(new DnsEndPoint("127.0.0.1", port), cts.Token)); + } + + [Fact] + public async Task DeadAddressesLeaveTimeForTheLastOne() + { + // three addresses that never answer, then one that does: before, each took a fixed share of the request + // timeout, so the working one was never reached. Every address is IPv4 so the order stays as given. + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var addresses = new[] + { + IPAddress.Parse("10.255.255.1"), IPAddress.Parse("10.255.255.2"), IPAddress.Parse("10.255.255.3"), IPAddress.Loopback, + }; + var tried = new List(); + + var budget = TimeSpan.FromSeconds(4); + var clock = System.Diagnostics.Stopwatch.StartNew(); + await using var stream = await QuotaMonitor.ConnectInOrder(addresses, port, budget, async (socket, endpoint, token) => + { + tried.Add(endpoint.Address); + if (IPAddress.IsLoopback(endpoint.Address)) await socket.ConnectAsync(endpoint, token); + else await Task.Delay(Timeout.Infinite, token); // pending until this attempt's share of the budget ends + }, CancellationToken.None); + + Assert.Equal(addresses, tried); + Assert.InRange(clock.Elapsed, TimeSpan.Zero, budget); + } + + [Fact] + public async Task TheSocketIsDisposedWhenTheCallerCancels() + { + Socket? attempted = null; + var started = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + + var connecting = QuotaMonitor.ConnectInOrder([IPAddress.Loopback], 9, TimeSpan.FromSeconds(30), async (socket, _, token) => + { + attempted = socket; + started.SetResult(); + await Task.Delay(Timeout.Infinite, token); + }, cts.Token).AsTask(); + await started.Task; + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => connecting); + Assert.Throws(() => attempted!.Available); + } +} diff --git a/agent/PhoneBox.Agent/QuotaMonitor.cs b/agent/PhoneBox.Agent/QuotaMonitor.cs index 2276ae0..720afc9 100644 --- a/agent/PhoneBox.Agent/QuotaMonitor.cs +++ b/agent/PhoneBox.Agent/QuotaMonitor.cs @@ -1,5 +1,7 @@ using System.Globalization; +using System.Net; using System.Net.Http.Headers; +using System.Net.Sockets; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; @@ -33,7 +35,65 @@ public sealed partial class QuotaMonitor(ConfigStore config, ILogger log) : this(null!, log) { } private static readonly string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(15) }; + // IPv4 first: on networks where IPv6 is advertised but not routable, the default connect fails with + // "Socket is not connected" instead of falling back, which breaks the quota checks. + private readonly HttpClient _http = new(new SocketsHttpHandler { ConnectCallback = (ctx, ct) => ConnectIpv4First(ctx.DnsEndPoint, ct) }) + { + Timeout = TimeSpan.FromSeconds(15), + }; + + /// The addresses in the order to try them: IPv4 first, each family keeping its resolver order. + internal static IEnumerable Ipv4First(IEnumerable addresses) => + addresses.OrderBy(a => a.AddressFamily == AddressFamily.InterNetwork ? 0 : 1); + + /// Time all connect attempts of one request may use together; the request itself times out after 15 s. + internal static readonly TimeSpan ConnectBudget = TimeSpan.FromSeconds(10); + + internal static async ValueTask ConnectIpv4First(DnsEndPoint endpoint, CancellationToken ct) + { + var addresses = await Dns.GetHostAddressesAsync(endpoint.Host, ct); + return await ConnectInOrder(addresses, endpoint.Port, ConnectBudget, static (s, ep, t) => s.ConnectAsync(ep, t), ct); + } + + /// + /// Tries the addresses one after another, IPv4 first. Each attempt gets an equal share of the time that is left, + /// so dead addresses of one family can't use up the budget before the other family is tried. The socket of an + /// attempt is disposed on every exit that doesn't hand it to the returned stream. + /// + internal static async ValueTask ConnectInOrder(IReadOnlyCollection addresses, int port, TimeSpan budget, + Func connect, CancellationToken ct) + { + var ordered = Ipv4First(addresses).ToList(); + var clock = System.Diagnostics.Stopwatch.StartNew(); + Exception? last = null; + for (var i = 0; i < ordered.Count; i++) + { + var left = budget - clock.Elapsed; + if (left <= TimeSpan.Zero) break; + var ip = ordered[i]; + var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + var handedOver = false; + try + { + using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct); + attempt.CancelAfter(left / (ordered.Count - i)); + await connect(socket, new IPEndPoint(ip, port), attempt.Token); + var stream = new NetworkStream(socket, ownsSocket: true); + handedOver = true; + return stream; + } + catch (Exception ex) when (ex is SocketException or OperationCanceledException && !ct.IsCancellationRequested) + { + last = ex; + } + finally + { + if (!handedOver) socket.Dispose(); + } + } + ct.ThrowIfCancellationRequested(); + throw new HttpRequestException("Could not connect", last); + } private volatile QuotaProvider? _claude; private volatile QuotaProvider? _codex;