From 289f8f1f23c40a421bd36bbf3cf69acbc7a48248 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Sat, 5 Oct 2024 18:23:34 +0200 Subject: [PATCH] Refactor ChunkUploaderWebSocket and add SendChunksAsync method --- .../Models/ChunkUploaderWebSocket.cs | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/BeeNet.Core/Models/ChunkUploaderWebSocket.cs b/src/BeeNet.Core/Models/ChunkUploaderWebSocket.cs index b097c2a..2dcb2eb 100644 --- a/src/BeeNet.Core/Models/ChunkUploaderWebSocket.cs +++ b/src/BeeNet.Core/Models/ChunkUploaderWebSocket.cs @@ -19,7 +19,7 @@ namespace Etherna.BeeNet.Models { - public sealed class ChunkUploaderWebSocket( + public class ChunkUploaderWebSocket( WebSocket webSocket) : IDisposable { @@ -27,13 +27,21 @@ public sealed class ChunkUploaderWebSocket( private readonly byte[] responseBuffer = new byte[SwarmHash.HashSize]; //not really used // Dispose. + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + webSocket.Dispose(); + } + } public void Dispose() { - webSocket.Dispose(); + Dispose(true); + GC.SuppressFinalize(this); } // Methods. - public async Task CloseAsync() + public virtual async Task CloseAsync() { if (webSocket.State == WebSocketState.Open) { @@ -49,7 +57,9 @@ await webSocket.CloseOutputAsync( } } - public async Task SendChunkAsync(SwarmChunk chunk, CancellationToken cancellationToken) + public virtual async Task SendChunkAsync( + SwarmChunk chunk, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(chunk, nameof(chunk)); @@ -62,5 +72,20 @@ public async Task SendChunkAsync(SwarmChunk chunk, CancellationToken cancellatio throw new OperationCanceledException( $"Connection closed by server, message: {response.CloseStatusDescription}"); } + + public virtual async Task SendChunksAsync( + SwarmChunk[] chunks, + Action? onChunkBatchSent = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(chunks, nameof(chunks)); + + // Iterate on chunks. + for (int i = 0; i < chunks.Length; i++) + { + await SendChunkAsync(chunks[i], cancellationToken).ConfigureAwait(false); + onChunkBatchSent?.Invoke(i); + } + } } } \ No newline at end of file