BasePeriodicWebSocketListener.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 Lock _activeConnectionsLock = new();
  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 (_activeConnectionsLock)
  105. {
  106. _activeConnections.Add((message.Connection, cancellationTokenSource, state));
  107. }
  108. }
  109. protected void SendData(bool force)
  110. {
  111. _channel.Writer.TryWrite(force);
  112. }
  113. private async Task HandleMessages()
  114. {
  115. while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false))
  116. {
  117. while (_channel.Reader.TryRead(out var force))
  118. {
  119. try
  120. {
  121. (IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State)[] tuples;
  122. var now = DateTime.UtcNow;
  123. lock (_activeConnectionsLock)
  124. {
  125. if (_activeConnections.Count == 0)
  126. {
  127. continue;
  128. }
  129. tuples = _activeConnections
  130. .Where(c =>
  131. {
  132. if (c.Connection.State != WebSocketState.Open || c.CancellationTokenSource.IsCancellationRequested)
  133. {
  134. return false;
  135. }
  136. var state = c.State;
  137. return force || (now - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs;
  138. })
  139. .ToArray();
  140. }
  141. if (tuples.Length == 0)
  142. {
  143. continue;
  144. }
  145. var data = await GetDataToSend().ConfigureAwait(false);
  146. if (data is null)
  147. {
  148. continue;
  149. }
  150. IEnumerable<Task> GetTasks()
  151. {
  152. foreach (var tuple in tuples)
  153. {
  154. yield return SendDataInternal(data, tuple);
  155. }
  156. }
  157. await Task.WhenAll(GetTasks()).ConfigureAwait(false);
  158. }
  159. catch (Exception ex)
  160. {
  161. Logger.LogError(ex, "Failed to send updates to websockets");
  162. }
  163. }
  164. }
  165. }
  166. private async Task SendDataInternal(TReturnDataType data, (IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) tuple)
  167. {
  168. try
  169. {
  170. var (connection, cts, state) = tuple;
  171. var cancellationToken = cts.Token;
  172. await connection.SendAsync(
  173. new OutboundWebSocketMessage<TReturnDataType> { MessageType = Type, Data = data },
  174. cancellationToken).ConfigureAwait(false);
  175. state.DateLastSendUtc = DateTime.UtcNow;
  176. }
  177. catch (OperationCanceledException)
  178. {
  179. if (tuple.CancellationTokenSource.IsCancellationRequested)
  180. {
  181. DisposeConnection(tuple);
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. Logger.LogError(ex, "Error sending web socket message {Name}", Type);
  187. DisposeConnection(tuple);
  188. }
  189. }
  190. /// <summary>
  191. /// Stops sending messages over a web socket.
  192. /// </summary>
  193. /// <param name="message">The message.</param>
  194. private void Stop(WebSocketMessageInfo message)
  195. {
  196. lock (_activeConnectionsLock)
  197. {
  198. var connection = _activeConnections.FirstOrDefault(c => c.Connection == message.Connection);
  199. if (connection != default)
  200. {
  201. DisposeConnection(connection);
  202. }
  203. }
  204. }
  205. /// <summary>
  206. /// Disposes the connection.
  207. /// </summary>
  208. /// <param name="connection">The connection.</param>
  209. private void DisposeConnection((IWebSocketConnection Connection, CancellationTokenSource CancellationTokenSource, TStateType State) connection)
  210. {
  211. Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Connection.RemoteEndPoint, GetType().Name);
  212. // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
  213. // connection.Item1.Dispose();
  214. try
  215. {
  216. connection.CancellationTokenSource.Cancel();
  217. connection.CancellationTokenSource.Dispose();
  218. }
  219. catch (ObjectDisposedException ex)
  220. {
  221. // TODO Investigate and properly fix.
  222. Logger.LogError(ex, "Object Disposed");
  223. }
  224. catch (Exception ex)
  225. {
  226. // TODO Investigate and properly fix.
  227. Logger.LogError(ex, "Error disposing websocket");
  228. }
  229. lock (_activeConnectionsLock)
  230. {
  231. _activeConnections.Remove(connection);
  232. }
  233. }
  234. protected virtual async ValueTask DisposeAsyncCore()
  235. {
  236. try
  237. {
  238. _channel.Writer.TryComplete();
  239. await _messageConsumerTask.ConfigureAwait(false);
  240. }
  241. catch (Exception ex)
  242. {
  243. Logger.LogError(ex, "Disposing the message consumer failed");
  244. }
  245. lock (_activeConnectionsLock)
  246. {
  247. foreach (var connection in _activeConnections.ToList())
  248. {
  249. DisposeConnection(connection);
  250. }
  251. }
  252. }
  253. /// <inheritdoc />
  254. public async ValueTask DisposeAsync()
  255. {
  256. await DisposeAsyncCore().ConfigureAwait(false);
  257. GC.SuppressFinalize(this);
  258. }
  259. }
  260. }