chore: Add JsonRpc types for websocket paradigm

This commit is contained in:
John Colvin committed 2025-11-03 16:13:17 -05:00
1 parent 714cf3572e
commit de7c94014e
15 files changed
+587 -2

No files matched your search

@@ -67,7 +67,7 @@ namespace mbts.utils {
throw new ArgumentException($"Must be greater than {value}.", name);
}
public static void GreaterThanEqualTo<T>(T argument, T value, string name) where T : IComparable<T> {
public static void GreaterThanEqualTo<T>(T argument, T value, [CallerArgumentExpression(nameof(argument))] string name = "") where T : IComparable<T> {
if (argument.CompareTo(value) < 0)
throw new ArgumentException($"Must be greater than {value}.", name);
}
@@ -1,3 +1,5 @@
using bts.websocket_core.json_rpc;
using System;
using System.Collections.Generic;
using System.Reflection;
@@ -7,5 +9,10 @@ namespace bts.websocket_core {
public class WebsocketClientID : UniqueID {
public WebsocketClientID() : base(Guid.NewGuid().ToString()) {
}
public WebsocketClientID(string str) : base(str) { }
public static WebsocketClientID? Parse(JsonRpcId id) =>
new(id.ToString()!);
}
}
}
@@ -0,0 +1,11 @@
namespace bts.websocket_core;
public class WebsocketConnectNotification {
public WebsocketConnectNotification(WebsocketClientID id, WebsocketIncomingMessage? message = null) {
Id = id;
Message = message;
}
public WebsocketClientID Id { get; }
public WebsocketIncomingMessage? Message { get; }
}
@@ -0,0 +1,73 @@
namespace bts.websocket_core;
using bts.websocket_core.json_rpc;
public class WebsocketConnectionUpdate {
readonly WebsocketClientID? connection;
readonly WebsocketIncomingMessage? incomingMessage;
readonly WebsocketOutgoingMessage? outgoingMessage;
readonly WebsocketConnectNotification? connect;
readonly WebsocketDisconnectNotification? disconnect;
WebsocketConnectionUpdate(
WebsocketClientID connection,
WebsocketIncomingMessage? incomingMessage = null,
WebsocketOutgoingMessage? outgoingMessage = null,
WebsocketConnectNotification? connect = null,
WebsocketDisconnectNotification? disconnect = null) {
this.connection = connection;
this.incomingMessage = incomingMessage;
this.outgoingMessage = outgoingMessage;
this.connect = connect;
this.disconnect = disconnect;
}
public static WebsocketConnectionUpdate Create(
WebsocketClientID connection, WebsocketConnectNotification connect) =>
new(connection, connect: connect);
public static WebsocketConnectionUpdate Create(
WebsocketClientID connection, WebsocketDisconnectNotification disconnect) =>
new(connection, disconnect: disconnect);
public static WebsocketConnectionUpdate Create(
WebsocketClientID connection, WebsocketIncomingMessage incomingMessage) =>
new(connection, incomingMessage: incomingMessage);
public static WebsocketConnectionUpdate Create(
WebsocketClientID connection, WebsocketOutgoingMessage outgoingMessage) =>
new(connection, outgoingMessage: outgoingMessage);
public WebsocketClientID Connection =>
connection ?? throw new InvalidOperationException();
public WebsocketConnectionUpdateType Type {
get {
if (incomingMessage is not null) {
return WebsocketConnectionUpdateType.IncomingMessage;
}
if (outgoingMessage is not null) {
return WebsocketConnectionUpdateType.OutgoingMessage;
}
if (connect is not null) {
return WebsocketConnectionUpdateType.Connect;
}
if (disconnect is not null) {
return WebsocketConnectionUpdateType.Disconnect;
}
return WebsocketConnectionUpdateType.Unspecified;
}
}
public WebsocketIncomingMessage IncomingMessage =>
incomingMessage ?? throw new InvalidOperationException();
public WebsocketOutgoingMessage OutgoingMessage =>
outgoingMessage ?? throw new InvalidOperationException();
public WebsocketConnectNotification Connect =>
connect ?? throw new InvalidOperationException();
public WebsocketDisconnectNotification Disconnect =>
disconnect ?? throw new InvalidOperationException();
}
@@ -0,0 +1,9 @@
namespace bts.websocket_core;
public enum WebsocketConnectionUpdateType {
Unspecified,
Connect,
IncomingMessage,
OutgoingMessage,
Disconnect
};
@@ -0,0 +1,8 @@
namespace bts.websocket_core;
public class WebsocketDisconnectNotification {
public WebsocketDisconnectNotification(WebsocketClientID id) =>
Id = id;
public WebsocketClientID Id { get; }
}
@@ -0,0 +1,9 @@
namespace bts.websocket_core.json_rpc;
using System.Text.Json.Nodes;
public interface IJsonRpcHandler : IDisposable {
void OnRequest(WebsocketClientID id, JsonRpcRequest<JsonObject?> req);
void OnConnect(WebsocketConnectNotification notification);
void OnDisconnect(WebsocketDisconnectNotification notification);
}
@@ -0,0 +1,134 @@
namespace bts.websocket_core.json_rpc;
using Spark.Core.Disposables;
using System.Reactive.Subjects;
using System.Text.Json;
using System.Text.Json.Nodes;
/// <summary>
/// Represents an I/O model (<see cref="ISubject{TSource, TResult}"/>), 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.
/// </summary>
public abstract class JsonRpcDataSync : ISubject<WebsocketConnectionUpdate, IEnumerable<WebsocketOutgoingMessage>> {
readonly JsonSerializerOptions serializerOpts;
protected readonly object lockObj = new();
protected JsonRpcDataSync(JsonSerializerOptions? serializerOpts = null) =>
this.serializerOpts = serializerOpts ?? JsonSerializerOptions.Default;
event Action<IEnumerable<WebsocketOutgoingMessage>>? 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<IEnumerable<WebsocketOutgoingMessage>> 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<JsonObject?> 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<T>(WebsocketClientID id, string method, T rpcParams) {
var rpcNotification = JsonRpcRequest.CreateNotification(method, rpcParams);
var rpcNotificationStr = JsonSerializer.Serialize(rpcNotification, serializerOpts);
send(new WebsocketOutgoingMessage(id, rpcNotificationStr));
}
protected void sendResponse<T>(WebsocketClientID id, JsonRpcId rpcId, T rpcParams) {
var rpcRes = JsonRpcResponse.Create(rpcId, rpcParams);
var rpcResStr = JsonSerializer.Serialize(rpcRes, serializerOpts);
send(new WebsocketOutgoingMessage(id, rpcResStr));
}
protected void sendError<T>(WebsocketClientID id, JsonRpcId rpcId, JsonRpcError<T> error) {
var rpcRes = JsonRpcResponse.CreateError(rpcId, error);
var rpcResStr = JsonSerializer.Serialize(rpcRes, serializerOpts);
send(new WebsocketOutgoingMessage(id, rpcResStr));
}
protected bool send(params WebsocketOutgoingMessage[] messages) =>
send(messages.AsEnumerable());
protected bool send(IEnumerable<WebsocketOutgoingMessage> 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<JsonRpcId>();
} 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);
}
}
}
@@ -0,0 +1,23 @@
namespace bts.websocket_core.json_rpc;
using System.Text.Json.Serialization;
public static class JsonRpcError {
public static JsonRpcError<T> Create<T>(long code, string? message, T data) =>
new() {
Code = code,
Message = message,
Data = data
};
}
public class JsonRpcError<T> {
[JsonPropertyName("code")]
public long Code { get; set; }
[JsonPropertyName("message")]
public string? Message { get; set; }
[JsonPropertyName("data")]
public T? Data { get; set; }
}
@@ -0,0 +1,6 @@
namespace bts.websocket_core.json_rpc;
public enum JsonRpcErrorCode {
None = 0,
InvalidRequest = 1,
}
@@ -0,0 +1,50 @@
namespace bts.websocket_core.json_rpc;
using System.Text.Json;
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonRpcIdConverter))]
public readonly struct JsonRpcId {
readonly long? int64;
readonly string? str;
JsonRpcId(long int64) =>
this.int64 = int64;
JsonRpcId(string str) =>
this.str = str;
public static JsonRpcId Create() =>
new(DateTime.Now.Ticks);
public override string? ToString() =>
int64?.ToString() ?? str;
class JsonRpcIdConverter : JsonConverter<JsonRpcId> {
public override bool CanConvert(Type typeToConvert) =>
typeToConvert == typeof(JsonRpcId);
public override JsonRpcId Read(
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
if (typeToConvert != typeof(JsonRpcId)) {
throw new ArgumentException($"Unable to parse {typeToConvert}");
}
return reader.TokenType switch {
JsonTokenType.String => new(reader.GetString()!),
JsonTokenType.Number => new(reader.GetInt64()),
_ => throw new ArgumentException($"Unable to parse {typeToConvert} from {reader.TokenType}"),
};
}
public override void Write(
Utf8JsonWriter writer, JsonRpcId value, JsonSerializerOptions options) {
if (value.int64.HasValue) {
writer.WriteNumberValue(value.int64.Value);
}
if (value.str is not null) {
writer.WriteStringValue(value.str);
}
}
}
}
@@ -0,0 +1,92 @@
namespace bts.websocket_core.json_rpc;
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<T> Create<T>(JsonRpcId id, string method, T parameters) =>
new() {
Id = id,
Method = method,
Params = parameters
};
public static JsonRpcRequest<T> CreateNotification<T>(string method, T parameters) =>
new() {
Method = method,
Params = parameters
};
public static bool TryDeserialize(
WebsocketIncomingMessage message,
[NotNullWhen(true)] out JsonRpcRequest<JsonObject?>? result,
[NotNullWhen(false)] out string? error
) {
try {
result = JsonSerializer.Deserialize<JsonRpcRequest<JsonObject?>>(message.message_body)!;
error = null;
return true;
} catch (Exception ex) {
error = ex.ToString();
result = null;
return false;
}
}
public static JsonRpcRequest<TResult> Deserialize<TResult>(this JsonRpcRequest<JsonNode> req) =>
new() {
Method = req.Method,
Params = req.Params.Deserialize<TResult>()!,
JsonRpc = req.JsonRpc,
Id = req.Id,
};
}
public class JsonRpcRequest<T> {
[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;
}
}
}
@@ -0,0 +1,60 @@
namespace bts.websocket_core.json_rpc;
using bts.utils;
using mbts.utils;
using Microsoft.Extensions.Logging;
using System.Net.WebSockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
public class JsonRpcRequestAsyncEnumerable {
public static IAsyncEnumerable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, CancellationToken cancellationToken) =>
Create(webSocket, logger, 4096, cancellationToken);
public static async IAsyncEnumerable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, int bufferCapacity, [EnumeratorCancellation]CancellationToken cancellationToken) {
ExceptionAssert.Argument.GreaterThanEqualTo(bufferCapacity, 0);
var buffer = new byte[bufferCapacity];
var offset = 0;
for (var res = await Recv(); res is not null && !res.CloseStatus.HasValue; res = await Recv()) {
offset += res.Count;
if (offset > buffer.Length) {
throw new InvalidOperationException($"Buffer offset ({offset}) exceeds length ({buffer.Length}).");
} else if (res.EndOfMessage) {
var req = ParseRequest();
offset = 0;
if (req is not null) {
yield return req;
}
} else if (offset == buffer.Length) {
ArrayHelper.expand(ref buffer, buffer.Length * 2);
}
}
async Task<WebSocketReceiveResult?> Recv() {
var offsetBuffer = new ArraySegment<byte>(buffer, offset, buffer.Length - offset);
try {
return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken);
} catch (TaskCanceledException) {
logger.LogTrace("JsonRpcRequestAsyncEnumerable 'ReceiveAsync' task was cancelled (exiting gracefully).");
} catch (Exception ex) {
logger.LogError("JsonRpcRequestAsyncEnumerable Exception while awaiting request: {Exception}", ex);
}
return null;
}
JsonRpcRequest<JsonNode>? ParseRequest() {
try {
return JsonSerializer.Deserialize<JsonRpcRequest<JsonNode>>(
Encoding.UTF8.GetString(new ArraySegment<byte>(buffer, 0, offset)));
} catch (Exception ex) {
logger.LogError("Failed to parse request: {Exception}", ex);
}
return null;
}
}
}
@@ -0,0 +1,74 @@
namespace bts.websocket_core.json_rpc;
using bts.utils;
using mbts.utils;
using Microsoft.Extensions.Logging;
using System.Net.WebSockets;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
public class JsonRpcRequestObservable {
public static IObservable<JsonRpcRequest<JsonNode>> Create(WebSocket webSocket, ILogger logger, int bufferCapacity = 4096) {
ExceptionAssert.Argument.GreaterThanEqualTo(bufferCapacity, 0);
var buffer = new byte[bufferCapacity];
var offset = 0;
return Observable.Create<JsonRpcRequest<JsonNode>>(Subscribe);
IDisposable Subscribe(IObserver<JsonRpcRequest<JsonNode>> observer) {
var cxl = new CancellationTokenSource();
var cxlToken = cxl.Token;
Task.Run(Run);
return Disposable.Create(Dispose);
void Dispose() {
logger.LogInformation("Disposing JsonRpcRequestObservable subscription.");
cxl.Cancel();
}
async Task Run() {
for (var res = await Recv(cxl.Token); res is not null && !res.CloseStatus.HasValue && !cxl.IsCancellationRequested; res = await Recv(cxl.Token)) {
offset += res.Count;
if (offset > buffer.Length) {
throw new InvalidOperationException($"Buffer offset ({offset}) exceeds length ({buffer.Length}).");
} else if (res.EndOfMessage) {
var req = ParseRequest();
offset = 0;
if (req is not null) {
observer.OnNext(req);
}
} else if (offset == buffer.Length) {
ArrayHelper.expand(ref buffer, buffer.Length * 2);
}
}
}
}
async Task<WebSocketReceiveResult?> Recv(CancellationToken cancellationToken) {
var offsetBuffer = new ArraySegment<byte>(buffer, offset, buffer.Length - offset);
try {
return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken);
} catch (TaskCanceledException) {
logger.LogTrace("JsonRpcRequestObservable 'ReceiveAsync' task was cancelled (exiting gracefully).");
} catch (Exception ex) {
logger.LogError("JsonRpcRequestObservable Exception while awaiting request: {Exception}", ex);
}
return null;
}
JsonRpcRequest<JsonNode>? ParseRequest() {
try {
return JsonSerializer.Deserialize<JsonRpcRequest<JsonNode>>(
Encoding.UTF8.GetString(new ArraySegment<byte>(buffer, 0, offset)));
} catch (Exception ex) {
logger.LogError("Failed to parse request: {Exception}", ex);
}
return null;
}
}
}
@@ -0,0 +1,29 @@
namespace bts.websocket_core.json_rpc;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
public static class JsonRpcResponse {
public static JsonRpcResponse<T, JsonObject?> Create<T>(JsonRpcId id, T result) =>
new() { Id = id, Result = result };
public static JsonRpcResponse<JsonObject?, T> CreateError<T>(JsonRpcId? id, JsonRpcError<T> error) =>
new() { Id = id, Error = error };
}
public class JsonRpcResponse<T, TError> {
[JsonPropertyName("id")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public JsonRpcId? Id { get; set; }
[JsonPropertyName("result")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public T? Result { get; set; }
[JsonPropertyName("error")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public JsonRpcError<TError>? Error { get; set; }
[JsonPropertyName("jsonrpc")]
public string JsonRpc { get; set; } = "2.0";
}