Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: close websocket when the application shuts down #3

Merged
merged 1 commit into from
Feb 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions backend/MangaMagnet.Api/Middlewares/WebSocketMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace MangaMagnet.Api.Middlewares;
/// <summary>
/// Handles WebSocket requests.
/// </summary>
public class WebSocketMiddleware(WebSocketService webSocketService, ProgressService progressService, IOptions<JsonOptions> jsonOptions) : IMiddleware
public class WebSocketMiddleware(WebSocketService webSocketService, ProgressService progressService, IOptions<JsonOptions> jsonOptions, IHostApplicationLifetime lifetime) : IMiddleware
{
/// <inheritdoc />
public Task InvokeAsync(HttpContext context, RequestDelegate next)
Expand Down Expand Up @@ -47,13 +47,14 @@ private async Task HandleWebSocketRequest(HttpContext context)

try
{
var cancellationToken = context.RequestAborted;
using var cts = CancellationTokenSource.CreateLinkedTokenSource(lifetime.ApplicationStopping, context.RequestAborted);
var cancellationToken = cts.Token;

await SendCurrentTasksAsync(webSocket);
webSocketService.AddSocket(id, webSocket);

var buffer = new byte[1024];
var result = await webSocket.ReceiveAsync(buffer, default);
var result = await webSocket.ReceiveAsync(buffer, cancellationToken);

while (!result.CloseStatus.HasValue)
{
Expand All @@ -62,9 +63,13 @@ private async Task HandleWebSocketRequest(HttpContext context)
// This websocket is only for sending progress updates, so we don't need to handle any incoming messages.
}

await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, cancellationToken);
await webSocket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure, result.CloseStatusDescription, cancellationToken);
}
catch (WebSocketException e)
catch (TaskCanceledException)
{
await TryCloseAsync(webSocket, WebSocketCloseStatus.NormalClosure);
}
catch (WebSocketException)
{
await TryCloseAsync(webSocket, WebSocketCloseStatus.ProtocolError);
}
Expand Down
Loading