fix: implement retry logic for establishing initial websocket connection with an expontential backoff

This commit is contained in:
Stevan Freeborn
2025-09-10 16:44:46 -05:00
parent 46d4cdf313
commit 96ba7e5fe7
@@ -677,19 +677,30 @@ internal sealed class DiscordGatewayClient : IDiscordGatewayClient
var connected = false; var connected = false;
var attempts = 0; var attempts = 0;
var delay = TimeSpan.FromSeconds(0); var delay = TimeSpan.FromSeconds(1);
while (connected is false) while (connected is false)
{ {
try try
{ {
await Task.Delay(delay, cancellationToken);
await _webSocket.ConnectAsync(uri, cancellationToken); await _webSocket.ConnectAsync(uri, cancellationToken);
connected = true; connected = true;
} }
catch (Exception e) when (e is WebSocketException) catch (Exception e) when (e is WebSocketException)
{ {
// TODO: Implement exponential backoff retry strategy var currentDelay = (int)(delay.TotalMilliseconds * Math.Pow(2, attempts));
_logger.LogWarning(
e,
"Failed to connect to {Uri} on {Attempt} attempt. Waiting for {Delay}ms before trying again",
uri,
attempts,
currentDelay
);
await Task.Delay(currentDelay, cancellationToken);
attempts++;
} }
} }
} }