SessionWebSocketListener.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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.Common.Extensions;
  9. using MediaBrowser.Controller.Net;
  10. using MediaBrowser.Controller.Session;
  11. using MediaBrowser.Model.Net;
  12. using MediaBrowser.Model.Session;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.Session
  16. {
  17. /// <summary>
  18. /// Class SessionWebSocketListener.
  19. /// </summary>
  20. public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
  21. {
  22. /// <summary>
  23. /// The timeout in seconds after which a WebSocket is considered to be lost.
  24. /// </summary>
  25. private const int WebSocketLostTimeout = 60;
  26. /// <summary>
  27. /// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets.
  28. /// </summary>
  29. private const float IntervalFactor = 0.2f;
  30. /// <summary>
  31. /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
  32. /// </summary>
  33. private const float ForceKeepAliveFactor = 0.75f;
  34. /// <summary>
  35. /// Lock used for accesing the KeepAlive cancellation token.
  36. /// </summary>
  37. private readonly object _keepAliveLock = new object();
  38. /// <summary>
  39. /// The WebSocket watchlist.
  40. /// </summary>
  41. private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>();
  42. /// <summary>
  43. /// Lock used for accessing the WebSockets watchlist.
  44. /// </summary>
  45. private readonly object _webSocketsLock = new object();
  46. private readonly ISessionManager _sessionManager;
  47. private readonly ILogger<SessionWebSocketListener> _logger;
  48. private readonly ILoggerFactory _loggerFactory;
  49. private readonly IAuthorizationContext _authorizationContext;
  50. /// <summary>
  51. /// The KeepAlive cancellation token.
  52. /// </summary>
  53. private CancellationTokenSource _keepAliveCancellationToken;
  54. /// <summary>
  55. /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
  56. /// </summary>
  57. /// <param name="logger">The logger.</param>
  58. /// <param name="sessionManager">The session manager.</param>
  59. /// <param name="loggerFactory">The logger factory.</param>
  60. /// <param name="authorizationContext">The authorization context.</param>
  61. public SessionWebSocketListener(
  62. ILogger<SessionWebSocketListener> logger,
  63. ISessionManager sessionManager,
  64. ILoggerFactory loggerFactory,
  65. IAuthorizationContext authorizationContext)
  66. {
  67. _logger = logger;
  68. _sessionManager = sessionManager;
  69. _loggerFactory = loggerFactory;
  70. _authorizationContext = authorizationContext;
  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, HttpContext httpContext)
  86. {
  87. var session = await GetSession(httpContext, connection.RemoteEndPoint?.ToString()).ConfigureAwait(false);
  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}", httpContext.Request.QueryString);
  96. }
  97. }
  98. private async Task<SessionInfo> GetSession(HttpContext httpContext, string remoteEndpoint)
  99. {
  100. var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(httpContext)
  101. .ConfigureAwait(false);
  102. if (!authorizationInfo.IsAuthenticated)
  103. {
  104. return null;
  105. }
  106. var deviceId = authorizationInfo.DeviceId;
  107. if (httpContext.Request.Query.TryGetValue("deviceId", out var queryDeviceId))
  108. {
  109. deviceId = queryDeviceId;
  110. }
  111. return await _sessionManager.GetSessionByAuthenticationToken(authorizationInfo.Token, deviceId, remoteEndpoint)
  112. .ConfigureAwait(false);
  113. }
  114. private void EnsureController(SessionInfo session, IWebSocketConnection connection)
  115. {
  116. var controllerInfo = session.EnsureController<WebSocketController>(
  117. s => new WebSocketController(_loggerFactory.CreateLogger<WebSocketController>(), s, _sessionManager));
  118. var controller = (WebSocketController)controllerInfo.Item1;
  119. controller.AddWebSocket(connection);
  120. _sessionManager.OnSessionControllerConnected(session);
  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 async Task 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. await SendForceKeepAlive(webSocket).ConfigureAwait(false);
  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.Dispose();
  207. _keepAliveCancellationToken = null;
  208. }
  209. }
  210. lock (_webSocketsLock)
  211. {
  212. foreach (var webSocket in _webSockets)
  213. {
  214. webSocket.Closed -= OnWebSocketClosed;
  215. }
  216. _webSockets.Clear();
  217. }
  218. }
  219. /// <summary>
  220. /// Checks status of KeepAlive of WebSockets.
  221. /// </summary>
  222. private async Task KeepAliveSockets()
  223. {
  224. List<IWebSocketConnection> inactive;
  225. List<IWebSocketConnection> lost;
  226. lock (_webSocketsLock)
  227. {
  228. _logger.LogDebug("Watching {0} WebSockets.", _webSockets.Count);
  229. inactive = _webSockets.Where(i =>
  230. {
  231. var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds;
  232. return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout);
  233. }).ToList();
  234. lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout).ToList();
  235. }
  236. if (inactive.Count > 0)
  237. {
  238. _logger.LogInformation("Sending ForceKeepAlive message to {0} inactive WebSockets.", inactive.Count);
  239. }
  240. foreach (var webSocket in inactive)
  241. {
  242. try
  243. {
  244. await SendForceKeepAlive(webSocket).ConfigureAwait(false);
  245. }
  246. catch (WebSocketException exception)
  247. {
  248. _logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket.");
  249. lost.Add(webSocket);
  250. }
  251. }
  252. lock (_webSocketsLock)
  253. {
  254. if (lost.Count > 0)
  255. {
  256. _logger.LogInformation("Lost {0} WebSockets.", lost.Count);
  257. foreach (var webSocket in lost)
  258. {
  259. // TODO: handle session relative to the lost webSocket
  260. RemoveWebSocket(webSocket);
  261. }
  262. }
  263. if (_webSockets.Count == 0)
  264. {
  265. StopKeepAlive();
  266. }
  267. }
  268. }
  269. /// <summary>
  270. /// Sends a ForceKeepAlive message to a WebSocket.
  271. /// </summary>
  272. /// <param name="webSocket">The WebSocket.</param>
  273. /// <returns>Task.</returns>
  274. private Task SendForceKeepAlive(IWebSocketConnection webSocket)
  275. {
  276. return webSocket.SendAsync(
  277. new WebSocketMessage<int>
  278. {
  279. MessageType = SessionMessageType.ForceKeepAlive,
  280. Data = WebSocketLostTimeout
  281. },
  282. CancellationToken.None);
  283. }
  284. /// <summary>
  285. /// Runs a given async callback once every specified interval time, until cancelled.
  286. /// </summary>
  287. /// <param name="callback">The async callback.</param>
  288. /// <param name="interval">The interval time.</param>
  289. /// <param name="cancellationToken">The cancellation token.</param>
  290. /// <returns>Task.</returns>
  291. private async Task RepeatAsyncCallbackEvery(Func<Task> callback, TimeSpan interval, CancellationToken cancellationToken)
  292. {
  293. while (!cancellationToken.IsCancellationRequested)
  294. {
  295. await callback().ConfigureAwait(false);
  296. try
  297. {
  298. await Task.Delay(interval, cancellationToken).ConfigureAwait(false);
  299. }
  300. catch (TaskCanceledException)
  301. {
  302. return;
  303. }
  304. }
  305. }
  306. }
  307. }