SessionWebSocketListener.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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.Events;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Serialization;
  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 class SessionWebSocketListener : IWebSocketListener, IDisposable
  20. {
  21. /// <summary>
  22. /// The timeout in seconds after which a WebSocket is considered to be lost.
  23. /// </summary>
  24. public 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. public const float IntervalFactor = 0.2f;
  29. /// <summary>
  30. /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
  31. /// </summary>
  32. public const float ForceKeepAliveFactor = 0.75f;
  33. /// <summary>
  34. /// The _session manager
  35. /// </summary>
  36. private readonly ISessionManager _sessionManager;
  37. /// <summary>
  38. /// The _logger
  39. /// </summary>
  40. private readonly ILogger _logger;
  41. /// <summary>
  42. /// The _dto service
  43. /// </summary>
  44. private readonly IJsonSerializer _json;
  45. private readonly IHttpServer _httpServer;
  46. /// <summary>
  47. /// The KeepAlive cancellation token.
  48. /// </summary>
  49. private CancellationTokenSource _keepAliveCancellationToken;
  50. /// <summary>
  51. /// Lock used for accesing the KeepAlive cancellation token.
  52. /// </summary>
  53. private readonly object _keepAliveLock = new object();
  54. /// <summary>
  55. /// The WebSocket watchlist.
  56. /// </summary>
  57. private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>();
  58. /// <summary>
  59. /// Lock used for accesing the WebSockets watchlist.
  60. /// </summary>
  61. private readonly object _webSocketsLock = new object();
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
  64. /// </summary>
  65. /// <param name="sessionManager">The session manager.</param>
  66. /// <param name="loggerFactory">The logger factory.</param>
  67. /// <param name="json">The json.</param>
  68. /// <param name="httpServer">The HTTP server.</param>
  69. public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer)
  70. {
  71. _sessionManager = sessionManager;
  72. _logger = loggerFactory.CreateLogger(GetType().Name);
  73. _json = json;
  74. _httpServer = httpServer;
  75. httpServer.WebSocketConnected += OnServerManagerWebSocketConnected;
  76. }
  77. void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
  78. {
  79. var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint);
  80. if (session != null)
  81. {
  82. EnsureController(session, e.Argument);
  83. KeepAliveWebSocket(e.Argument);
  84. }
  85. else
  86. {
  87. _logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url);
  88. }
  89. }
  90. private SessionInfo GetSession(IQueryCollection queryString, string remoteEndpoint)
  91. {
  92. if (queryString == null)
  93. {
  94. return null;
  95. }
  96. var token = queryString["api_key"];
  97. if (string.IsNullOrWhiteSpace(token))
  98. {
  99. return null;
  100. }
  101. var deviceId = queryString["deviceId"];
  102. return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint);
  103. }
  104. public void Dispose()
  105. {
  106. _httpServer.WebSocketConnected -= OnServerManagerWebSocketConnected;
  107. StopKeepAlive();
  108. }
  109. /// <summary>
  110. /// Processes the message.
  111. /// </summary>
  112. /// <param name="message">The message.</param>
  113. /// <returns>Task.</returns>
  114. public Task ProcessMessageAsync(WebSocketMessageInfo message)
  115. => Task.CompletedTask;
  116. private void EnsureController(SessionInfo session, IWebSocketConnection connection)
  117. {
  118. var controllerInfo = session.EnsureController<WebSocketController>(s => new WebSocketController(s, _logger, _sessionManager));
  119. var controller = (WebSocketController)controllerInfo.Item1;
  120. controller.AddWebSocket(connection);
  121. }
  122. /// <summary>
  123. /// Called when a WebSocket is closed.
  124. /// </summary>
  125. /// <param name="sender">The WebSocket.</param>
  126. /// <param name="e">The event arguments.</param>
  127. private void OnWebSocketClosed(object sender, EventArgs e)
  128. {
  129. var webSocket = (IWebSocketConnection) sender;
  130. _logger.LogDebug("WebSocket {0} is closed.", webSocket);
  131. RemoveWebSocket(webSocket);
  132. }
  133. /// <summary>
  134. /// Adds a WebSocket to the KeepAlive watchlist.
  135. /// </summary>
  136. /// <param name="webSocket">The WebSocket to monitor.</param>
  137. private void KeepAliveWebSocket(IWebSocketConnection webSocket)
  138. {
  139. lock (_webSocketsLock)
  140. {
  141. if (!_webSockets.Add(webSocket))
  142. {
  143. _logger.LogWarning("Multiple attempts to keep alive single WebSocket {0}", webSocket);
  144. return;
  145. }
  146. webSocket.Closed += OnWebSocketClosed;
  147. webSocket.LastKeepAliveDate = DateTime.UtcNow;
  148. StartKeepAlive();
  149. }
  150. // Notify WebSocket about timeout
  151. try
  152. {
  153. SendForceKeepAlive(webSocket).Wait();
  154. }
  155. catch (WebSocketException exception)
  156. {
  157. _logger.LogWarning(exception, "Cannot send ForceKeepAlive message to WebSocket {0}.", webSocket);
  158. }
  159. }
  160. /// <summary>
  161. /// Removes a WebSocket from the KeepAlive watchlist.
  162. /// </summary>
  163. /// <param name="webSocket">The WebSocket to remove.</param>
  164. private void RemoveWebSocket(IWebSocketConnection webSocket)
  165. {
  166. lock (_webSocketsLock)
  167. {
  168. if (!_webSockets.Remove(webSocket))
  169. {
  170. _logger.LogWarning("WebSocket {0} not on watchlist.", webSocket);
  171. }
  172. else
  173. {
  174. webSocket.Closed -= OnWebSocketClosed;
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Starts the KeepAlive watcher.
  180. /// </summary>
  181. private void StartKeepAlive()
  182. {
  183. lock (_keepAliveLock)
  184. {
  185. if (_keepAliveCancellationToken == null)
  186. {
  187. _keepAliveCancellationToken = new CancellationTokenSource();
  188. // Start KeepAlive watcher
  189. _ = RepeatAsyncCallbackEvery(
  190. KeepAliveSockets,
  191. TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor),
  192. _keepAliveCancellationToken.Token);
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Stops the KeepAlive watcher.
  198. /// </summary>
  199. private void StopKeepAlive()
  200. {
  201. lock (_keepAliveLock)
  202. {
  203. if (_keepAliveCancellationToken != null)
  204. {
  205. _keepAliveCancellationToken.Cancel();
  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.Any())
  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);
  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.Any())
  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.Any())
  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(new WebSocketMessage<int>
  276. {
  277. MessageType = "ForceKeepAlive",
  278. Data = WebSocketLostTimeout
  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();
  293. Task task = Task.Delay(interval, cancellationToken);
  294. try
  295. {
  296. await task;
  297. }
  298. catch (TaskCanceledException)
  299. {
  300. return;
  301. }
  302. }
  303. }
  304. }
  305. }