87 lines
3.2 KiB
C#
87 lines
3.2 KiB
C#
namespace Bts.DataStreamWebApp.Server.Controllers;
|
|
|
|
using bts.websocket_core.json_rpc;
|
|
|
|
using Bts.DataStreamWebApp.Server.Messages;
|
|
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
public class DataStreamWebSocketServer {
|
|
readonly ILogger logger;
|
|
readonly WebSocket webSocket;
|
|
readonly Dictionary<string, DataStreamSubscription> subscriptions = new();
|
|
|
|
public DataStreamWebSocketServer(WebSocket webSocket, ILogger logger) {
|
|
this.webSocket = webSocket;
|
|
this.logger = logger;
|
|
}
|
|
|
|
public async Task<int> Run() {
|
|
logger.LogInformation("DataStreamWebSocketServer running");
|
|
await foreach (var req in JsonRpcRequestAsyncEnumerable.Create(webSocket, logger)) {
|
|
await (req.Method switch {
|
|
"subscribe" => onSubscribe(req),
|
|
"unsubscribe" => onUnsubscribe(req.Deserialize<UnsubscribeRequest>()),
|
|
_ => Task.CompletedTask,
|
|
});
|
|
}
|
|
logger.LogInformation("DataStreamWebSocketServer stopped");
|
|
return 0;
|
|
}
|
|
|
|
async Task onSubscribe(JsonRpcRequest<JsonNode> req) {
|
|
ArgumentNullException.ThrowIfNull(req.Id);
|
|
ArgumentException.ThrowIfNullOrEmpty(req.Method);
|
|
if (!SubscribeRequest.ParseQuery(req, out var vs, out var subId, out var errMsg, out var errCode)) {
|
|
logger.LogError("Invalid 'subscribe' request: {Reason}", errMsg);
|
|
await send(new JsonRpcError<JsonNode>() {
|
|
Code = (long)errCode,
|
|
Message = $"{errCode}: {errMsg}",
|
|
});
|
|
return;
|
|
}
|
|
if (subscriptions.TryGetValue(subId, out var oldSub)) {
|
|
oldSub.Dispose();
|
|
}
|
|
var sub = new DataStreamSubscription(subId, vs, webSocket, logger);
|
|
subscriptions[subId] = sub;
|
|
await sendSubscriptionStatus(req.Id.Value, subId, req.Method, SubscriptionStatus.Subscribed);
|
|
sub.Start();
|
|
}
|
|
|
|
async Task onUnsubscribe(JsonRpcRequest<UnsubscribeRequest> req) {
|
|
ArgumentNullException.ThrowIfNull(req.Id);
|
|
ArgumentException.ThrowIfNullOrEmpty(req.Method);
|
|
var subId = req.Params?.SubscriptionId ?? string.Empty;
|
|
if (!subscriptions.TryGetValue(subId, out var sub)) {
|
|
logger.LogInformation("Ignoring '{Method}' request because no subscription was found with id {Id}.", req.Method, subId);
|
|
return;
|
|
}
|
|
logger.LogInformation("Disposing subscription");
|
|
sub.Dispose();
|
|
subscriptions.Remove(subId);
|
|
await sendSubscriptionStatus(req.Id.Value, subId, req.Method, SubscriptionStatus.Unsubscribed);
|
|
}
|
|
|
|
Task sendSubscriptionStatus(JsonRpcId reqId, string subId, string method, SubscriptionStatus status) {
|
|
logger.LogInformation("Sending {Method} ack. SubscriptionId = {SubscriptionId}", method, subId);
|
|
return send(JsonRpcResponse.Create(reqId, new SubscriptionStatusMessage() {
|
|
SubscriptionId = subId,
|
|
Status = status,
|
|
}));
|
|
}
|
|
|
|
Task send<T>(T message) {
|
|
if (message is null) {
|
|
return Task.CompletedTask;
|
|
}
|
|
var str = JsonSerializer.Serialize(message);
|
|
var bytes = Encoding.UTF8.GetBytes(str);
|
|
logger.LogTrace("Sending data. Length = {Length}", bytes.Length);
|
|
return webSocket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);
|
|
}
|
|
}
|