| 1 | using Zipelo.Core; |
| 2 | using Zipelo.Runtime; |
| 3 | using Zipelo.Worker; |
| 4 | |
| 5 | // 요청 한 건을 처리하고 종료함. 경로나 암호를 명령행으로 받지 않음. |
| 6 | if (args.Length != 0) { return 2; } |
| 7 | AppContext.SetSwitch("System.IO.Compression.UseStrictValidation", true); |
| 8 | using var lifetime = new CancellationTokenSource(TimeSpan.FromMinutes(5)); |
| 9 | var id = Guid.Empty; |
| 10 | ZipWorkerResult response; |
| 11 | try |
| 12 | { |
| 13 | var request = await WorkerProtocol.ReadAsync<WorkerRequest>(Console.OpenStandardInput(), lifetime.Token); |
| 14 | id = request.JobId; |
| 15 | WorkerProtocol.ValidateLimits(request.Limits); |
| 16 | if (id == Guid.Empty || request.Inputs is null || request.Names is null || |
| 17 | request.Inputs.Length == 0 || request.Inputs.Length > WorkerProtocol.MaxEntries || |
| 18 | request.Inputs.Any(input => input is null) || |
| 19 | request.Inputs.Sum(input => (long)input.Length) > WorkerProtocol.MaxDataBytes || |
| 20 | request.Names.Any(name => name is null || name.Length > WorkerProtocol.MaxNameLength) || |
| 21 | (request.Action is ArchiveAction.List or ArchiveAction.Extract && (request.Inputs.Length != 1 || request.Names.Length != 0)) || |
| 22 | (request.Action == ArchiveAction.Create && request.Names.Length != request.Inputs.Length)) |
| 23 | { |
| 24 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 25 | } |
| 26 | if (request.Action == ArchiveAction.Extract) |
| 27 | { |
| 28 | response = ZipExtractor.Extract(request, lifetime.Token); |
| 29 | } |
| 30 | else |
| 31 | { |
| 32 | var inputs = request.Inputs.Select(input => (Stream)new MemoryStream(input, writable: false)).ToArray(); |
| 33 | try |
| 34 | { |
| 35 | var output = new BoundedMemoryOutput(); |
| 36 | var result = await new ArchiveJob(id, request.Limits).ExecuteAsync(request.Action, "zip", |
| 37 | new BuiltInZipEngine(request.Names, request.Limits.MaxOutputBytes), inputs, output, |
| 38 | (_, _) => throw new ArchiveException(ArchiveError.UnsupportedOperation), null, lifetime.Token); |
| 39 | response = new(result, result.State == JobState.Completed ? output.CommittedBytes : null); |
| 40 | } |
| 41 | finally |
| 42 | { |
| 43 | foreach (var input in inputs) { input.Dispose(); } |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | catch (ArchiveException failure) { response = WorkerProtocol.Failure(id, failure.Code); } |
| 48 | catch (OperationCanceledException) { response = WorkerProtocol.Failure(id, ArchiveError.BudgetExceeded); } |
| 49 | catch { response = WorkerProtocol.Failure(id, ArchiveError.EngineFailure); } |
| 50 | try |
| 51 | { |
| 52 | await WorkerProtocol.WriteAsync(Console.OpenStandardOutput(), response, lifetime.Token); |
| 53 | return 0; |
| 54 | } |
| 55 | catch { return 1; } |