From eff979fb2b39ec707db11c0cfbbabd33046b808f Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 11 Jul 2024 09:16:58 -0400 Subject: [PATCH] improvement: Accept CancellationToken in JsonRpcRequestObservable --- .../JsonRpc/JsonRpcRequestAsyncEnumerable.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs b/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs index 89e9ca6df..de2c01c44 100644 --- a/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs +++ b/src/client/spark_websocket/JsonRpc/JsonRpcRequestAsyncEnumerable.cs @@ -7,14 +7,17 @@ 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 async IAsyncEnumerable> Create(WebSocket webSocket, ILogger logger, int bufferCapacity = 4096, CancellationToken? cancellationToken = null) { + public static IAsyncEnumerable> Create(WebSocket webSocket, ILogger logger, CancellationToken cancellationToken) => + Create(webSocket, logger, 4096, cancellationToken); + + public static async IAsyncEnumerable> Create(WebSocket webSocket, ILogger logger, int bufferCapacity, [EnumeratorCancellation]CancellationToken cancellationToken) { 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()) { @@ -35,7 +38,7 @@ public class JsonRpcRequestAsyncEnumerable { async Task Recv() { var offsetBuffer = new ArraySegment(buffer, offset, buffer.Length - offset); try { - return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken.Value); + return await webSocket.ReceiveAsync(offsetBuffer, cancellationToken); } catch (TaskCanceledException) { logger.LogTrace("JsonRpcRequestAsyncEnumerable 'ReceiveAsync' task was cancelled (exiting gracefully)."); } catch (Exception ex) {