SessionWebSocketListener.cs 12 KB

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