| 1 | using System.Buffers.Binary; |
| 2 | using System.Runtime.CompilerServices; |
| 3 | using System.Text.Json; |
| 4 | using Zipelo.Core; |
| 5 | |
| 6 | [assembly: InternalsVisibleTo("Zipelo.Worker")] |
| 7 | |
| 8 | namespace Zipelo.Runtime; |
| 9 | |
| 10 | public sealed record ZipCreateInput(string EntryName, Stream Content); |
| 11 | public sealed record ZipCreationOptions(bool Encrypt = false, long? SplitVolumeBytes = null); |
| 12 | |
| 13 | // ZIP 바이트의 메모리 전달 결과임. 디스크 저장이나 해제 완료를 뜻하지 않음. |
| 14 | public sealed record ZipWorkerResult(JobResult Job, byte[]? CreatedZip) |
| 15 | { |
| 16 | // 해제된 바이트는 메모리 검증 결과임. 디스크 게시 성공을 뜻하지 않음. |
| 17 | public IReadOnlyList<ZipExtractedEntry>? ExtractedEntries { get; init; } |
| 18 | } |
| 19 | |
| 20 | internal sealed record WorkerRequest(Guid JobId, ArchiveAction Action, byte[][] Inputs, string[] Names, JobLimits Limits); |
| 21 | |
| 22 | internal static class WorkerProtocol |
| 23 | { |
| 24 | internal const int MaxDataBytes = 16 * 1024 * 1024; |
| 25 | internal const int MaxFrameBytes = 32 * 1024 * 1024; |
| 26 | internal const int MaxEntries = 1024; |
| 27 | internal const int MaxNameLength = 1024; |
| 28 | |
| 29 | internal static void ValidateLimits(JobLimits limits) |
| 30 | { |
| 31 | _ = new JobBudget(limits); |
| 32 | if (limits.MaxDuration > TimeSpan.FromMinutes(5)) |
| 33 | { |
| 34 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | internal static ZipWorkerResult Failure(Guid id, ArchiveError error) => new( |
| 39 | new(id, error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, |
| 40 | Array.Empty<EntryResult>(), error), null); |
| 41 | |
| 42 | internal static async Task WriteAsync<T>(Stream stream, T value, CancellationToken token) |
| 43 | { |
| 44 | var payload = JsonSerializer.SerializeToUtf8Bytes(value); |
| 45 | if (payload.Length > MaxFrameBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 46 | var header = new byte[4]; |
| 47 | BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length); |
| 48 | await stream.WriteAsync(header, token).ConfigureAwait(false); |
| 49 | await stream.WriteAsync(payload, token).ConfigureAwait(false); |
| 50 | await stream.FlushAsync(token).ConfigureAwait(false); |
| 51 | } |
| 52 | |
| 53 | internal static async Task<T> ReadAsync<T>(Stream stream, CancellationToken token) |
| 54 | { |
| 55 | var header = new byte[4]; |
| 56 | await stream.ReadExactlyAsync(header, token).ConfigureAwait(false); |
| 57 | var length = BinaryPrimitives.ReadInt32LittleEndian(header); |
| 58 | if (length <= 0 || length > MaxFrameBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 59 | var payload = new byte[length]; |
| 60 | await stream.ReadExactlyAsync(payload, token).ConfigureAwait(false); |
| 61 | return JsonSerializer.Deserialize<T>(payload) ?? throw new ArchiveException(ArchiveError.EngineFailure); |
| 62 | } |
| 63 | } |