team-ljyzipelo

공개
125줄5.5 KB
1namespace Zipelo.Core;
2
3public sealed class ArchiveJob
4{
5 private readonly Guid id;
6 private readonly JobLimits limits;
7 private int started;
8
9 public ArchiveJob(Guid id, JobLimits limits)
10 {
11 if (id == Guid.Empty) { throw new ArgumentException("작업 ID가 필요함", nameof(id)); }
12 this.id = id;
13 this.limits = limits;
14 }
15
16 // 입력 수명은 호출자가 소유함. 출력 트랜잭션은 작업이 소유하여 종료 전에 정리함.
17 public async Task<JobResult> ExecuteAsync(ArchiveAction action, string format, IArchiveEngine engine,
18 IReadOnlyList<Stream> readOnlyInputs, IOutputTransaction output, PasswordProvider passwords,
19 IProgress<JobEvent>? progress, CancellationToken cancellationToken)
20 {
21 ArgumentNullException.ThrowIfNull(engine);
22 ArgumentNullException.ThrowIfNull(readOnlyInputs);
23 ArgumentNullException.ThrowIfNull(output);
24 ArgumentNullException.ThrowIfNull(passwords);
25 if (Interlocked.Exchange(ref started, 1) != 0)
26 {
27 throw new InvalidOperationException("작업 인스턴스는 재사용할 수 없음");
28 }
29
30 JobBudget? budget = null;
31 EngineContext? context = null;
32 CancellationTokenSource? linked = null;
33 CancellationTokenRegistration cancellationRegistration = default;
34 var eventGate = new object();
35 long sequence = 0;
36 void Report(JobState reportedState)
37 {
38 lock (eventGate)
39 {
40 if ((reportedState is JobState.Running or JobState.WaitingForPassword) &&
41 (cancellationToken.IsCancellationRequested || linked?.IsCancellationRequested == true))
42 {
43 reportedState = JobState.Cancelling;
44 }
45
46 // 관찰자 오류가 정리나 실제 작업 결과를 바꾸지 않도록 함.
47 try { progress?.Report(new(id, ++sequence, reportedState, budget?.Usage.ProcessedBytes ?? 0)); }
48 catch { }
49 }
50 }
51
52 var state = JobState.Failed;
53 var error = ArchiveError.None;
54 var committed = false;
55 try
56 {
57 // 출력 소유권을 받은 뒤의 초기화도 정리 범위에 포함함.
58 budget = new JobBudget(limits);
59 linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
60 cancellationRegistration = linked.Token.Register(() => Report(JobState.Cancelling));
61 var inputs = readOnlyInputs.ToArray();
62 context = new EngineContext(id, action, budget, output, passwords, Report, linked, limits.MaxPasswordAttempts);
63 budget.Check(linked.Token);
64 if (inputs.Length == 0 || inputs.Any(input => input is null || !input.CanRead || input.CanWrite))
65 {
66 throw new ArchiveException(ArchiveError.UnsupportedOperation);
67 }
68 if (!engine.Capabilities.Any(capability => capability.Action == action &&
69 string.Equals(capability.Format, format, StringComparison.OrdinalIgnoreCase)))
70 {
71 throw new ArchiveException(engine is UnavailableEngine ? ArchiveError.EngineUnavailable : ArchiveError.UnsupportedOperation);
72 }
73
74 Report(JobState.Running);
75 await engine.ExecuteAsync(action, Array.AsReadOnly(inputs), context, linked.Token).ConfigureAwait(false);
76 budget.Check(linked.Token);
77 if (context.Failure != ArchiveError.None)
78 {
79 throw new ArchiveException(context.Failure);
80 }
81 if (context.Results.Any(result => result.Error != ArchiveError.None || result.Verification == VerificationState.Failed))
82 {
83 throw new ArchiveException(ArchiveError.IntegrityFailure);
84 }
85
86 if (context.HasOutput)
87 {
88 await output.CommitAsync(linked.Token).ConfigureAwait(false);
89 committed = true;
90 }
91 // 게시 성공 뒤의 늦은 취소로 실제 출력을 취소 결과로 바꾸지 않음.
92 state = JobState.Completed;
93 }
94 catch (OperationCanceledException) when (linked?.IsCancellationRequested == true || cancellationToken.IsCancellationRequested)
95 {
96 state = JobState.Cancelled;
97 error = ArchiveError.Cancelled;
98 }
99 catch (ArgumentException) when (context is null) { error = ArchiveError.UnsupportedOperation; }
100 catch (ArchiveException failure) { error = failure.Code; }
101 catch { error = ArchiveError.EngineFailure; }
102 finally
103 {
104 try { await output.DisposeAsync().ConfigureAwait(false); }
105 catch
106 {
107 state = JobState.Failed;
108 if (error == ArchiveError.None) { error = ArchiveError.OutputUnavailable; }
109 }
110 finally
111 {
112 // 종료 이벤트 뒤에 취소 이벤트가 나오지 않도록 등록을 먼저 해제함.
113 cancellationRegistration.Dispose();
114 linked?.Dispose();
115 }
116 }
117
118 var results = (context?.Results ?? Array.Empty<EntryResult>()).Select(result => result.Outcome == EntryOutcome.Staged
119 ? result with { Outcome = committed ? EntryOutcome.Extracted : EntryOutcome.Failed,
120 Error = committed ? ArchiveError.None : error }
121 : result).ToArray();
122 Report(state);
123 return new(id, state, Array.AsReadOnly(results), error);
124 }
125}