jellyfin/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs

261 lines
8.6 KiB
C#
Raw Normal View History

using System;
2018-12-27 23:27:57 +00:00
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
2018-12-27 23:27:57 +00:00
namespace MediaBrowser.Controller.Net
{
/// <summary>
/// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received.
2018-12-27 23:27:57 +00:00
/// </summary>
/// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
/// <typeparam name="TStateType">The type of the T state type.</typeparam>
public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IDisposable
where TStateType : WebSocketListenerState, new()
where TReturnDataType : class
{
/// <summary>
/// The _active connections.
2018-12-27 23:27:57 +00:00
/// </summary>
private readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>> _activeConnections =
2019-02-27 21:09:22 +00:00
new List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>>();
2018-12-27 23:27:57 +00:00
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
protected abstract string Name { get; }
/// <summary>
/// Gets the data to send.
/// </summary>
/// <returns>Task{`1}.</returns>
2019-02-27 21:09:22 +00:00
protected abstract Task<TReturnDataType> GetDataToSend();
2018-12-27 23:27:57 +00:00
/// <summary>
/// The logger.
2018-12-27 23:27:57 +00:00
/// </summary>
2020-06-06 00:15:56 +00:00
protected ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> Logger;
2018-12-27 23:27:57 +00:00
2020-06-06 00:15:56 +00:00
protected BasePeriodicWebSocketListener(ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> logger)
2018-12-27 23:27:57 +00:00
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
2018-12-27 23:27:57 +00:00
}
Logger = logger;
}
/// <summary>
/// Processes the message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Task.</returns>
2019-02-24 02:16:19 +00:00
public Task ProcessMessageAsync(WebSocketMessageInfo message)
2018-12-27 23:27:57 +00:00
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
2018-12-27 23:27:57 +00:00
}
if (string.Equals(message.MessageType, Name + "Start", StringComparison.OrdinalIgnoreCase))
{
Start(message);
}
if (string.Equals(message.MessageType, Name + "Stop", StringComparison.OrdinalIgnoreCase))
{
Stop(message);
}
2019-02-24 02:16:19 +00:00
return Task.CompletedTask;
2018-12-27 23:27:57 +00:00
}
/// <summary>
/// Starts sending messages over a web socket.
2018-12-27 23:27:57 +00:00
/// </summary>
/// <param name="message">The message.</param>
private void Start(WebSocketMessageInfo message)
{
var vals = message.Data.Split(',');
2019-12-27 14:20:27 +00:00
var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
2018-12-27 23:27:57 +00:00
var cancellationTokenSource = new CancellationTokenSource();
2019-12-27 14:20:27 +00:00
Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
2018-12-27 23:27:57 +00:00
var state = new TStateType
{
IntervalMs = periodMs,
InitialDelayMs = dueTimeMs
};
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
_activeConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>(message.Connection, cancellationTokenSource, state));
2018-12-27 23:27:57 +00:00
}
}
2020-05-25 21:52:51 +00:00
protected async Task SendData(bool force)
2018-12-27 23:27:57 +00:00
{
2019-02-27 21:09:22 +00:00
Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>[] tuples;
2018-12-27 23:27:57 +00:00
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
tuples = _activeConnections
2018-12-27 23:27:57 +00:00
.Where(c =>
{
if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
{
2019-02-27 21:09:22 +00:00
var state = c.Item3;
2018-12-27 23:27:57 +00:00
if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
{
return true;
}
}
return false;
})
.ToArray();
}
2020-05-25 21:52:51 +00:00
IEnumerable<Task> GetTasks()
2018-12-27 23:27:57 +00:00
{
2020-05-25 21:52:51 +00:00
foreach (var tuple in tuples)
{
yield return SendData(tuple);
}
2018-12-27 23:27:57 +00:00
}
2020-05-25 21:52:51 +00:00
await Task.WhenAll(GetTasks()).ConfigureAwait(false);
2018-12-27 23:27:57 +00:00
}
2020-05-25 21:52:51 +00:00
private async Task SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
2018-12-27 23:27:57 +00:00
{
var connection = tuple.Item1;
try
{
2019-02-27 21:09:22 +00:00
var state = tuple.Item3;
2018-12-27 23:27:57 +00:00
var cancellationToken = tuple.Item2.Token;
2019-02-27 21:09:22 +00:00
var data = await GetDataToSend().ConfigureAwait(false);
2018-12-27 23:27:57 +00:00
if (data != null)
{
2020-05-25 21:52:51 +00:00
await connection.SendAsync(
new WebSocketMessage<TReturnDataType>
{
MessageId = Guid.NewGuid(),
2020-05-25 21:52:51 +00:00
MessageType = Name,
Data = data
},
cancellationToken).ConfigureAwait(false);
2018-12-27 23:27:57 +00:00
state.DateLastSendUtc = DateTime.UtcNow;
}
}
catch (OperationCanceledException)
{
if (tuple.Item2.IsCancellationRequested)
{
DisposeConnection(tuple);
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error sending web socket message {Name}", Name);
2018-12-27 23:27:57 +00:00
DisposeConnection(tuple);
}
}
/// <summary>
/// Stops sending messages over a web socket.
2018-12-27 23:27:57 +00:00
/// </summary>
/// <param name="message">The message.</param>
private void Stop(WebSocketMessageInfo message)
{
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
2018-12-27 23:27:57 +00:00
if (connection != null)
{
DisposeConnection(connection);
}
}
}
/// <summary>
/// Disposes the connection.
/// </summary>
/// <param name="connection">The connection.</param>
2019-02-27 21:09:22 +00:00
private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
2018-12-27 23:27:57 +00:00
{
2019-12-27 14:20:27 +00:00
Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
2018-12-27 23:27:57 +00:00
2019-03-05 06:41:41 +00:00
// TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
// connection.Item1.Dispose();
2018-12-27 23:27:57 +00:00
try
{
connection.Item2.Cancel();
connection.Item2.Dispose();
}
catch (ObjectDisposedException)
{
2020-06-14 09:11:11 +00:00
// TODO Investigate and properly fix.
2018-12-27 23:27:57 +00:00
}
lock (_activeConnections)
{
_activeConnections.Remove(connection);
}
2018-12-27 23:27:57 +00:00
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
foreach (var connection in _activeConnections.ToArray())
2018-12-27 23:27:57 +00:00
{
DisposeConnection(connection);
}
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
2019-12-27 14:20:27 +00:00
GC.SuppressFinalize(this);
2018-12-27 23:27:57 +00:00
}
}
public class WebSocketListenerState
{
public DateTime DateLastSendUtc { get; set; }
public long InitialDelayMs { get; set; }
public long IntervalMs { get; set; }
}
}