Skip to content

Commit e60efcb

Browse files
shanselmanCopilot
andcommitted
Fix websocket lifecycle responsiveness
Serialize outbound WebSocket sends, propagate connection cancellation, and move node invoke execution off the receive loop with bounded dispatch. Add regression coverage for send serialization, dispatch responsiveness, and lifecycle cancellation. Co-authored-by: Copilot <[email protected]>
1 parent d9e0c20 commit e60efcb

7 files changed

Lines changed: 459 additions & 67 deletions

File tree

‎src/OpenClaw.Connection/GatewayClientFactory.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public GatewayClientLifecycleAdapter(OpenClawGatewayClient client)
4646
public event EventHandler<ConnectionStatus>? StatusChanged;
4747
public event EventHandler<string>? AuthenticationFailed;
4848

49-
public Task ConnectAsync(CancellationToken ct) => _client.ConnectAsync();
49+
public Task ConnectAsync(CancellationToken ct) => _client.ConnectAsync(ct);
5050

5151
public void Dispose() => _client.Dispose();
5252
}

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,10 @@ private async Task ConnectCoreAsync(string? gatewayId = null)
254254
catch (OperationCanceledException) { }
255255
catch (Exception ex)
256256
{
257-
_logger.Error($"[ConnMgr] Connect failed: {ex.Message}");
257+
if (Interlocked.Read(ref _generation) == gen)
258+
{
259+
_logger.Error($"[ConnMgr] Connect failed: {ex.Message}");
260+
}
258261
}
259262
}, ct);
260263
}
@@ -276,6 +279,11 @@ public async Task DisconnectAsync()
276279
/// <summary>Core disconnect logic. Caller must hold <see cref="_transitionSemaphore"/>.</summary>
277280
private void DisconnectCore()
278281
{
282+
Interlocked.Increment(ref _generation);
283+
var oldCts = Interlocked.Exchange(ref _operationCts, null);
284+
oldCts?.Cancel();
285+
oldCts?.Dispose();
286+
279287
var prev = _stateMachine.Current.OverallState;
280288
DisposeActiveClient();
281289
_stateMachine.TryTransition(ConnectionTrigger.DisconnectRequested);
@@ -533,7 +541,7 @@ private async Task HandleHandshakeSucceededAsync(long gen)
533541
// Start node connection outside the semaphore to avoid deadlocks
534542
if (_nodeConnector != null && ShouldStartNodeConnection())
535543
{
536-
await StartNodeConnectionAsync();
544+
await StartNodeConnectionAsync(gen);
537545
}
538546
}
539547

@@ -653,7 +661,7 @@ void Handler(object? _, GatewayConnectionSnapshot s)
653661
StateChanged += Handler;
654662
try
655663
{
656-
var startAttempted = await StartNodeConnectionAsync();
664+
var startAttempted = await StartNodeConnectionAsync(Interlocked.Read(ref _generation));
657665

658666
if (!startAttempted)
659667
{
@@ -706,19 +714,26 @@ private bool ShouldStartNodeConnection()
706714
return _isNodeEnabled?.Invoke() ?? false;
707715
}
708716

709-
private async Task<bool> StartNodeConnectionAsync()
717+
private bool IsGenerationStale(long? generation)
718+
=> generation.HasValue && Interlocked.Read(ref _generation) != generation.Value;
719+
720+
private async Task<bool> StartNodeConnectionAsync(long? generation = null)
710721
{
711-
if (_nodeConnector == null || _activeGatewayRecordId == null || _activeIdentityPath == null) return false;
722+
if (IsGenerationStale(generation)) return false;
712723

713-
var record = _registry.GetById(_activeGatewayRecordId);
724+
var activeGatewayRecordId = _activeGatewayRecordId;
725+
var activeIdentityPath = _activeIdentityPath;
726+
if (_nodeConnector == null || activeGatewayRecordId == null || activeIdentityPath == null) return false;
727+
728+
var record = _registry.GetById(activeGatewayRecordId);
714729
if (record == null)
715730
{
716731
_logger.Warn("[ConnMgr] Cannot start node — gateway record not found");
717732
return false;
718733
}
719734

720735
// Use root identity path — clients always read/write from root, not per-gateway
721-
var nodeCredential = _credentialResolver.ResolveNode(record, _activeIdentityPath!);
736+
var nodeCredential = _credentialResolver.ResolveNode(record, activeIdentityPath);
722737
if (nodeCredential == null)
723738
{
724739
_logger.Warn("[ConnMgr] No node credential available — skipping node connection");
@@ -731,6 +746,7 @@ private async Task<bool> StartNodeConnectionAsync()
731746
await _transitionSemaphore.WaitAsync();
732747
try
733748
{
749+
if (IsGenerationStale(generation)) return false;
734750
_stateMachine.SetNodeEnabled(true);
735751
}
736752
finally
@@ -747,7 +763,9 @@ private async Task<bool> StartNodeConnectionAsync()
747763

748764
try
749765
{
750-
await _nodeConnector.ConnectAsync(nodeConnectUrl, nodeCredential, _activeIdentityPath,
766+
if (IsGenerationStale(generation)) return false;
767+
768+
await _nodeConnector.ConnectAsync(nodeConnectUrl, nodeCredential, activeIdentityPath,
751769
useV2Signature: _gatewayNeedsV2Signature);
752770
}
753771
catch (Exception ex)
@@ -809,6 +827,7 @@ private async void OnNodeStatusChanged(object? sender, ConnectionStatus status)
809827

810828
private async void OnNodePairingStatusChanged(object? sender, PairingStatusEventArgs e)
811829
{
830+
var handlerGeneration = Interlocked.Read(ref _generation);
812831
_diagnostics.Record("node", $"Node pairing: {e.Status}");
813832

814833
await _transitionSemaphore.WaitAsync();
@@ -871,7 +890,7 @@ private async void OnNodePairingStatusChanged(object? sender, PairingStatusEvent
871890
_lastAutoApprovedRequestId = e.RequestId;
872891
_diagnostics.Record("node", "Node pairing auto-approved — reconnecting node");
873892
await Task.Delay(1000); // brief delay for gateway to process
874-
await StartNodeConnectionAsync();
893+
await StartNodeConnectionAsync(handlerGeneration);
875894
}
876895
else
877896
{

‎src/OpenClaw.Shared/WebSocketClientBase.cs‎

Lines changed: 103 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ public abstract class WebSocketClientBase : IDisposable
2121
private bool _disposed;
2222
private int _reconnectAttempts;
2323
private int _reconnectLoopActive;
24+
private long _connectionGeneration;
25+
private readonly SemaphoreSlim _sendSemaphore = new(1, 1);
2426
private static readonly int[] BackoffMs = { 1000, 2000, 4000, 8000, 15000, 30000, 60000 };
2527

2628
protected readonly string _token;
@@ -102,57 +104,89 @@ protected WebSocketClientBase(string gatewayUrl, string token, IOpenClawLogger?
102104
_cts = new CancellationTokenSource();
103105
}
104106

105-
public async Task ConnectAsync()
107+
public async Task ConnectAsync(CancellationToken cancellationToken = default)
106108
{
107109
if (_disposed)
108110
{
109111
_logger.Debug($"Skipping {ClientRole} connect: client already disposed");
110112
return;
111113
}
112114

115+
var connectGeneration = Interlocked.Increment(ref _connectionGeneration);
116+
ClientWebSocket? ws = null;
117+
113118
try
114119
{
115120
RaiseStatusChanged(ConnectionStatus.Connecting);
116121
_logger.Info($"Connecting to {ClientRole}: {GatewayUrlForDisplay}");
117122

118-
_webSocket = new ClientWebSocket();
119-
_webSocket.Options.KeepAliveInterval = TimeSpan.FromSeconds(30);
123+
ws = new ClientWebSocket();
124+
ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(30);
125+
_webSocket = ws;
120126

121127
// Set Origin header (convert ws/wss to http/https)
122128
var uri = new Uri(_gatewayUrl);
123129
var originScheme = uri.Scheme == "wss" ? "https" : "http";
124130
var origin = $"{originScheme}://{uri.Host}:{uri.Port}";
125-
_webSocket.Options.SetRequestHeader("Origin", origin);
131+
ws.Options.SetRequestHeader("Origin", origin);
126132

127133
if (!string.IsNullOrEmpty(_credentials))
128134
{
129135
var credentialsToEncode = GatewayUrlHelper.DecodeCredentials(_credentials);
130-
_webSocket.Options.SetRequestHeader(
136+
ws.Options.SetRequestHeader(
131137
"Authorization",
132138
$"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes(credentialsToEncode))}");
133139
}
134140

135-
await _webSocket.ConnectAsync(uri, _cts.Token);
141+
using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, cancellationToken);
142+
var connectToken = connectCts.Token;
143+
144+
await ws.ConnectAsync(uri, connectToken);
145+
if (!IsCurrentConnection(ws, connectGeneration) || connectToken.IsCancellationRequested)
146+
{
147+
DisposeStaleSocket(ws);
148+
return;
149+
}
136150

137151
// Don't reset _reconnectAttempts here — TCP connect succeeding doesn't mean
138152
// auth will succeed. Reset only after the full application-level handshake
139153
// completes (subclass calls ResetReconnectAttempts after hello-ok).
140154
_logger.Info($"{ClientRole} connected, waiting for challenge...");
141155

142156
await OnConnectedAsync();
157+
if (!IsCurrentConnection(ws, connectGeneration) || connectToken.IsCancellationRequested)
158+
{
159+
DisposeStaleSocket(ws);
160+
return;
161+
}
143162

144-
_ = Task.Run(() => ListenForMessagesAsync(), _cts.Token);
163+
_ = Task.Run(() => ListenForMessagesAsync(ws, _cts.Token, connectGeneration), _cts.Token);
145164
}
146165
catch (OperationCanceledException)
147166
{
148167
_logger.Debug($"{ClientRole} connect canceled (likely shutdown)");
168+
if (ws != null && ReferenceEquals(_webSocket, ws))
169+
{
170+
_webSocket = null;
171+
try { ws.Dispose(); } catch { /* ignore dispose errors */ }
172+
}
149173
}
150174
catch (ObjectDisposedException)
151175
{
152176
_logger.Debug($"{ClientRole} connect aborted after dispose");
177+
if (ws != null && ReferenceEquals(_webSocket, ws))
178+
{
179+
_webSocket = null;
180+
try { ws.Dispose(); } catch { /* ignore dispose errors */ }
181+
}
153182
}
154183
catch (Exception ex)
155184
{
185+
if (ws != null && ReferenceEquals(_webSocket, ws))
186+
{
187+
_webSocket = null;
188+
try { ws.Dispose(); } catch { /* ignore dispose errors */ }
189+
}
156190
_logger.Error($"{ClientRole} connection failed", ex);
157191
RaiseStatusChanged(ConnectionStatus.Error);
158192

@@ -163,7 +197,22 @@ public async Task ConnectAsync()
163197
}
164198
}
165199

166-
private async Task ListenForMessagesAsync()
200+
private bool IsCurrentConnection(ClientWebSocket ws, long generation)
201+
=> !_disposed
202+
&& Interlocked.Read(ref _connectionGeneration) == generation
203+
&& ReferenceEquals(_webSocket, ws);
204+
205+
private void DisposeStaleSocket(ClientWebSocket ws)
206+
{
207+
if (ReferenceEquals(_webSocket, ws))
208+
{
209+
_webSocket = null;
210+
}
211+
212+
try { ws.Dispose(); } catch { /* ignore dispose errors */ }
213+
}
214+
215+
private async Task ListenForMessagesAsync(ClientWebSocket ws, CancellationToken cancellationToken, long connectionGeneration)
167216
{
168217
// Rent a pooled buffer — consistent with the SendRawAsync hot path; avoids a large
169218
// (16–64 KB) heap allocation per connection that would otherwise land on the LOH.
@@ -172,10 +221,10 @@ private async Task ListenForMessagesAsync()
172221

173222
try
174223
{
175-
while (_webSocket?.State == WebSocketState.Open && !_cts.Token.IsCancellationRequested)
224+
while (ws.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
176225
{
177-
var result = await _webSocket.ReceiveAsync(
178-
new ArraySegment<byte>(buffer, 0, ReceiveBufferSize), _cts.Token);
226+
var result = await ws.ReceiveAsync(
227+
new ArraySegment<byte>(buffer, 0, ReceiveBufferSize), cancellationToken);
179228

180229
if (result.MessageType == WebSocketMessageType.Text)
181230
{
@@ -197,40 +246,49 @@ private async Task ListenForMessagesAsync()
197246
}
198247
else if (result.MessageType == WebSocketMessageType.Close)
199248
{
200-
var closeStatus = _webSocket.CloseStatus?.ToString() ?? "unknown";
201-
var closeDesc = _webSocket.CloseStatusDescription ?? "no description";
249+
var closeStatus = ws.CloseStatus?.ToString() ?? "unknown";
250+
var closeDesc = ws.CloseStatusDescription ?? "no description";
202251
_logger.Info($"Server closed connection: {closeStatus} - {closeDesc}");
203-
OnDisconnected();
204-
RaiseStatusChanged(ConnectionStatus.Disconnected);
252+
if (IsCurrentConnection(ws, connectionGeneration))
253+
{
254+
OnDisconnected();
255+
RaiseStatusChanged(ConnectionStatus.Disconnected);
256+
}
205257
break;
206258
}
207259
}
208260
}
209261
catch (WebSocketException ex) when (ex.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
210262
{
211263
_logger.Warn("Connection closed prematurely");
212-
OnDisconnected();
213-
RaiseStatusChanged(ConnectionStatus.Disconnected);
264+
if (IsCurrentConnection(ws, connectionGeneration))
265+
{
266+
OnDisconnected();
267+
RaiseStatusChanged(ConnectionStatus.Disconnected);
268+
}
214269
}
215270
catch (OperationCanceledException) { }
216271
catch (ObjectDisposedException) { /* CTS or WebSocket disposed during shutdown */ }
217272
catch (Exception ex)
218273
{
219274
_logger.Error($"{ClientRole} listen error", ex);
220-
OnError(ex);
221-
RaiseStatusChanged(ConnectionStatus.Error);
275+
if (IsCurrentConnection(ws, connectionGeneration))
276+
{
277+
OnError(ex);
278+
RaiseStatusChanged(ConnectionStatus.Error);
279+
}
222280
}
223281
finally
224282
{
225283
ArrayPool<byte>.Shared.Return(buffer);
226284
}
227285

228286
// Auto-reconnect if not intentionally disposed
229-
if (!_disposed)
287+
if (!_disposed && IsCurrentConnection(ws, connectionGeneration))
230288
{
231289
try
232290
{
233-
if (!_cts.Token.IsCancellationRequested && ShouldAutoReconnect())
291+
if (!cancellationToken.IsCancellationRequested && ShouldAutoReconnect())
234292
{
235293
await ReconnectWithBackoffAsync();
236294
}
@@ -295,20 +353,19 @@ protected async Task ReconnectWithBackoffAsync()
295353
/// <summary>Send a text message over the WebSocket. Thread-safe.</summary>
296354
protected async Task SendRawAsync(string message)
297355
{
298-
// Capture local reference to avoid TOCTOU race with reconnect/dispose
299-
var ws = _webSocket;
300-
if (ws?.State != WebSocketState.Open) return;
356+
await _sendSemaphore.WaitAsync(_cts.Token);
301357

302358
try
303359
{
360+
if (!CanSendRaw) return;
361+
304362
// Rent a pooled buffer to avoid per-send heap allocations on the hot send path.
305363
var byteCount = Encoding.UTF8.GetByteCount(message);
306364
var buffer = ArrayPool<byte>.Shared.Rent(byteCount);
307365
try
308366
{
309367
var written = Encoding.UTF8.GetBytes(message, buffer);
310-
await ws.SendAsync(buffer.AsMemory(0, written),
311-
WebSocketMessageType.Text, true, _cts.Token);
368+
await SendWebSocketTextAsync(buffer.AsMemory(0, written), _cts.Token);
312369
}
313370
finally
314371
{
@@ -323,6 +380,25 @@ await ws.SendAsync(buffer.AsMemory(0, written),
323380
{
324381
_logger.Warn($"WebSocket send failed (state changed): {ex.Message}");
325382
}
383+
finally
384+
{
385+
_sendSemaphore.Release();
386+
}
387+
}
388+
389+
/// <summary>Test seam for send gating; production sends only when the current socket is open.</summary>
390+
protected virtual bool CanSendRaw => _webSocket?.State == WebSocketState.Open;
391+
392+
/// <summary>Test seam for the raw WebSocket send performed under the send gate.</summary>
393+
protected virtual ValueTask SendWebSocketTextAsync(ReadOnlyMemory<byte> payload, CancellationToken cancellationToken)
394+
{
395+
var ws = _webSocket;
396+
if (ws?.State != WebSocketState.Open)
397+
{
398+
return ValueTask.CompletedTask;
399+
}
400+
401+
return ws.SendAsync(payload, WebSocketMessageType.Text, true, cancellationToken);
326402
}
327403

328404
/// <summary>Gracefully close the WebSocket connection.</summary>
@@ -346,6 +422,7 @@ public void Dispose()
346422

347423
OnDisposing();
348424

425+
Interlocked.Increment(ref _connectionGeneration);
349426
try { _cts.Cancel(); } catch { }
350427

351428
var ws = _webSocket;

0 commit comments

Comments
 (0)