-
-
Notifications
You must be signed in to change notification settings - Fork 725
/
WebSocketConnection.cs
206 lines (177 loc) · 6.53 KB
/
WebSocketConnection.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
using System;
using System.IO.Pipelines;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace HotChocolate.AspNetCore.Subscriptions
{
public class WebSocketConnection
: ISocketConnection
{
private const string _protocol = "graphql-ws";
private const int _maxMessageSize = 1024 * 4;
private WebSocket? _webSocket;
private bool _disposed;
private WebSocketConnection(HttpContext httpContext)
{
HttpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
Subscriptions = new SubscriptionManager(this);
}
public bool Closed => _webSocket is null || _webSocket.CloseStatus.HasValue;
public HttpContext HttpContext { get; }
public ISubscriptionManager Subscriptions { get; }
public WebSocketManager WebSockets => HttpContext.WebSockets;
public IServiceProvider RequestServices => HttpContext.RequestServices;
public CancellationToken RequestAborted => HttpContext.RequestAborted;
public async Task<bool> TryOpenAsync()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(WebSocketConnection));
}
_webSocket = await WebSockets.AcceptWebSocketAsync(_protocol);
if (_webSocket.SubProtocol is not null &&
WebSockets.WebSocketRequestedProtocols.Contains(_webSocket.SubProtocol))
{
return true;
}
await _webSocket.CloseOutputAsync(
WebSocketCloseStatus.ProtocolError,
"Expected graphql-ws protocol.",
CancellationToken.None);
_webSocket.Dispose();
_webSocket = null;
return false;
}
public Task SendAsync(
byte[] message,
CancellationToken cancellationToken)
{
WebSocket? webSocket = _webSocket;
if (_disposed || webSocket == null)
{
return Task.CompletedTask;
}
return webSocket.SendAsync(
new ArraySegment<byte>(message),
WebSocketMessageType.Text,
true, cancellationToken);
}
public async Task ReceiveAsync(
PipeWriter writer,
CancellationToken cancellationToken)
{
WebSocket? webSocket = _webSocket;
if (_disposed || webSocket == null)
{
return;
}
try
{
WebSocketReceiveResult? socketResult = null;
do
{
Memory<byte> memory = writer.GetMemory(_maxMessageSize);
var success = MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> buffer);
if (success)
{
try
{
socketResult = await webSocket.ReceiveAsync(buffer, cancellationToken);
if (socketResult.Count == 0)
{
break;
}
writer.Advance(socketResult.Count);
}
catch
{
break;
}
FlushResult result = await writer.FlushAsync(cancellationToken);
if (result.IsCompleted)
{
break;
}
}
} while (socketResult == null || !socketResult.EndOfMessage);
}
catch (ObjectDisposedException)
{
// we will just stop receiving
}
}
public async Task CloseAsync(
string message,
SocketCloseStatus closeStatus,
CancellationToken cancellationToken)
{
try
{
WebSocket? webSocket = _webSocket;
if (_disposed || Closed || webSocket is null)
{
return;
}
await webSocket.CloseOutputAsync(
MapCloseStatus(closeStatus),
message,
cancellationToken);
Dispose();
}
catch
{
// we do not throw here ...
}
}
private static WebSocketCloseStatus MapCloseStatus(
SocketCloseStatus closeStatus)
{
switch (closeStatus)
{
case SocketCloseStatus.EndpointUnavailable:
return WebSocketCloseStatus.EndpointUnavailable;
case SocketCloseStatus.InternalServerError:
return WebSocketCloseStatus.InternalServerError;
case SocketCloseStatus.InvalidMessageType:
return WebSocketCloseStatus.InvalidMessageType;
case SocketCloseStatus.InvalidPayloadData:
return WebSocketCloseStatus.InvalidPayloadData;
case SocketCloseStatus.MandatoryExtension:
return WebSocketCloseStatus.MandatoryExtension;
case SocketCloseStatus.MessageTooBig:
return WebSocketCloseStatus.MessageTooBig;
case SocketCloseStatus.NormalClosure:
return WebSocketCloseStatus.NormalClosure;
case SocketCloseStatus.PolicyViolation:
return WebSocketCloseStatus.PolicyViolation;
case SocketCloseStatus.ProtocolError:
return WebSocketCloseStatus.ProtocolError;
default:
return WebSocketCloseStatus.Empty;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
Subscriptions.Dispose();
_webSocket?.Dispose();
_webSocket = null;
}
_disposed = true;
}
}
public static WebSocketConnection New(HttpContext httpContext) =>
new WebSocketConnection(httpContext);
}
}