team-ljyzipelo

공개
101줄5.1 KB
1using System.IO;
2using Zipelo.Core;
3using Zipelo.Runtime;
4
5namespace Zipelo.Ui;
6
7public sealed record CreationSource(string Name, Func<CancellationToken, Task<Stream>> OpenRead);
8public sealed record CreationResult(JobResult Job, ZipPublicationResult? Publication);
9
10public static class ZipCreationWorkflow
11{
12#if ZIPELO_CREATION_VALIDATION
13 public static bool ValidationEnabled => true;
14#else
15 public static bool ValidationEnabled => false;
16#endif
17 public const string ScopeMessage = "개발 검증용: 파일 최대 1,024개, 합계 16 MiB, 새 ZIP만 저장합니다. 폴더, 암호, 분할은 지원하지 않습니다.";
18
19 public static async Task<CreationResult> RunAsync(ZipWorkerClient client, Guid jobId,
20 IReadOnlyList<CreationSource> sources, string destination, CancellationToken cancellationToken)
21 {
22 if (!ValidationEnabled || !NewZipPublisher.IsSupportedPlatform)
23 {
24 throw new ArchiveException(ArchiveError.UnsupportedOperation);
25 }
26 if (sources.Count is < 1 or > 1024 || !Path.IsPathFullyQualified(destination))
27 {
28 throw new ArchiveException(ArchiveError.BudgetExceeded);
29 }
30 using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
31 deadline.CancelAfter(TimeSpan.FromMinutes(2));
32 var token = deadline.Token;
33 var snapshots = new List<MemoryStream>();
34 var inputs = new List<ZipCreateInput>();
35 var names = new HashSet<string>(OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy));
36 long total = 0;
37 try
38 {
39 var buffer = new byte[65536];
40 foreach (var source in sources)
41 {
42 token.ThrowIfCancellationRequested();
43 if (source.Name.Length > 1024 ||
44 OutputPathPolicy.Validate(source.Name, OutputPathPolicy.CurrentPolicy).Count != 1 ||
45 !names.Add(source.Name))
46 {
47 throw new ArchiveException(ArchiveError.UnsafePath);
48 }
49 await using var input = await source.OpenRead(token).ConfigureAwait(false);
50 using var snapshot = new MemoryStream();
51 int count;
52 while ((count = await input.ReadAsync(buffer.AsMemory(), token).ConfigureAwait(false)) != 0)
53 {
54 total += count;
55 if (total > 16L * 1024 * 1024) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
56 await snapshot.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
57 }
58 // Runtime requires read-only inputs; keep writable staging private.
59 var readOnlySnapshot = new MemoryStream(snapshot.ToArray(), writable: false);
60 snapshots.Add(readOnlySnapshot);
61 inputs.Add(new ZipCreateInput(source.Name, readOnlySnapshot));
62 }
63 var limits = new JobLimits(1024, 16L * 1024 * 1024, 16L * 1024 * 1024,
64 TimeSpan.FromMinutes(2), 3);
65 var result = await client.CreateAsync(jobId, inputs, limits, new ZipCreationOptions(), token)
66 .ConfigureAwait(false);
67 if (result.Job.JobId != jobId) { throw new ArchiveException(ArchiveError.EngineFailure); }
68 if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None)
69 {
70 return new CreationResult(result.Job, null);
71 }
72 var publication = await NewZipPublisher.PublishAsync(result, destination, token).ConfigureAwait(false);
73 return new CreationResult(result.Job, publication);
74 }
75 catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && deadline.IsCancellationRequested)
76 {
77 throw new ArchiveException(ArchiveError.BudgetExceeded);
78 }
79 finally
80 {
81 foreach (var snapshot in snapshots) { snapshot.Dispose(); }
82 }
83 }
84
85 public static string Describe(CreationResult result)
86 {
87 if (result.Publication is { Published: true }) { return "새 ZIP 파일을 저장했습니다. 기존 파일은 덮어쓰지 않았습니다."; }
88 if (result.Publication is { CleanupFailed: true })
89 {
90 return "ZIP 저장에 실패했고 임시 파일 정리도 완료하지 못했습니다. 선택한 저장 폴더를 확인하세요.";
91 }
92 var error = result.Publication?.Error ?? result.Job.Error;
93 return error switch
94 {
95 ArchiveError.Cancelled => "생성이 중지되었습니다. 새 ZIP 파일은 게시되지 않았습니다.",
96 ArchiveError.OutputConflict => "같은 이름의 파일이 있습니다. 기존 파일을 유지했습니다. 새 이름을 선택하세요.",
97 ArchiveError.BudgetExceeded => "파일 크기나 처리 시간 한도를 초과했습니다. 더 작은 파일로 시도하세요.",
98 _ => "새 ZIP 파일을 저장하지 못했습니다. 파일과 저장 위치를 확인하고 다시 시도하세요."
99 };
100 }
101}