|
| 1 | +using EntglDb.Core.Storage; |
| 2 | +using EntglDb.Network.Proto; |
| 3 | +using Google.Protobuf; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using System.IO; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace EntglDb.Network.Handlers; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Handles <see cref="MessageType.GetSnapshotReq"/> by streaming the full database snapshot |
| 12 | +/// to the requesting peer in <see cref="MessageType.SnapshotChunkMsg"/> chunks. |
| 13 | +/// Returns <c>(null, MessageType.Unknown)</c> because the response is sent directly via |
| 14 | +/// <see cref="IMessageHandlerContext.SendMessageAsync"/>. |
| 15 | +/// </summary> |
| 16 | +internal sealed class GetSnapshotHandler : INetworkMessageHandler |
| 17 | +{ |
| 18 | + private const int ChunkSizeBytes = 80 * 1024; // 80 KB |
| 19 | + |
| 20 | + private readonly ISnapshotService _snapshotService; |
| 21 | + private readonly ILogger<GetSnapshotHandler> _logger; |
| 22 | + |
| 23 | + public GetSnapshotHandler(ISnapshotService snapshotService, ILogger<GetSnapshotHandler> logger) |
| 24 | + { |
| 25 | + _snapshotService = snapshotService; |
| 26 | + _logger = logger; |
| 27 | + } |
| 28 | + |
| 29 | + public MessageType MessageType => MessageType.GetSnapshotReq; |
| 30 | + |
| 31 | + public async Task<(IMessage? Response, MessageType ResponseType)> HandleAsync(IMessageHandlerContext context) |
| 32 | + { |
| 33 | + _logger.LogInformation("Processing GetSnapshotReq from {Endpoint}", context.RemoteEndPoint); |
| 34 | + var tempFile = Path.GetTempFileName(); |
| 35 | + try |
| 36 | + { |
| 37 | + using (var fs = File.Create(tempFile)) |
| 38 | + { |
| 39 | + await _snapshotService.CreateSnapshotAsync(fs, context.CancellationToken); |
| 40 | + } |
| 41 | + |
| 42 | + using (var fs = File.OpenRead(tempFile)) |
| 43 | + { |
| 44 | + byte[] buffer = new byte[ChunkSizeBytes]; |
| 45 | + int bytesRead; |
| 46 | + while ((bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length, context.CancellationToken)) > 0) |
| 47 | + { |
| 48 | + var chunk = new SnapshotChunk |
| 49 | + { |
| 50 | + Data = ByteString.CopyFrom(buffer, 0, bytesRead), |
| 51 | + IsLast = false |
| 52 | + }; |
| 53 | + await context.SendMessageAsync(MessageType.SnapshotChunkMsg, chunk); |
| 54 | + } |
| 55 | + |
| 56 | + // Signal end of snapshot |
| 57 | + await context.SendMessageAsync(MessageType.SnapshotChunkMsg, new SnapshotChunk { IsLast = true }); |
| 58 | + } |
| 59 | + } |
| 60 | + finally |
| 61 | + { |
| 62 | + if (File.Exists(tempFile)) File.Delete(tempFile); |
| 63 | + } |
| 64 | + return (null, MessageType.Unknown); |
| 65 | + } |
| 66 | +} |
0 commit comments