BasePeriodicWebSocketListener.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #nullable disable
  2. #pragma warning disable CS1591, SA1306, SA1401
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Net.WebSockets;
  8. using System.Threading;
  9. using System.Threading.Channels;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Controller.Net.WebSocketMessages;
  12. using MediaBrowser.Model.Session;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. namespace MediaBrowser.Controller.Net
  16. {
  17. /// <summary>
  18. /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received.
  19. /// </summary>
  20. /// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
  21. /// <typeparam name="TStateType">The type of the T state type.</typeparam>
  22. public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IAsyncDisposable
  23. where TStateType : WebSocketListenerState, new()
  24. where TReturnDataType : class
  25. {
  26. private readonly Channel<bool> _channel = Channel.CreateUnbounded<bool>(new UnboundedChannelOptions
  27. {
  28. AllowSynchronousContinuations = false,
  29. SingleReader = true,
  30. SingleWriter = false
  31. });
  32. private readonly SemaphoreSlim _lock = new(1, 1);
  33. /// <summary>
  34. /// The _active connections.
  35. /// </summary>
  36. private readonly List<(IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State)> _activeConnections = new();
  37. /// <summary>
  38. /// The logger.
  39. /// </summary>
  40. protected readonly ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> Logger;
  41. private readonly Task _messageConsumerTask;
  42. protected BasePeriodicWebSocketListener(ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> logger)
  43. {
  44. ArgumentNullException.ThrowIfNull(logger);
  45. Logger = logger;
  46. _messageConsumerTask = HandleMessages();
  47. }
  48. /// <summary>
  49. /// Gets the type used for the messages sent to the client.
  50. /// </summary>
  51. /// <value>The type.</value>
  52. protected abstract SessionMessageType Type { get; }
  53. /// <summary>
  54. /// Gets the message type received from the client to start sending messages.
  55. /// </summary>
  56. /// <value>The type.</value>
  57. protected abstract SessionMessageType StartType { get; }
  58. /// <summary>
  59. /// Gets the message type received from the client to stop sending messages.
  60. /// </summary>
  61. /// <value>The type.</value>
  62. protected abstract SessionMessageType StopType { get; }
  63. /// <summary>
  64. /// Gets the data to send.
  65. /// </summary>
  66. /// <returns>Task{`1}.</returns>
  67. protected abstract Task<TReturnDataType> GetDataToSend();
  68. /// <summary>
  69. /// Processes the message.
  70. /// </summary>
  71. /// <param name="message">The message.</param>
  72. /// <returns>Task.</returns>
  73. public Task ProcessMessageAsync(WebSocketMessageInfo message)
  74. {
  75. ArgumentNullException.ThrowIfNull(message);
  76. if (message.MessageType == StartType)
  77. {
  78. Start(message);
  79. }
  80. if (message.MessageType == StopType)
  81. {
  82. Stop(message);
  83. }
  84. return Task.CompletedTask;
  85. }
  86. /// <inheritdoc />
  87. public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection, HttpContext httpContext) => Task.CompletedTask;
  88. /// <summary>
  89. /// Starts sending messages over a web socket.
  90. /// </summary>
  91. /// <param name="message">The message.</param>
  92. protected virtual void Start(WebSocketMessageInfo message)
  93. {
  94. var vals = message.Data.Split(',');
  95. var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
  96. var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
  97. var cancellationTokenSource = new CancellationTokenSource();
  98. Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
  99. var state = new TStateType
  100. {
  101. IntervalMs = periodMs,
  102. InitialDelayMs = dueTimeMs
  103. };
  104. _lock.Wait();
  105. try
  106. {
  107. _activeConnections.Add((message.Connection, cancellationTokenSource, state));
  108. }
  109. finally
  110. {
  111. _lock.Release();
  112. }
  113. }
  114. protected void SendData(bool force)
  115. {
  116. _channel.Writer.TryWrite(force);
  117. }
  118. private async Task HandleMessages()
  119. {
  120. while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false))
  121. {
  122. while (_channel.Reader.TryRead(out var force))
  123. {
  124. try
  125. {
  126. (IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State)[] tuples;
  127. var now = DateTime.UtcNow;
  128. await _lock.WaitAsync().ConfigureAwait(false);
  129. try
  130. {
  131. if (_activeConnections.Count == 0)
  132. {
  133. continue;
  134. }
  135. tuples = _activeConnections
  136. .Where(c =>
  137. {
  138. if (c.Connection.State != WebSocketState.Open || c.CancellationTokenSource.IsCancellationRequested)
  139. {
  140. return false;
  141. }
  142. var state = c.State;
  143. return force || (now - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs;
  144. })
  145. .ToArray();
  146. }
  147. finally
  148. {
  149. _lock.Release();
  150. }
  151. if (tuples.Length == 0)
  152. {
  153. continue;
  154. }
  155. var data = await GetDataToSend().ConfigureAwait(false);
  156. if (data is null)
  157. {
  158. continue;
  159. }
  160. IEnumerable<Task> GetTasks()
  161. {
  162. foreach (var tuple in tuples)
  163. {
  164. yield return SendDataInternal(data, tuple);
  165. }
  166. }
  167. await Task.WhenAll(GetTasks()).ConfigureAwait(false);
  168. }
  169. catch (Exception ex)
  170. {
  171. Logger.LogError(ex, "Failed to send updates to websockets");
  172. }
  173. }
  174. }
  175. }
  176. private async Task SendDataInternal(TReturnDataType data, (IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) tuple)
  177. {
  178. try
  179. {
  180. var (connection, cts, state) = tuple;
  181. var cancellationToken = cts.Token;
  182. await connection.SendAsync(
  183. new OutboundWebSocketMessage<TReturnDataType> { MessageType = Type, Data = data },
  184. cancellationToken).ConfigureAwait(false);
  185. state.DateLastSendUtc = DateTime.UtcNow;
  186. }
  187. catch (OperationCanceledException)
  188. {
  189. if (tuple.CancellationTokenSource.IsCancellationRequested)
  190. {
  191. DisposeConnection(tuple);
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. Logger.LogError(ex, "Error sending web socket message {Name}", Type);
  197. DisposeConnection(tuple);
  198. }
  199. }
  200. /// <summary>
  201. /// Stops sending messages over a web socket.
  202. /// </summary>
  203. /// <param name="message">The message.</param>
  204. private void Stop(WebSocketMessageInfo message)
  205. {
  206. _lock.Wait();
  207. try
  208. {
  209. var connection = _activeConnections.FirstOrDefault(c => c.Connection == message.Connection);
  210. if (connection != default)
  211. {
  212. DisposeConnection(connection);
  213. }
  214. }
  215. finally
  216. {
  217. _lock.Release();
  218. }
  219. }
  220. /// <summary>
  221. /// Disposes the connection.
  222. /// </summary>
  223. /// <param name="connection">The connection.</param>
  224. private void DisposeConnection((IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) connection)
  225. {
  226. Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Connection.RemoteEndPoint, GetType().Name);
  227. // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
  228. // connection.Item1.Dispose();
  229. try
  230. {
  231. connection.CancellationTokenSource.Cancel();
  232. connection.CancellationTokenSource.Dispose();
  233. }
  234. catch (ObjectDisposedException ex)
  235. {
  236. // TODO Investigate and properly fix.
  237. Logger.LogError(ex, "Object Disposed");
  238. }
  239. catch (Exception ex)
  240. {
  241. // TODO Investigate and properly fix.
  242. Logger.LogError(ex, "Error disposing websocket");
  243. }
  244. _lock.Wait();
  245. try
  246. {
  247. _activeConnections.Remove(connection);
  248. }
  249. finally
  250. {
  251. _lock.Release();
  252. }
  253. }
  254. protected virtual async ValueTask DisposeAsyncCore()
  255. {
  256. try
  257. {
  258. _channel.Writer.TryComplete();
  259. await _messageConsumerTask.ConfigureAwait(false);
  260. }
  261. catch (Exception ex)
  262. {
  263. Logger.LogError(ex, "Disposing the message consumer failed");
  264. }
  265. await _lock.WaitAsync().ConfigureAwait(false);
  266. try
  267. {
  268. foreach (var connection in _activeConnections.ToArray())
  269. {
  270. DisposeConnection(connection);
  271. }
  272. }
  273. finally
  274. {
  275. _lock.Release();
  276. }
  277. }
  278. /// <inheritdoc />
  279. public async ValueTask DisposeAsync()
  280. {
  281. await DisposeAsyncCore().ConfigureAwait(false);
  282. GC.SuppressFinalize(this);
  283. }
  284. }
  285. }