Skip to content

Commit

Permalink
fix ungraceful shutdown of EventSub websocket connection
Browse files Browse the repository at this point in the history
  • Loading branch information
Felk committed Feb 29, 2024
1 parent 4607c91 commit 6b4d514
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions TPP.Core/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ private static void Mode(string modeName, string baseConfigFilename, string mode
Task modeTask = mode.Start(cts.Token);
void Abort(object? sender, EventArgs args)
{
if (cts.IsCancellationRequested) return;
logger.LogInformation("Aborting mode...");
cts.Cancel();
cleanupDone.Task.Wait();
Expand Down
9 changes: 7 additions & 2 deletions TPP.Twitch.EventSub/EventSubClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ public async Task<DisconnectReason> ConnectAndReceive(CancellationToken cancella
Instant lastMessageTimestamp = _clock.GetCurrentInstant(); // treat a fresh connection as a received message
while (!cancellationToken.IsCancellationRequested)
{
Task<ParseResult?> readTask = ReadMessage(webSocketBox.WebSocket, cancellationToken);
// Don't pass the cancellation token here. Instead, once cancelled we perform a graceful websocket closure.
// Otherwise the websocket would be immediately put in an aborted state, but we're not in that of a hurry.
Task<ParseResult?> readTask = ReadMessage(webSocketBox.WebSocket, CancellationToken.None);
Instant assumeDeadAt = lastMessageTimestamp + KeepaliveDuration + KeepAliveGrace;
Instant now = _clock.GetCurrentInstant();
Task timeoutTask = assumeDeadAt < now
Expand Down Expand Up @@ -215,7 +217,10 @@ public async Task<DisconnectReason> ConnectAndReceive(CancellationToken cancella
_logger.LogError("Known message was not handled and skipped: {Message}", message);
}
}
await webSocketBox.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
if (webSocketBox.WebSocket.State == WebSocketState.Open)
await webSocketBox.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
else
webSocketBox.WebSocket.Abort();
throw new TaskCanceledException();
}

Expand Down

0 comments on commit 6b4d514

Please sign in to comment.