SessionWebSocketListener.cs 12 KB

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