| 1 | using Zipelo.Core; |
| 2 | using Zipelo.Runtime; |
| 3 | |
| 4 | namespace Zipelo.Worker; |
| 5 | |
| 6 | internal sealed class BoundedMemoryStream(long limit) : MemoryStream |
| 7 | { |
| 8 | private void CheckWrite(int count) |
| 9 | { |
| 10 | if (count < 0 || Position > limit - count) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 11 | } |
| 12 | |
| 13 | public override void Write(byte[] buffer, int offset, int count) |
| 14 | { |
| 15 | CheckWrite(count); |
| 16 | base.Write(buffer, offset, count); |
| 17 | } |
| 18 | |
| 19 | public override void Write(ReadOnlySpan<byte> buffer) |
| 20 | { |
| 21 | CheckWrite(buffer.Length); |
| 22 | base.Write(buffer); |
| 23 | } |
| 24 | |
| 25 | public override void WriteByte(byte value) |
| 26 | { |
| 27 | CheckWrite(1); |
| 28 | base.WriteByte(value); |
| 29 | } |
| 30 | |
| 31 | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) |
| 32 | { |
| 33 | token.ThrowIfCancellationRequested(); |
| 34 | Write(buffer, offset, count); |
| 35 | return Task.CompletedTask; |
| 36 | } |
| 37 | |
| 38 | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) |
| 39 | { |
| 40 | token.ThrowIfCancellationRequested(); |
| 41 | Write(buffer.Span); |
| 42 | return ValueTask.CompletedTask; |
| 43 | } |
| 44 | |
| 45 | public override void SetLength(long value) |
| 46 | { |
| 47 | if (value < 0 || value > limit) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 48 | base.SetLength(value); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // 디스크 저장 없이 단일 ZIP 생성물을 메모리에 확정함. |
| 53 | internal sealed class BoundedMemoryOutput : IOutputTransaction |
| 54 | { |
| 55 | private BoundedMemoryStream? pending; |
| 56 | public byte[]? CommittedBytes { get; private set; } |
| 57 | |
| 58 | public ValueTask<Stream> CreateFileAsync(IReadOnlyList<string> segments, CancellationToken token) |
| 59 | { |
| 60 | token.ThrowIfCancellationRequested(); |
| 61 | if (pending is not null || segments.Count != 1 || segments[0] != "archive.zip") |
| 62 | { |
| 63 | throw new ArchiveException(ArchiveError.OutputConflict); |
| 64 | } |
| 65 | pending = new BoundedMemoryStream(WorkerProtocol.MaxDataBytes); |
| 66 | return ValueTask.FromResult<Stream>(pending); |
| 67 | } |
| 68 | |
| 69 | public ValueTask CommitAsync(CancellationToken token) |
| 70 | { |
| 71 | token.ThrowIfCancellationRequested(); |
| 72 | if (pending is null) { throw new ArchiveException(ArchiveError.OutputUnavailable); } |
| 73 | CommittedBytes = pending.ToArray(); |
| 74 | return ValueTask.CompletedTask; |
| 75 | } |
| 76 | |
| 77 | public ValueTask DisposeAsync() |
| 78 | { |
| 79 | pending?.Dispose(); |
| 80 | pending = null; |
| 81 | return ValueTask.CompletedTask; |
| 82 | } |
| 83 | } |