diff --git a/src/client/spark_websocket/IJsonRpcHandler.cs b/src/client/spark_websocket/IJsonRpcHandler.cs new file mode 100644 index 000000000..73b535dc2 --- /dev/null +++ b/src/client/spark_websocket/IJsonRpcHandler.cs @@ -0,0 +1,11 @@ +namespace Bts.Websocket { + using bts.websocket_core; + + using System.Text.Json.Nodes; + + public interface IJsonRpcHandler : IDisposable { + void OnRequest(WebsocketClientID id, JsonRpcRequest req); + void OnConnect(WebsocketConnectNotification notification); + void OnDisconnect(WebsocketDisconnectNotification notification); + } +} diff --git a/src/client/spark_websocket/JsonRpcDataSync.cs b/src/client/spark_websocket/JsonRpcDataSync.cs new file mode 100644 index 000000000..bd014af18 --- /dev/null +++ b/src/client/spark_websocket/JsonRpcDataSync.cs @@ -0,0 +1,136 @@ +namespace Bts.DataStream.Websocket; + +using bts; +using bts.websocket_core; + +using Bts.Websocket; + +using Spark.Core.Disposables; + +using System.Reactive.Subjects; +using System.Text.Json; +using System.Text.Json.Nodes; + +/// +/// Represents an I/O model (), that accepts websocket +/// requests (from clients) as input, and emits data/notifications (to clients) as output. +/// This class's chief role is managing data subscriptions to sparkd on the clients' behalf. +/// +public abstract class JsonRpcDataSync : ISubject> { + readonly JsonSerializerOptions serializerOpts; + protected readonly object lockObj = new(); + + protected JsonRpcDataSync(JsonSerializerOptions? serializerOpts = null) => + this.serializerOpts = serializerOpts ?? JsonSerializerOptions.Default; + + event Action>? requestSend; + + public void OnCompleted() => + Log.Api.info("DataSync incoming request stream has completed."); + + public void OnError(Exception error) => + Log.Api.error($"DataSync error: {error}"); + + public void OnNext(WebsocketConnectionUpdate value) { + switch (value.Type) { + case WebsocketConnectionUpdateType.IncomingMessage: + onIncomingMessage(value.IncomingMessage); + break; + case WebsocketConnectionUpdateType.Connect: + Log.Api.info($"DataStreamWebsocketDataSync client connected. clientId: {value.Connect.Id}"); + onConnect(value.Connect); + if (value.Connect.Message is not null) { + onIncomingMessage(value.Connect.Message); + } + break; + case WebsocketConnectionUpdateType.Disconnect: + onDisconnect(value.Disconnect); + break; + default: + Log.assert(false, $"Unexpected WebsocketConnectionUpdate type: {value.Type}"); + break; + } + } + + public IDisposable Subscribe(IObserver> observer) { + lock (lockObj) { + requestSend += observer.OnNext; + return Disposable.Create(Dispose); + } + void Dispose() { + lock (lockObj) { + requestSend -= observer.OnNext; + } + } + } + + protected abstract void onConnect(WebsocketConnectNotification notification); + protected abstract void onDisconnect(WebsocketDisconnectNotification notification); + protected abstract void onRequest(WebsocketClientID id, JsonRpcRequest req); + + protected virtual void onInvalidRequest(WebsocketIncomingMessage request, string? errorMsg) { + var logMsg = $"Recieved invalid request:\n{request.message_body}"; + if (errorMsg is not null) { + logMsg += $"\n\n**Exception**\n{errorMsg}"; + } + Log.Api.error(logMsg); + var rpcId = extractRpcId(request.message_body); + if (rpcId is not null) { + // Send error back to client + var rpcErr = JsonRpcError.Create( + (long)JsonRpcErrorCode.InvalidRequest, + $"Received invalid request: {errorMsg ?? "unknown error"}", + request.message_body); + sendError(request.sender_client_id, rpcId.Value, rpcErr); + } + } + + protected void sendNotification(WebsocketClientID id, string method, T rpcParams) { + var rpcNotification = JsonRpcRequest.CreateNotification(method, rpcParams); + var rpcNotificationStr = JsonSerializer.Serialize(rpcNotification, serializerOpts); + send([new(id, rpcNotificationStr)]); + } + + protected void sendResponse(WebsocketClientID id, JsonRpcId rpcId, T rpcParams) { + var rpcRes = JsonRpcResponse.Create(rpcId, rpcParams); + var rpcResStr = JsonSerializer.Serialize(rpcRes, serializerOpts); + send([new(id, rpcResStr)]); + } + + protected void sendError(WebsocketClientID id, JsonRpcId rpcId, JsonRpcError error) { + var rpcRes = JsonRpcResponse.CreateError(rpcId, error); + var rpcResStr = JsonSerializer.Serialize(rpcRes, serializerOpts); + send([new(id, rpcResStr)]); + } + + protected bool send(IEnumerable messages) { + lock (lockObj) { + if (requestSend is null) { + Log.Api.warn( + $"Unable to send message(s) because '{nameof(requestSend)}' handler is null"); + return false; + } + requestSend(messages); + return true; + } + } + + static JsonRpcId? extractRpcId(string messageBody) { + try { + return JsonNode.Parse(messageBody) + ?.AsObject() + ?.GetValueOrDefault("id") + ?.Deserialize(); + } catch { + return null; + } + } + + void onIncomingMessage(WebsocketIncomingMessage message) { + if (JsonRpcRequest.TryDeserialize(message, out var req, out var err)) { + onRequest(message.sender_client_id, req); + } else { + onInvalidRequest(message, err); + } + } +} diff --git a/src/client/spark_websocket/JsonRpcErrorCode.cs b/src/client/spark_websocket/JsonRpcErrorCode.cs new file mode 100644 index 000000000..63da42224 --- /dev/null +++ b/src/client/spark_websocket/JsonRpcErrorCode.cs @@ -0,0 +1,6 @@ +namespace Bts.DataStream.Websocket; + +public enum JsonRpcErrorCode { + None = 0, + InvalidRequest = 1, +} diff --git a/src/client/spark_websocket/JsonRpcRequest.cs b/src/client/spark_websocket/JsonRpcRequest.cs index 037590e7d..8a68ecb3d 100644 --- a/src/client/spark_websocket/JsonRpcRequest.cs +++ b/src/client/spark_websocket/JsonRpcRequest.cs @@ -1,86 +1,86 @@ -namespace Bts.Websocket; - -using bts.websocket_core; - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; - -public static class JsonRpcRequest { - public static JsonRpcRequest Create(JsonRpcId id, string method, T parameters) => - new() { - Id = id, - Method = method, - Params = parameters - }; - - public static JsonRpcRequest CreateNotification(string method, T parameters) => - new() { - Method = method, - Params = parameters - }; - - public static bool TryDeserialize( - WebsocketIncomingMessage message, - [NotNullWhen(true)]out JsonRpcRequest? result, - [NotNullWhen(false)]out string? error - ) { - try { - result = JsonSerializer.Deserialize>(message.message_body)!; - error = null; - return true; - } catch (Exception ex) { - error = ex.ToString(); - result = null; - return false; - } - } -} - -public class JsonRpcRequest { - [JsonPropertyName("method")] - public string? Method { get; set; } - - [JsonPropertyName("params")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [MaybeNull] - public T Params { get; set; } - - [JsonPropertyName("jsonrpc")] - public string JsonRpc { get; set; } = "2.0"; - - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("id")] - public JsonRpcId? Id { get; set; } - - [JsonIgnore] - public bool IsNotification => - !Id.HasValue; - - public string Serialize() => - Serialize(JsonSerializerOptions.Default); - - public string Serialize(JsonSerializerOptions opts) => - JsonSerializer.Serialize(this, opts); - - public bool SerializeSafe( - [NotNullWhen(true)]out string? result, - [NotNullWhen(false)]out Exception? error) => - SerializeSafe(JsonSerializerOptions.Default, out result, out error); - - public bool SerializeSafe( - JsonSerializerOptions opts, - [NotNullWhen(true)]out string? result, - [NotNullWhen(false)]out Exception? error) { - try { - result = JsonSerializer.Serialize(this, opts); - error = null; - return true; - } catch (Exception ex) { - error = ex; - result = null; - return false; - } - } -} +namespace Bts.Websocket; + +using bts.websocket_core; + +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; + +public static class JsonRpcRequest { + public static JsonRpcRequest Create(JsonRpcId id, string method, T parameters) => + new() { + Id = id, + Method = method, + Params = parameters + }; + + public static JsonRpcRequest CreateNotification(string method, T parameters) => + new() { + Method = method, + Params = parameters + }; + + public static bool TryDeserialize( + WebsocketIncomingMessage message, + [NotNullWhen(true)]out JsonRpcRequest? result, + [NotNullWhen(false)]out string? error + ) { + try { + result = JsonSerializer.Deserialize>(message.message_body)!; + error = null; + return true; + } catch (Exception ex) { + error = ex.ToString(); + result = null; + return false; + } + } +} + +public class JsonRpcRequest { + [JsonPropertyName("method")] + public string? Method { get; set; } + + [JsonPropertyName("params")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [MaybeNull] + public T Params { get; set; } + + [JsonPropertyName("jsonrpc")] + public string JsonRpc { get; set; } = "2.0"; + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("id")] + public JsonRpcId? Id { get; set; } + + [JsonIgnore] + public bool IsNotification => + !Id.HasValue; + + public string Serialize() => + Serialize(JsonSerializerOptions.Default); + + public string Serialize(JsonSerializerOptions opts) => + JsonSerializer.Serialize(this, opts); + + public bool SerializeSafe( + [NotNullWhen(true)]out string? result, + [NotNullWhen(false)]out Exception? error) => + SerializeSafe(JsonSerializerOptions.Default, out result, out error); + + public bool SerializeSafe( + JsonSerializerOptions opts, + [NotNullWhen(true)]out string? result, + [NotNullWhen(false)]out Exception? error) { + try { + result = JsonSerializer.Serialize(this, opts); + error = null; + return true; + } catch (Exception ex) { + error = ex; + result = null; + return false; + } + } +}