-
-
Notifications
You must be signed in to change notification settings - Fork 724
/
WebSocketSubscriptionMiddleware.cs
54 lines (48 loc) · 1.82 KB
/
WebSocketSubscriptionMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Microsoft.AspNetCore.Http;
using HotChocolate.AspNetCore.Instrumentation;
using HotChocolate.AspNetCore.Serialization;
using HotChocolate.AspNetCore.Subscriptions;
using RequestDelegate = Microsoft.AspNetCore.Http.RequestDelegate;
namespace HotChocolate.AspNetCore;
public sealed class WebSocketSubscriptionMiddleware : MiddlewareBase
{
private readonly IServerDiagnosticEvents _diagnosticEvents;
public WebSocketSubscriptionMiddleware(
RequestDelegate next,
IRequestExecutorResolver executorResolver,
IHttpResponseFormatter responseFormatter,
IServerDiagnosticEvents diagnosticEvents,
string schemaName)
: base(next, executorResolver, responseFormatter, schemaName)
{
_diagnosticEvents = diagnosticEvents ??
throw new ArgumentNullException(nameof(diagnosticEvents));
}
public Task InvokeAsync(HttpContext context)
{
return context.WebSockets.IsWebSocketRequest
? HandleWebSocketSessionAsync(context)
: NextAsync(context);
}
private async Task HandleWebSocketSessionAsync(HttpContext context)
{
if (!IsDefaultSchema)
{
context.Items[WellKnownContextData.SchemaName] = SchemaName;
}
using (_diagnosticEvents.WebSocketSession(context))
{
try
{
var executor = await GetExecutorAsync(context.RequestAborted);
var interceptor = executor.GetRequiredService<ISocketSessionInterceptor>();
context.Items[WellKnownContextData.RequestExecutor] = executor;
await WebSocketSession.AcceptAsync(context, executor, interceptor);
}
catch (Exception ex)
{
_diagnosticEvents.WebSocketSessionError(context, ex);
}
}
}
}