126 lines
4.3 KiB
C#
126 lines
4.3 KiB
C#
namespace Bts.DataStreamWebApp.Server.Controllers;
|
|
|
|
using BCG;
|
|
|
|
using bts.websocket_core.json_rpc;
|
|
|
|
using Bts.DataStreamCore;
|
|
using Bts.DataStreamWebApp.Server.Messages;
|
|
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
class DataStreamSubscription : IDisposable, IHostedService {
|
|
public readonly ViewStream ViewStream;
|
|
public DataPacket? LastFired;
|
|
|
|
readonly ILogger logger;
|
|
readonly WebSocket webSocket;
|
|
|
|
public DataStreamSubscription(string id, JsonRpcId requestId, ViewStream viewStream, WebSocket webSocket, ILogger logger) {
|
|
ViewStream = viewStream;
|
|
RequestId = requestId;
|
|
Id = id;
|
|
this.webSocket = webSocket;
|
|
this.logger = logger;
|
|
}
|
|
|
|
public string Id { get; }
|
|
public JsonRpcId RequestId { get; }
|
|
public SubscriptionStatus Status { get; private set; }
|
|
|
|
public void Start() {
|
|
if (Status == SubscriptionStatus.Subscribed) {
|
|
logger.LogWarning("Ignoring redundant call to 'Start'. Id = {Id} Status = {Status}", Id, Status);
|
|
return;
|
|
}
|
|
logger.LogInformation("Subscribing to ViewStream. SubscriptionId = {SubscriptionId}", Id);
|
|
Status = SubscriptionStatus.Subscribed;
|
|
ViewStream.onChange += onChange;
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken) {
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
Start();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task Clear() {
|
|
if (LastFired is null) {
|
|
return Task.CompletedTask;
|
|
}
|
|
logger.LogInformation("Clearing subscription (firing DataPacket to delete all rows). Id = {Id} Status = {Status}", Id, Status);
|
|
return sendDataPacket("clear", new(new BlueTable(LastFired.schema), new BlueTable(LastFired.schema), LastFired.newRows));
|
|
}
|
|
|
|
public void Stop() {
|
|
if (Status == SubscriptionStatus.Unsubscribed) {
|
|
logger.LogWarning("Ignoring redundant call to 'Stop'. Id = {Id} Status = {Status}", Id, Status);
|
|
return;
|
|
}
|
|
logger.LogInformation("Unsubscribing from ViewStream. SubscriptionId = {SubscriptionId}", Id);
|
|
Status = SubscriptionStatus.Unsubscribed;
|
|
ViewStream.onChange -= onChange;
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken) {
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
Stop();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public void Dispose() =>
|
|
Stop();
|
|
|
|
async void onChange(object newValue) {
|
|
if (newValue is not DataPacket dp) {
|
|
logger.LogError("Expected DataPacket in stream callback (actually received {}).", newValue?.GetType());
|
|
return;
|
|
}
|
|
if (webSocket.State != WebSocketState.Open) {
|
|
logger.LogError(
|
|
"Unsubscribing from stream early because WebSocket state = {WebSocketState}", webSocket.State);
|
|
Dispose();
|
|
return;
|
|
}
|
|
await sendDataPacket("subscribe", dp);
|
|
}
|
|
|
|
async Task sendDataPacket(string method, DataPacket dp) {
|
|
var serializerOpts = new JsonSerializerOptions {
|
|
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals
|
|
};
|
|
serializerOpts.Converters.Add(new DataPacketJsonConverter() {
|
|
IncludeCurrent = true,
|
|
UseObjectRows = true,
|
|
});
|
|
var res = JsonRpcRequest.CreateNotification(method, dp);
|
|
var str = serialize(res, serializerOpts);
|
|
if (str is null) {
|
|
logger.LogError("Unsubscribing from stream early because we failed to serialize an outgoing DataPacket");
|
|
Dispose();
|
|
return;
|
|
}
|
|
logger.LogInformation(
|
|
"Sending DataPacket. NumRows = {NumRows} NumCols = {NumCols} MessageLength = {MessageLength}",
|
|
dp.newRows.Count,
|
|
dp.schema.columnNames.Length,
|
|
str.Length);
|
|
var bytes = Encoding.UTF8.GetBytes(str);
|
|
await webSocket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);
|
|
LastFired = dp;
|
|
}
|
|
|
|
string? serialize<T>(T message, JsonSerializerOptions? opts) {
|
|
opts ??= JsonSerializerOptions.Default;
|
|
try {
|
|
return JsonSerializer.Serialize(message, opts);
|
|
} catch (Exception ex) {
|
|
logger.LogError("Failed to serialize message of type {MessageType}: {Exception}", typeof(T), ex);
|
|
}
|
|
return null;
|
|
}
|
|
}
|