SessionWebSocketListener.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.WebSockets;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Extensions;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
  10. using MediaBrowser.Controller.Session;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.Extensions.Logging;
  13. namespace Emby.Server.Implementations.Session
  14. {
  15. /// <summary>
  16. /// Class SessionWebSocketListener.
  17. /// </summary>
  18. public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
  19. {
  20. /// <summary>
  21. /// The timeout in seconds after which a WebSocket is considered to be lost.
  22. /// </summary>
  23. private const int WebSocketLostTimeout = 60;
  24. /// <summary>
  25. /// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets.
  26. /// </summary>
  27. private const float IntervalFactor = 0.2f;
  28. /// <summary>
  29. /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
  30. /// </summary>
  31. private const float ForceKeepAliveFactor = 0.75f;
  32. /// <summary>
  33. /// Lock used for accessing the KeepAlive cancellation token.
  34. /// </summary>
  35. private readonly object _keepAliveLock = new object();
  36. /// <summary>
  37. /// The WebSocket watchlist.
  38. /// </summary>
  39. private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>();
  40. /// <summary>
  41. /// Lock used for accessing the WebSockets watchlist.
  42. /// </summary>
  43. private readonly object _webSocketsLock = new object();
  44. private readonly ISessionManager _sessionManager;
  45. private readonly ILogger<SessionWebSocketListener> _logger;
  46. private readonly ILoggerFactory _loggerFactory;
  47. /// <summary>
  48. /// The KeepAlive cancellation token.
  49. /// </summary>
  50. private CancellationTokenSource? _keepAliveCancellationToken;
  51. /// <summary>
  52. /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
  53. /// </summary>
  54. /// <param name="logger">The logger.</param>
  55. /// <param name="sessionManager">The session manager.</param>
  56. /// <param name="loggerFactory">The logger factory.</param>
  57. public SessionWebSocketListener(
  58. ILogger<SessionWebSocketListener> logger,
  59. ISessionManager sessionManager,
  60. ILoggerFactory loggerFactory)
  61. {
  62. _logger = logger;
  63. _sessionManager = sessionManager;
  64. _loggerFactory = loggerFactory;
  65. }
  66. /// <inheritdoc />
  67. public void Dispose()
  68. {
  69. StopKeepAlive();
  70. }
  71. /// <summary>
  72. /// Processes the message.
  73. /// </summary>
  74. /// <param name="message">The message.</param>
  75. /// <returns>Task.</returns>
  76. public Task ProcessMessageAsync(WebSocketMessageInfo message)
  77. => Task.CompletedTask;
  78. /// <inheritdoc />
  79. public async Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection, HttpContext httpContext)
  80. {
  81. var session = await GetSession(httpContext, connection.RemoteEndPoint?.ToString()).ConfigureAwait(false);
  82. if (session is not null)
  83. {
  84. EnsureController(session, connection);
  85. await KeepAliveWebSocket(connection).ConfigureAwait(false);
  86. }
  87. else
  88. {
  89. _logger.LogWarning("Unable to determine session based on query string: {0}", httpContext.Request.QueryString);
  90. }
  91. }
  92. private async Task<SessionInfo?> GetSession(HttpContext httpContext, string? remoteEndpoint)
  93. {
  94. if (!httpContext.User.Identity?.IsAuthenticated ?? false)
  95. {
  96. return null;
  97. }
  98. var deviceId = httpContext.User.GetDeviceId();
  99. if (httpContext.Request.Query.TryGetValue("deviceId", out var queryDeviceId))
  100. {
  101. deviceId = queryDeviceId;
  102. }
  103. return await _sessionManager.GetSessionByAuthenticationToken(httpContext.User.GetToken(), deviceId, remoteEndpoint)
  104. .ConfigureAwait(false);
  105. }
  106. private void EnsureController(SessionInfo session, IWebSocketConnection connection)
  107. {
  108. var controllerInfo = session.EnsureController<WebSocketController>(
  109. s => new WebSocketController(_loggerFactory.CreateLogger<WebSocketController>(), s, _sessionManager));
  110. var controller = (WebSocketController)controllerInfo.Item1;
  111. controller.AddWebSocket(connection);
  112. _sessionManager.OnSessionControllerConnected(session);
  113. }
  114. /// <summary>
  115. /// Called when a WebSocket is closed.
  116. /// </summary>
  117. /// <param name="sender">The WebSocket.</param>
  118. /// <param name="e">The event arguments.</param>
  119. private void OnWebSocketClosed(object? sender, EventArgs e)
  120. {
  121. if (sender is null)
  122. {
  123. return;
  124. }
  125. var webSocket = (IWebSocketConnection)sender;
  126. _logger.LogDebug("WebSocket {0} is closed.", webSocket);
  127. RemoveWebSocket(webSocket);
  128. }
  129. /// <summary>
  130. /// Adds a WebSocket to the KeepAlive watchlist.
  131. /// </summary>
  132. /// <param name="webSocket">The WebSocket to monitor.</param>
  133. private async Task KeepAliveWebSocket(IWebSocketConnection webSocket)
  134. {
  135. lock (_webSocketsLock)
  136. {
  137. if (!_webSockets.Add(webSocket))
  138. {
  139. _logger.LogWarning("Multiple attempts to keep alive single WebSocket {0}", webSocket);
  140. return;
  141. }
  142. webSocket.Closed += OnWebSocketClosed;
  143. webSocket.LastKeepAliveDate = DateTime.UtcNow;
  144. StartKeepAlive();
  145. }
  146. // Notify WebSocket about timeout
  147. try
  148. {
  149. await SendForceKeepAlive(webSocket).ConfigureAwait(false);
  150. }
  151. catch (WebSocketException exception)
  152. {
  153. _logger.LogWarning(exception, "Cannot send ForceKeepAlive message to WebSocket {0}.", webSocket);
  154. }
  155. }
  156. /// <summary>
  157. /// Removes a WebSocket from the KeepAlive watchlist.
  158. /// </summary>
  159. /// <param name="webSocket">The WebSocket to remove.</param>
  160. private void RemoveWebSocket(IWebSocketConnection webSocket)
  161. {
  162. lock (_webSocketsLock)
  163. {
  164. if (!_webSockets.Remove(webSocket))
  165. {
  166. _logger.LogWarning("WebSocket {0} not on watchlist.", webSocket);
  167. }
  168. else
  169. {
  170. webSocket.Closed -= OnWebSocketClosed;
  171. }
  172. }
  173. }
  174. /// <summary>
  175. /// Starts the KeepAlive watcher.
  176. /// </summary>
  177. private void StartKeepAlive()
  178. {
  179. lock (_keepAliveLock)
  180. {
  181. if (_keepAliveCancellationToken is null)
  182. {
  183. _keepAliveCancellationToken = new CancellationTokenSource();
  184. // Start KeepAlive watcher
  185. _ = RepeatAsyncCallbackEvery(
  186. KeepAliveSockets,
  187. TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor),
  188. _keepAliveCancellationToken.Token);
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// Stops the KeepAlive watcher.
  194. /// </summary>
  195. private void StopKeepAlive()
  196. {
  197. lock (_keepAliveLock)
  198. {
  199. if (_keepAliveCancellationToken is not null)
  200. {
  201. _keepAliveCancellationToken.Cancel();
  202. _keepAliveCancellationToken.Dispose();
  203. _keepAliveCancellationToken = null;
  204. }
  205. }
  206. lock (_webSocketsLock)
  207. {
  208. foreach (var webSocket in _webSockets)
  209. {
  210. webSocket.Closed -= OnWebSocketClosed;
  211. }
  212. _webSockets.Clear();
  213. }
  214. }
  215. /// <summary>
  216. /// Checks status of KeepAlive of WebSockets.
  217. /// </summary>
  218. private async Task KeepAliveSockets()
  219. {
  220. List<IWebSocketConnection> inactive;
  221. List<IWebSocketConnection> lost;
  222. lock (_webSocketsLock)
  223. {
  224. _logger.LogDebug("Watching {0} WebSockets.", _webSockets.Count);
  225. inactive = _webSockets.Where(i =>
  226. {
  227. var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds;
  228. return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout);
  229. }).ToList();
  230. lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout).ToList();
  231. }
  232. if (inactive.Count > 0)
  233. {
  234. _logger.LogInformation("Sending ForceKeepAlive message to {0} inactive WebSockets.", inactive.Count);
  235. }
  236. foreach (var webSocket in inactive)
  237. {
  238. try
  239. {
  240. await SendForceKeepAlive(webSocket).ConfigureAwait(false);
  241. }
  242. catch (WebSocketException exception)
  243. {
  244. _logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket.");
  245. lost.Add(webSocket);
  246. }
  247. }
  248. lock (_webSocketsLock)
  249. {
  250. if (lost.Count > 0)
  251. {
  252. _logger.LogInformation("Lost {0} WebSockets.", lost.Count);
  253. foreach (var webSocket in lost)
  254. {
  255. // TODO: handle session relative to the lost webSocket
  256. RemoveWebSocket(webSocket);
  257. }
  258. }
  259. if (_webSockets.Count == 0)
  260. {
  261. StopKeepAlive();
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// Sends a ForceKeepAlive message to a WebSocket.
  267. /// </summary>
  268. /// <param name="webSocket">The WebSocket.</param>
  269. /// <returns>Task.</returns>
  270. private Task SendForceKeepAlive(IWebSocketConnection webSocket)
  271. {
  272. return webSocket.SendAsync(
  273. new ForceKeepAliveMessage(WebSocketLostTimeout),
  274. CancellationToken.None);
  275. }
  276. /// <summary>
  277. /// Runs a given async callback once every specified interval time, until cancelled.
  278. /// </summary>
  279. /// <param name="callback">The async callback.</param>
  280. /// <param name="interval">The interval time.</param>
  281. /// <param name="cancellationToken">The cancellation token.</param>
  282. /// <returns>Task.</returns>
  283. private async Task RepeatAsyncCallbackEvery(Func<Task> callback, TimeSpan interval, CancellationToken cancellationToken)
  284. {
  285. while (!cancellationToken.IsCancellationRequested)
  286. {
  287. await callback().ConfigureAwait(false);
  288. try
  289. {
  290. await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
  291. }
  292. catch (TaskCanceledException)
  293. {
  294. return;
  295. }
  296. }
  297. }
  298. }
  299. }