Skip to content

Commit 6670bee

Browse files
shanselmanCopilot
andcommitted
fix(shared): keep reconnect ownership after stale websocket races
Guard reconnect loops so failed retries and closing current sockets do not strand the websocket client while still avoiding active newer sockets. Co-authored-by: Copilot <[email protected]>
1 parent 121947c commit 6670bee

2 files changed

Lines changed: 92 additions & 2 deletions

File tree

‎src/OpenClaw.Shared/WebSocketClientBase.cs‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,14 @@ protected async Task ReconnectWithBackoffAsync(
359359
DisposeStaleSocket(oldSocket);
360360
}
361361

362+
var currentSocket = _webSocket;
363+
if (currentSocket != null
364+
&& !ReferenceEquals(currentSocket, oldSocket)
365+
&& IsSocketClosingOrClosed(currentSocket))
366+
{
367+
DisposeStaleSocket(currentSocket);
368+
}
369+
362370
await ConnectAsync();
363371

364372
if (IsConnected)
@@ -380,8 +388,22 @@ protected async Task ReconnectWithBackoffAsync(
380388
}
381389
}
382390

383-
private bool IsReconnectOwner(ClientWebSocket? expectedSocket, long expectedGeneration) =>
384-
expectedSocket is null || IsCurrentConnection(expectedSocket, expectedGeneration);
391+
private bool IsReconnectOwner(ClientWebSocket? expectedSocket, long expectedGeneration)
392+
{
393+
if (expectedSocket is null || IsCurrentConnection(expectedSocket, expectedGeneration))
394+
{
395+
return true;
396+
}
397+
398+
var currentSocket = _webSocket;
399+
return currentSocket is null || IsSocketClosingOrClosed(currentSocket);
400+
}
401+
402+
private static bool IsSocketClosingOrClosed(ClientWebSocket ws) =>
403+
ws.State is WebSocketState.CloseReceived
404+
or WebSocketState.CloseSent
405+
or WebSocketState.Closed
406+
or WebSocketState.Aborted;
385407

386408
/// <summary>Send a text message over the WebSocket. Thread-safe.</summary>
387409
protected async Task SendRawAsync(string message)

‎tests/OpenClaw.Shared.Tests/WebSocketClientBaseTests.cs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,67 @@ await WaitForConditionAsync(
352352
client.Dispose();
353353
}
354354

355+
[Fact]
356+
public async Task ReconnectBackoff_ContinuesAfterFailedRetry_WhenNoNewerConnectionOwnsSocket()
357+
{
358+
using var server = new LoopbackWebSocketServer();
359+
await server.StartAsync();
360+
var client = new ReconnectBackoffRaceClient(server.WebSocketUrl, "token", _logger);
361+
var statuses = new ConcurrentQueue<ConnectionStatus>();
362+
client.StatusChanged += (_, s) => statuses.Enqueue(s);
363+
364+
await client.ConnectAsync();
365+
await client.FirstConnected.WaitAsync(TimeSpan.FromSeconds(2));
366+
await WaitForConditionAsync(() => server.AcceptedCount >= 1, TimeSpan.FromSeconds(2));
367+
368+
await server.CloseSocketAsync(0);
369+
server.StopAccepting();
370+
371+
await WaitForConditionAsync(
372+
() => statuses.Count(s => s == ConnectionStatus.Connecting) >= 4,
373+
TimeSpan.FromSeconds(4));
374+
375+
Assert.Equal(1, client.OnConnectedCallCount);
376+
Assert.True(_logger.Logs.Count(
377+
line => line.Contains("reconnecting in", StringComparison.OrdinalIgnoreCase)) >= 2);
378+
379+
client.Dispose();
380+
}
381+
382+
[Fact]
383+
public async Task ReconnectBackoff_ReconnectsCurrentClosingSocket_WhenSupersededLoopIsActive()
384+
{
385+
using var server = new LoopbackWebSocketServer();
386+
await server.StartAsync();
387+
var client = new ReconnectBackoffRaceClient(server.WebSocketUrl, "token", _logger);
388+
var statuses = new ConcurrentQueue<ConnectionStatus>();
389+
client.StatusChanged += (_, s) => statuses.Enqueue(s);
390+
391+
await client.ConnectAsync();
392+
await client.FirstConnected.WaitAsync(TimeSpan.FromSeconds(2));
393+
await WaitForConditionAsync(() => server.AcceptedCount >= 1, TimeSpan.FromSeconds(2));
394+
395+
await server.CloseSocketAsync(0);
396+
await WaitForConditionAsync(
397+
() => statuses.Count(s => s == ConnectionStatus.Connecting) >= 2,
398+
TimeSpan.FromSeconds(2));
399+
400+
await client.ConnectAsync();
401+
await client.SecondConnected.WaitAsync(TimeSpan.FromSeconds(2));
402+
await WaitForConditionAsync(() => server.AcceptedCount >= 2, TimeSpan.FromSeconds(2));
403+
404+
await server.CloseSocketAsync(1);
405+
406+
var reconnect = await Task.WhenAny(
407+
client.ThirdConnected,
408+
Task.Delay(TimeSpan.FromSeconds(3)));
409+
410+
Assert.Same(client.ThirdConnected, reconnect);
411+
Assert.True(server.AcceptedCount >= 3);
412+
413+
client.Dispose();
414+
}
415+
355416
private static async Task WaitForConditionAsync(Func<bool> predicate, TimeSpan timeout)
356417
{
357418
var start = DateTime.UtcNow;
@@ -532,6 +593,13 @@ await socket.CloseOutputAsync(
532593
}
533594
}
534595

596+
public void StopAccepting()
597+
{
598+
_cts.Cancel();
599+
try { _listener.Stop(); } catch { }
600+
try { _acceptLoop?.Wait(TimeSpan.FromSeconds(1)); } catch { }
601+
}
602+
535603
public void Dispose()
536604
{
537605
_cts.Cancel();

0 commit comments

Comments
 (0)