@@ -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