| 1 | using System.Diagnostics; |
| 2 | using Zipelo.Core; |
| 3 | |
| 4 | namespace Zipelo.Runtime; |
| 5 | |
| 6 | public sealed class ZipWorkerClient |
| 7 | { |
| 8 | private readonly string workerPath; |
| 9 | private readonly string? dotnetHostPath; |
| 10 | private static readonly IReadOnlyCollection<EngineCapability> Supported = Array.AsReadOnly(new[] |
| 11 | { |
| 12 | new EngineCapability("zip", ArchiveAction.List), |
| 13 | new EngineCapability("zip", ArchiveAction.Create) |
| 14 | }); |
| 15 | |
| 16 | // 호출자가 신뢰하는 앱 배포 경로만 전달함. 압축파일에서 실행 경로를 얻지 않음. |
| 17 | public ZipWorkerClient(string workerPath, string? dotnetHostPath = null) |
| 18 | { |
| 19 | if (!Path.IsPathFullyQualified(workerPath) || |
| 20 | (dotnetHostPath is not null && !Path.IsPathFullyQualified(dotnetHostPath))) |
| 21 | { |
| 22 | throw new ArgumentException("작업자와 호스트의 절대 경로가 필요함"); |
| 23 | } |
| 24 | this.workerPath = workerPath; |
| 25 | this.dotnetHostPath = dotnetHostPath; |
| 26 | } |
| 27 | |
| 28 | public bool IsAvailable => File.Exists(workerPath) && |
| 29 | (!workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || |
| 30 | (dotnetHostPath is not null && File.Exists(dotnetHostPath))); |
| 31 | public IReadOnlyCollection<EngineCapability> Capabilities => IsAvailable ? Supported : Array.Empty<EngineCapability>(); |
| 32 | public bool SupportsEncryption => false; |
| 33 | public bool SupportsSplitVolumes => false; |
| 34 | public bool SupportsSafeExtraction => false; |
| 35 | public bool SupportsFilePublication => NewZipPublisher.IsSupportedPlatform; |
| 36 | |
| 37 | // 입력은 읽기 전용 스트림의 현재 위치부터 복사하며 수명은 호출자가 소유함. |
| 38 | public Task<ZipWorkerResult> ListAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token) |
| 39 | => ExecuteAsync(jobId, ArchiveAction.List, new[] { zip }, Array.Empty<string>(), limits, token); |
| 40 | |
| 41 | public Task<ZipWorkerResult> ExtractAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token) |
| 42 | => ExecuteAsync(jobId, ArchiveAction.Extract, new[] { zip }, Array.Empty<string>(), limits, token); |
| 43 | |
| 44 | // 일반 UI 해제 능력은 OS별 저장 검증 뒤에 별도로 활성화함. |
| 45 | public bool SupportsMemoryExtraction => IsAvailable; |
| 46 | |
| 47 | public Task<ZipWorkerResult> CreateAsync(Guid jobId, IReadOnlyList<ZipCreateInput> inputs, |
| 48 | JobLimits limits, ZipCreationOptions? options, CancellationToken token) |
| 49 | { |
| 50 | ArgumentNullException.ThrowIfNull(inputs); |
| 51 | if (options is { Encrypt: true } || options?.SplitVolumeBytes is not null) |
| 52 | { |
| 53 | return Task.FromResult(WorkerProtocol.Failure(jobId, ArchiveError.UnsupportedOperation)); |
| 54 | } |
| 55 | return ExecuteAsync(jobId, ArchiveAction.Create, inputs.Select(input => input.Content).ToArray(), |
| 56 | inputs.Select(input => input.EntryName).ToArray(), limits, token); |
| 57 | } |
| 58 | |
| 59 | private async Task<ZipWorkerResult> ExecuteAsync(Guid jobId, ArchiveAction action, |
| 60 | IReadOnlyList<Stream> inputs, string[] names, JobLimits limits, CancellationToken token) |
| 61 | { |
| 62 | Process? process = null; |
| 63 | var started = false; |
| 64 | Task? drain = null; |
| 65 | using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); |
| 66 | try |
| 67 | { |
| 68 | if (jobId == Guid.Empty) { throw new ArchiveException(ArchiveError.UnsupportedOperation); } |
| 69 | WorkerProtocol.ValidateLimits(limits); |
| 70 | deadline.CancelAfter(limits.MaxDuration); |
| 71 | var operationToken = deadline.Token; |
| 72 | operationToken.ThrowIfCancellationRequested(); |
| 73 | if (!IsAvailable) { throw new ArchiveException(ArchiveError.EngineUnavailable); } |
| 74 | if (inputs.Count == 0 || inputs.Count > WorkerProtocol.MaxEntries || |
| 75 | names.Any(name => name is null || name.Length > WorkerProtocol.MaxNameLength)) |
| 76 | { |
| 77 | throw new ArchiveException(ArchiveError.BudgetExceeded); |
| 78 | } |
| 79 | |
| 80 | var copies = new byte[inputs.Count][]; |
| 81 | long total = 0; |
| 82 | var buffer = new byte[64 * 1024]; |
| 83 | for (var index = 0; index < inputs.Count; index++) |
| 84 | { |
| 85 | var source = inputs[index]; |
| 86 | if (source is null || !source.CanRead || source.CanWrite) |
| 87 | { |
| 88 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 89 | } |
| 90 | using var copy = new MemoryStream(); |
| 91 | int count; |
| 92 | while ((count = await source.ReadAsync(buffer, operationToken).ConfigureAwait(false)) != 0) |
| 93 | { |
| 94 | total += count; |
| 95 | if (total > WorkerProtocol.MaxDataBytes || total > limits.MaxProcessedBytes) |
| 96 | { |
| 97 | throw new ArchiveException(ArchiveError.BudgetExceeded); |
| 98 | } |
| 99 | copy.Write(buffer, 0, count); |
| 100 | } |
| 101 | copies[index] = copy.ToArray(); |
| 102 | } |
| 103 | |
| 104 | var start = new ProcessStartInfo |
| 105 | { |
| 106 | FileName = workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? dotnetHostPath! : workerPath, |
| 107 | UseShellExecute = false, |
| 108 | CreateNoWindow = true, |
| 109 | RedirectStandardInput = true, |
| 110 | RedirectStandardOutput = true, |
| 111 | RedirectStandardError = true |
| 112 | }; |
| 113 | if (workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { start.ArgumentList.Add(workerPath); } |
| 114 | process = new Process { StartInfo = start }; |
| 115 | if (!process.Start()) { throw new ArchiveException(ArchiveError.EngineUnavailable); } |
| 116 | // stderr는 보관하거나 UI에 노출하지 않고 배출함. |
| 117 | started = true; |
| 118 | drain = process.StandardError.BaseStream.CopyToAsync(Stream.Null, operationToken); |
| 119 | await WorkerProtocol.WriteAsync(process.StandardInput.BaseStream, |
| 120 | new WorkerRequest(jobId, action, copies, names, limits), operationToken).ConfigureAwait(false); |
| 121 | process.StandardInput.Close(); |
| 122 | var result = await WorkerProtocol.ReadAsync<ZipWorkerResult>(process.StandardOutput.BaseStream, operationToken) |
| 123 | .ConfigureAwait(false); |
| 124 | await process.WaitForExitAsync(operationToken).ConfigureAwait(false); |
| 125 | await drain.ConfigureAwait(false); |
| 126 | if (process.ExitCode != 0 || result.Job.JobId != jobId || |
| 127 | result.Job.State is not (JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed) || |
| 128 | (result.Job.State == JobState.Completed && result.Job.Error != ArchiveError.None) || |
| 129 | result.Job.Entries.Count > WorkerProtocol.MaxEntries + 1 || |
| 130 | result.CreatedZip?.Length > WorkerProtocol.MaxDataBytes || |
| 131 | (action == ArchiveAction.Create && result.Job.State == JobState.Completed && result.CreatedZip is null) || |
| 132 | (result.CreatedZip is not null && (action != ArchiveAction.Create || result.Job.State != JobState.Completed))) |
| 133 | { |
| 134 | throw new ArchiveException(ArchiveError.EngineFailure); |
| 135 | } |
| 136 | if (action == ArchiveAction.Extract && result.Job.State == JobState.Completed) |
| 137 | { |
| 138 | _ = ZipExtraction.ValidateResult(result, operationToken, snapshot: false); |
| 139 | } |
| 140 | else if (result.ExtractedEntries is not null) |
| 141 | { |
| 142 | throw new ArchiveException(ArchiveError.EngineFailure); |
| 143 | } |
| 144 | return result; |
| 145 | } |
| 146 | catch (OperationCanceledException) when (deadline.IsCancellationRequested) |
| 147 | { |
| 148 | return WorkerProtocol.Failure(jobId, token.IsCancellationRequested ? ArchiveError.Cancelled : ArchiveError.BudgetExceeded); |
| 149 | } |
| 150 | catch (ArchiveException failure) { return WorkerProtocol.Failure(jobId, failure.Code); } |
| 151 | catch (ArgumentException) { return WorkerProtocol.Failure(jobId, ArchiveError.UnsupportedOperation); } |
| 152 | catch { return WorkerProtocol.Failure(jobId, ArchiveError.EngineFailure); } |
| 153 | finally |
| 154 | { |
| 155 | if (process is not null) |
| 156 | { |
| 157 | try |
| 158 | { |
| 159 | // 취소 응답 전에 실제 작업자 종료를 기다림. 종료 실패를 성공으로 숨기지 않음. |
| 160 | if (started && !process.HasExited) |
| 161 | { |
| 162 | process.Kill(entireProcessTree: true); |
| 163 | await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); |
| 164 | } |
| 165 | } |
| 166 | finally |
| 167 | { |
| 168 | deadline.Cancel(); |
| 169 | if (drain is not null) |
| 170 | { |
| 171 | try { await drain.ConfigureAwait(false); } |
| 172 | catch { } |
| 173 | } |
| 174 | process.Dispose(); |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | } |