From 7cf90d95da827ee91c2bf80a75dca9b225b6becf Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 19 Jun 2024 14:37:30 -0400 Subject: [PATCH] Add JsonRpcRequestObservable, AsyncEnumerable --- .../JsonRpc/JsonRpcRequestAsyncEnumerable.cs | 57 ++++++++++++++ .../JsonRpc/JsonRpcRequestObservable.cs | 74 +++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs create mode 100644 src/client/spark_websocket/JsonRpc/JsonRpcRequestObservable.cs diff --git a/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs b/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs new file mode 100644 index 000000000..89e9ca6df --- /dev/null +++ b/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs @@ -0,0 +1,57 @@ +namespace bts.websocket_core.json_rpc; + +using bts.utils; + +using mbts.utils; + +using Microsoft.Extensions.Logging; + +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +public class JsonRpcRequestAsyncEnumerable { + public static async IAsyncEnumerable> Create(WebSocket webSocket, ILogger logger, int bufferCapacity = 4096, CancellationToken? cancellationToken = null) { + ExceptionAssert.Argument.GreaterThanEqualTo(bufferCapacity, 0); + cancellationToken ??= CancellationToken.None; + 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 Recv() { + var offsetBuffer = new ArraySegment(buffer, offset, buffer.Length - offset); + try { + return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken.Value); + } 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? ParseRequest() { + try { + return JsonSerializer.Deserialize>( + Encoding.UTF8.GetString(new ArraySegment(buffer, 0, offset))); + } catch (Exception ex) { + logger.LogError("Failed to parse request: {Exception}", ex); + } + return null; + } + } +} diff --git a/src/client/spark_websocket/JsonRpc/JsonRpcRequestObservable.cs b/src/client/spark_websocket/JsonRpc/JsonRpcRequestObservable.cs new file mode 100644 index 000000000..c06384ed2 --- /dev/null +++ b/src/client/spark_websocket/JsonRpc/JsonRpcRequestObservable.cs @@ -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> Create(WebSocket webSocket, ILogger logger, int bufferCapacity = 4096) { + ExceptionAssert.Argument.GreaterThanEqualTo(bufferCapacity, 0); + var buffer = new byte[bufferCapacity]; + var offset = 0; + return Observable.Create>(Subscribe); + + IDisposable Subscribe(IObserver> 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 Recv(CancellationToken cancellationToken) { + var offsetBuffer = new ArraySegment(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? ParseRequest() { + try { + return JsonSerializer.Deserialize>( + Encoding.UTF8.GetString(new ArraySegment(buffer, 0, offset))); + } catch (Exception ex) { + logger.LogError("Failed to parse request: {Exception}", ex); + } + return null; + } + } +}