|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Net.WebSockets; |
| 5 | +using System.Reflection; |
| 6 | +using System.Text; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using OpenClaw.TestSupport; |
| 10 | +using Xunit; |
| 11 | + |
| 12 | +namespace OpenClaw.Shared.Tests; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// Regression tests for the #1021 sibling sites: when the client-lifetime token is |
| 16 | +/// cancelled while a chat.send or exec.approval.resolve response is pending, the |
| 17 | +/// failure must surface as a cancellation, not as a gateway timeout. The |
| 18 | +/// wizard-request site has its own fix and tests (#1018). |
| 19 | +/// </summary> |
| 20 | +[Collection("WebSocketClientBase")] |
| 21 | +public sealed class GatewayRequestShutdownClassificationTests |
| 22 | +{ |
| 23 | + [Fact] |
| 24 | + public async Task SendChatMessage_ShutdownDuringWait_SurfacesCancellationNotTimeout() |
| 25 | + { |
| 26 | + using var server = new LoopbackWebSocketServer(); |
| 27 | + using var identity = new TempDirectory("gateway-shutdown-"); |
| 28 | + await server.StartAsync(); |
| 29 | + using var client = CreateClient(server, identity.Path); |
| 30 | + await ConnectAsync(client, server); |
| 31 | + |
| 32 | + // Start the request, then cancel the lifetime token only after the server has |
| 33 | + // observed the request frame — by then the request has passed its connectivity |
| 34 | + // guards and is parked on the response wait, so the cancelled timeout delay is |
| 35 | + // the only thing that can complete it. |
| 36 | + var requestTask = client.SendChatMessageAsync("hello", sessionKey: "agent:main:test"); |
| 37 | + await WaitForFrameContainingAsync(server, "chat.send", TimeSpan.FromSeconds(2)); |
| 38 | + CancelLifetime(client); |
| 39 | + |
| 40 | + var elapsed = Stopwatch.StartNew(); |
| 41 | + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask); |
| 42 | + Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(4), |
| 43 | + "shutdown must classify immediately instead of waiting out the 5s chat.send budget"); |
| 44 | + } |
| 45 | + |
| 46 | + [Fact] |
| 47 | + public async Task ResolveExecApproval_ShutdownDuringWait_SurfacesCancellationNotTimeout() |
| 48 | + { |
| 49 | + using var server = new LoopbackWebSocketServer(); |
| 50 | + using var identity = new TempDirectory("gateway-shutdown-"); |
| 51 | + await server.StartAsync(); |
| 52 | + using var client = CreateClient(server, identity.Path); |
| 53 | + await ConnectAsync(client, server); |
| 54 | + |
| 55 | + var requestTask = client.ResolveExecApprovalAsync("approval-1", "allow-once"); |
| 56 | + await WaitForFrameContainingAsync(server, "exec.approval.resolve", TimeSpan.FromSeconds(2)); |
| 57 | + CancelLifetime(client); |
| 58 | + |
| 59 | + var elapsed = Stopwatch.StartNew(); |
| 60 | + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask); |
| 61 | + Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(10), |
| 62 | + "shutdown must classify immediately instead of waiting out the 15s approval budget"); |
| 63 | + } |
| 64 | + |
| 65 | + // Guards the actual shutdown entry point: Dispose faults the pending completion |
| 66 | + // via ClearPendingRequests before cancelling the lifetime token, and that path |
| 67 | + // must never fabricate a gateway timeout either. The two tests above pin the |
| 68 | + // residual register-after-clear window, which a real Dispose cannot reach |
| 69 | + // deterministically precisely because of that ordering. |
| 70 | + [Fact] |
| 71 | + public async Task ResolveExecApproval_RealDisposeDuringWait_SurfacesCancellationNotTimeout() |
| 72 | + { |
| 73 | + using var server = new LoopbackWebSocketServer(); |
| 74 | + using var identity = new TempDirectory("gateway-shutdown-"); |
| 75 | + await server.StartAsync(); |
| 76 | + using var client = CreateClient(server, identity.Path); |
| 77 | + await ConnectAsync(client, server); |
| 78 | + |
| 79 | + var requestTask = client.ResolveExecApprovalAsync("approval-1", "allow-once"); |
| 80 | + await WaitForFrameContainingAsync(server, "exec.approval.resolve", TimeSpan.FromSeconds(2)); |
| 81 | + client.Dispose(); |
| 82 | + |
| 83 | + var elapsed = Stopwatch.StartNew(); |
| 84 | + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask); |
| 85 | + Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(10), |
| 86 | + "disposal must surface as cancellation instead of waiting out the 15s approval budget"); |
| 87 | + } |
| 88 | + |
| 89 | + [Fact] |
| 90 | + public async Task ResolveGatewayResponse_ResponseWinsWhenTerminalSignalCompletedFirst() |
| 91 | + { |
| 92 | + using var cancellation = new CancellationTokenSource(); |
| 93 | + var cancellationTask = Task.Delay(Timeout.InfiniteTimeSpan, cancellation.Token); |
| 94 | + cancellation.Cancel(); |
| 95 | + var responseTask = Task.FromResult(42); |
| 96 | + |
| 97 | + var result = await OpenClawGatewayClient.ResolveGatewayResponseAsync( |
| 98 | + responseTask, |
| 99 | + cancellationTask, |
| 100 | + cancellationTask, |
| 101 | + "must not time out"); |
| 102 | + |
| 103 | + Assert.Equal(42, result); |
| 104 | + } |
| 105 | + |
| 106 | + [Fact] |
| 107 | + public async Task ResolveGatewayResponse_TimeoutWinnerStaysTimeoutAfterLaterCancellation() |
| 108 | + { |
| 109 | + var response = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 110 | + var timeoutTask = Task.CompletedTask; |
| 111 | + using var cancellation = new CancellationTokenSource(); |
| 112 | + var cancellationTask = Task.Delay(Timeout.InfiniteTimeSpan, cancellation.Token); |
| 113 | + cancellation.Cancel(); |
| 114 | + |
| 115 | + var exception = await Assert.ThrowsAsync<TimeoutException>(() => |
| 116 | + OpenClawGatewayClient.ResolveGatewayResponseAsync( |
| 117 | + response.Task, |
| 118 | + timeoutTask, |
| 119 | + cancellationTask, |
| 120 | + "expected timeout")); |
| 121 | + |
| 122 | + Assert.Equal("expected timeout", exception.Message); |
| 123 | + } |
| 124 | + |
| 125 | + private static OpenClawGatewayClient CreateClient(LoopbackWebSocketServer server, string identityPath) |
| 126 | + => new(server.WebSocketUrl, "test-token", new TestLogger(), identityPath: identityPath); |
| 127 | + |
| 128 | + private static async Task ConnectAsync(OpenClawGatewayClient client, LoopbackWebSocketServer server) |
| 129 | + { |
| 130 | + await client.ConnectAsync(); |
| 131 | + var start = DateTime.UtcNow; |
| 132 | + while (server.AcceptedCount < 1) |
| 133 | + { |
| 134 | + if (DateTime.UtcNow - start > TimeSpan.FromSeconds(2)) |
| 135 | + throw new TimeoutException("Loopback server did not accept the connection."); |
| 136 | + |
| 137 | + // slopwatch-ignore: SW004 Test delay is an intentional bounded async wait; replacing it would change the scenario under test. |
| 138 | + await Task.Delay(25); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + /// <summary>Reads server-side frames (skipping the connect handshake traffic) until |
| 143 | + /// one contains the marker, proving the request frame reached the wire.</summary> |
| 144 | + private static async Task WaitForFrameContainingAsync( |
| 145 | + LoopbackWebSocketServer server, string marker, TimeSpan timeout) |
| 146 | + { |
| 147 | + var socket = GetAcceptedSocket(server); |
| 148 | + var buffer = new byte[64 * 1024]; |
| 149 | + using var cts = new CancellationTokenSource(timeout); |
| 150 | + while (true) |
| 151 | + { |
| 152 | + var message = new StringBuilder(); |
| 153 | + WebSocketReceiveResult result; |
| 154 | + do |
| 155 | + { |
| 156 | + result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token); |
| 157 | + if (result.MessageType != WebSocketMessageType.Text) |
| 158 | + throw new InvalidOperationException($"Unexpected {result.MessageType} frame before '{marker}'."); |
| 159 | + |
| 160 | + message.Append(Encoding.UTF8.GetString(buffer, 0, result.Count)); |
| 161 | + } while (!result.EndOfMessage); |
| 162 | + |
| 163 | + if (message.ToString().Contains(marker, StringComparison.Ordinal)) |
| 164 | + return; |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + // Models the shutdown race from #1021: the lifetime token is cancelled while this |
| 169 | + // request's pending completion has not been faulted — the state a request reaches |
| 170 | + // when it registers after ClearPendingRequests has already swept the pending maps. |
| 171 | + private static void CancelLifetime(OpenClawGatewayClient client) |
| 172 | + { |
| 173 | + var field = typeof(WebSocketClientBase).GetField( |
| 174 | + "_cts", BindingFlags.Instance | BindingFlags.NonPublic); |
| 175 | + Assert.NotNull(field); |
| 176 | + ((CancellationTokenSource)field!.GetValue(client)!).Cancel(); |
| 177 | + } |
| 178 | + |
| 179 | + private static WebSocket GetAcceptedSocket(LoopbackWebSocketServer server) |
| 180 | + { |
| 181 | + var field = typeof(LoopbackWebSocketServer).GetField( |
| 182 | + "_acceptedSockets", BindingFlags.Instance | BindingFlags.NonPublic); |
| 183 | + Assert.NotNull(field); |
| 184 | + var sockets = (List<WebSocket>)field!.GetValue(server)!; |
| 185 | + lock (sockets) |
| 186 | + { |
| 187 | + Assert.NotEmpty(sockets); |
| 188 | + return sockets[0]; |
| 189 | + } |
| 190 | + } |
| 191 | +} |
0 commit comments