team-ljyzipelo

공개
163줄6.3 KB
1using System.Security;
2using Zipelo.Core;
3
4namespace Zipelo.Desktop;
5
6// 호스트는 별도 작업 프로세스를 사용하고 입력과 출력 정리를 마친 뒤 반환해야 함.
7public delegate Task<JobResult> CoreJobRunner(
8 WorkspaceRequest request,
9 IProgress<JobEvent> progress,
10 PasswordProvider passwords,
11 CancellationToken cancellationToken);
12
13public sealed class CoreWorkspace : IArchiveWorkspace, IWorkspaceCapabilities
14{
15 private readonly CoreJobRunner run;
16 private readonly string? availabilityMessage;
17 private readonly IReadOnlyList<EngineCapability> capabilities;
18
19 public CoreWorkspace(CoreJobRunner run, IEnumerable<EngineCapability> capabilities, string? availabilityMessage = null)
20 {
21 ArgumentNullException.ThrowIfNull(run);
22 ArgumentNullException.ThrowIfNull(capabilities);
23 this.run = run;
24 this.availabilityMessage = availabilityMessage;
25 this.capabilities = Array.AsReadOnly(capabilities.ToArray());
26 }
27
28 public bool IsAvailable => capabilities.Any(capability =>
29 capability.Action is ArchiveAction.List or ArchiveAction.Create);
30
31 public string AvailabilityMessage => availabilityMessage ?? (IsAvailable
32 ? "연결된 형식과 기능만 사용할 수 있습니다. 압축 풀기는 안전 검증 전까지 준비 중입니다."
33 : "작업 프로세스가 아직 연결되지 않았습니다. 파일을 처리할 수 없습니다.");
34
35 public bool CanExecute(WorkspaceAction action, string format)
36 {
37 // 안전한 출력 계층의 Windows 검증 전까지 해제를 닫아 둠.
38 return action != WorkspaceAction.Extract && capabilities.Any(capability =>
39 capability.Action == MapAction(action) &&
40 string.Equals(capability.Format, format, StringComparison.OrdinalIgnoreCase));
41 }
42
43 public async Task<WorkspaceResult> ExecuteAsync(
44 WorkspaceRequest request,
45 IProgress<WorkspaceProgress> progress,
46 Func<PasswordChallenge, CancellationToken, Task<SecureString?>> requestPassword,
47 CancellationToken cancellationToken)
48 {
49 ArgumentNullException.ThrowIfNull(request);
50 ArgumentNullException.ThrowIfNull(progress);
51 ArgumentNullException.ThrowIfNull(requestPassword);
52 if (request.JobId == Guid.Empty || request.Sources.Count == 0)
53 {
54 throw new ArchiveException(ArchiveError.UnsupportedOperation);
55 }
56 if (!CanExecute(request.Action, request.Format))
57 {
58 return new(WorkspaceOutcome.Failed, Array.Empty<FileRow>())
59 {
60 JobId = request.JobId,
61 Error = IsAvailable ? ArchiveError.UnsupportedOperation : ArchiveError.EngineUnavailable
62 };
63 }
64
65 var gate = new object();
66 long lastSequence = 0;
67 var finished = false;
68 var events = new ForwardProgress<JobEvent>(value =>
69 {
70 lock (gate)
71 {
72 if (finished || value.JobId != request.JobId || value.Sequence <= lastSequence)
73 {
74 return;
75 }
76 lastSequence = value.Sequence;
77 progress.Report(new(value.ProcessedBytes, null)
78 {
79 JobId = value.JobId,
80 Sequence = value.Sequence,
81 State = value.State
82 });
83 }
84 });
85
86 async ValueTask<SecureString?> Passwords(Zipelo.Core.PasswordChallenge challenge, CancellationToken token)
87 {
88 if (challenge.JobId != request.JobId || challenge.RequestId == Guid.Empty)
89 {
90 throw new ArchiveException(ArchiveError.InvalidPasswordResponse);
91 }
92 // 성공한 전달 이후 암호는 Core가 소비와 폐기를 소유함.
93 return await requestPassword(new(challenge.JobId, challenge.RequestId)
94 {
95 Attempt = challenge.Attempt
96 }, token).ConfigureAwait(false);
97 }
98
99 try
100 {
101 var result = await run(request, events, Passwords, cancellationToken).ConfigureAwait(false);
102 if (result.JobId != request.JobId)
103 {
104 throw new ArchiveException(ArchiveError.EngineFailure);
105 }
106 return MapResult(result);
107 }
108 finally
109 {
110 lock (gate) { finished = true; }
111 }
112 }
113
114 private static ArchiveAction MapAction(WorkspaceAction action) => action switch
115 {
116 WorkspaceAction.List => ArchiveAction.List,
117 WorkspaceAction.Create => ArchiveAction.Create,
118 WorkspaceAction.Extract => ArchiveAction.Extract,
119 _ => throw new ArchiveException(ArchiveError.UnsupportedOperation)
120 };
121
122 internal static WorkspaceResult MapResult(JobResult result)
123 {
124 var terminal = result.State is JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed;
125 var outcome = result.State switch
126 {
127 JobState.Completed => WorkspaceOutcome.Completed,
128 JobState.Partial => WorkspaceOutcome.Partial,
129 JobState.Cancelled => WorkspaceOutcome.Cancelled,
130 _ => WorkspaceOutcome.Failed
131 };
132 var rows = result.Entries.Select(value => new FileRow(
133 value.Entry.Name,
134 value.Entry.DeclaredSize is long size ? $"{size:N0}바이트" : "알 수 없음",
135 value.Verification switch
136 {
137 VerificationState.Passed => "검증 통과",
138 VerificationState.Failed => "검증 실패",
139 VerificationState.Unavailable => "검증 불가",
140 _ => "검증 전"
141 })
142 {
143 EntryId = value.Entry.Id,
144 Kind = value.Entry.Kind,
145 Outcome = value.Outcome,
146 Error = value.Error
147 }).ToArray();
148 if (outcome == WorkspaceOutcome.Completed && result.Error != ArchiveError.None)
149 {
150 outcome = WorkspaceOutcome.Failed;
151 }
152 return new(outcome, Array.AsReadOnly(rows))
153 {
154 JobId = result.JobId,
155 Error = terminal ? result.Error : ArchiveError.EngineFailure
156 };
157 }
158
159 private sealed class ForwardProgress<T>(Action<T> report) : IProgress<T>
160 {
161 public void Report(T value) => report(value);
162 }
163}