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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
#nullable disable
#pragma warning disable CS1591, SA1306, SA1401
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net.WebSocketMessages;
using MediaBrowser.Model.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Net
{
/// <summary>
/// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received.
/// </summary>
/// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
/// <typeparam name="TStateType">The type of the T state type.</typeparam>
public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IAsyncDisposable
where TStateType : WebSocketListenerState, new()
where TReturnDataType : class
{
private readonly Channel<bool> _channel = Channel.CreateUnbounded<bool>(new UnboundedChannelOptions
{
AllowSynchronousContinuations = false,
SingleReader = true,
SingleWriter = false
});
private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary>
/// The _active connections.
/// </summary>
private readonly List<(IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State)> _activeConnections = new();
/// <summary>
/// The logger.
/// </summary>
protected readonly ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> Logger;
private readonly Task _messageConsumerTask;
protected BasePeriodicWebSocketListener(ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> logger)
{
ArgumentNullException.ThrowIfNull(logger);
Logger = logger;
_messageConsumerTask = HandleMessages();
}
/// <summary>
/// Gets the type used for the messages sent to the client.
/// </summary>
/// <value>The type.</value>
protected abstract SessionMessageType Type { get; }
/// <summary>
/// Gets the message type received from the client to start sending messages.
/// </summary>
/// <value>The type.</value>
protected abstract SessionMessageType StartType { get; }
/// <summary>
/// Gets the message type received from the client to stop sending messages.
/// </summary>
/// <value>The type.</value>
protected abstract SessionMessageType StopType { get; }
/// <summary>
/// Gets the data to send.
/// </summary>
/// <returns>Task{`1}.</returns>
protected abstract Task<TReturnDataType> GetDataToSend();
/// <summary>
/// Processes the message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Task.</returns>
public Task ProcessMessageAsync(WebSocketMessageInfo message)
{
ArgumentNullException.ThrowIfNull(message);
if (message.MessageType == StartType)
{
Start(message);
}
if (message.MessageType == StopType)
{
Stop(message);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection, HttpContext httpContext) => Task.CompletedTask;
/// <summary>
/// Starts sending messages over a web socket.
/// </summary>
/// <param name="message">The message.</param>
protected virtual void Start(WebSocketMessageInfo message)
{
var vals = message.Data.Split(',');
var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
var cancellationTokenSource = new CancellationTokenSource();
Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
var state = new TStateType
{
IntervalMs = periodMs,
InitialDelayMs = dueTimeMs
};
_lock.Wait();
try
{
_activeConnections.Add((message.Connection, cancellationTokenSource, state));
}
finally
{
_lock.Release();
}
}
protected void SendData(bool force)
{
_channel.Writer.TryWrite(force);
}
private async Task HandleMessages()
{
while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false))
{
while (_channel.Reader.TryRead(out var force))
{
try
{
(IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State)[] tuples;
var now = DateTime.UtcNow;
await _lock.WaitAsync().ConfigureAwait(false);
try
{
if (_activeConnections.Count == 0)
{
continue;
}
tuples = _activeConnections
.Where(c =>
{
if (c.Connection.State != WebSocketState.Open || c.CancellationTokenSource.IsCancellationRequested)
{
return false;
}
var state = c.State;
return force || (now - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs;
})
.ToArray();
}
finally
{
_lock.Release();
}
if (tuples.Length == 0)
{
continue;
}
var data = await GetDataToSend().ConfigureAwait(false);
if (data is null)
{
continue;
}
IEnumerable<Task> GetTasks()
{
foreach (var tuple in tuples)
{
yield return SendDataInternal(data, tuple);
}
}
await Task.WhenAll(GetTasks()).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to send updates to websockets");
}
}
}
}
private async Task SendDataInternal(TReturnDataType data, (IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) tuple)
{
try
{
var (connection, cts, state) = tuple;
var cancellationToken = cts.Token;
await connection.SendAsync(
new OutboundWebSocketMessage<TReturnDataType> { MessageType = Type, Data = data },
cancellationToken).ConfigureAwait(false);
state.DateLastSendUtc = DateTime.UtcNow;
}
catch (OperationCanceledException)
{
if (tuple.CancellationTokenSource.IsCancellationRequested)
{
DisposeConnection(tuple);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error sending web socket message {Name}", Type);
DisposeConnection(tuple);
}
}
/// <summary>
/// Stops sending messages over a web socket.
/// </summary>
/// <param name="message">The message.</param>
private void Stop(WebSocketMessageInfo message)
{
_lock.Wait();
try
{
var connection = _activeConnections.FirstOrDefault(c => c.Connection == message.Connection);
if (connection != default)
{
DisposeConnection(connection);
}
}
finally
{
_lock.Release();
}
}
/// <summary>
/// Disposes the connection.
/// </summary>
/// <param name="connection">The connection.</param>
private void DisposeConnection((IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) connection)
{
Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Connection.RemoteEndPoint, GetType().Name);
// TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
// connection.Item1.Dispose();
try
{
connection.CancellationTokenSource.Cancel();
connection.CancellationTokenSource.Dispose();
}
catch (ObjectDisposedException ex)
{
// TODO Investigate and properly fix.
Logger.LogError(ex, "Object Disposed");
}
catch (Exception ex)
{
// TODO Investigate and properly fix.
Logger.LogError(ex, "Error disposing websocket");
}
_lock.Wait();
try
{
_activeConnections.Remove(connection);
}
finally
{
_lock.Release();
}
}
protected virtual async ValueTask DisposeAsyncCore()
{
try
{
_channel.Writer.TryComplete();
await _messageConsumerTask.ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex, "Disposing the message consumer failed");
}
await _lock.WaitAsync().ConfigureAwait(false);
try
{
foreach (var connection in _activeConnections.ToArray())
{
DisposeConnection(connection);
}
}
finally
{
_lock.Release();
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
await DisposeAsyncCore().ConfigureAwait(false);
GC.SuppressFinalize(this);
}
}
}
|