Add/modify JsonRpc stuff
This commit is contained in:
1 parent
1b7e54e334
commit
240c4e8661
4 files changed
+239
-86
No files matched your search
@@ -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<JsonObject?> req);
|
||||
void OnConnect(WebsocketConnectNotification notification);
|
||||
void OnDisconnect(WebsocketDisconnectNotification notification);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <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(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(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(id, rpcResStr)]);
|
||||
}
|
||||
|
||||
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,6 @@
|
||||
namespace Bts.DataStream.Websocket;
|
||||
|
||||
public enum JsonRpcErrorCode {
|
||||
None = 0,
|
||||
InvalidRequest = 1,
|
||||
}
|
||||
@@ -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<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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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<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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user