BasePeriodicWebSocketListener.cs 11 KB

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