team-ljyzipelo

공개
1,723줄64 KB
1use std::{collections::BTreeSet, path::PathBuf};
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub enum Format {
5 Zip,
6 Tar,
7 Gzip,
8 TarGzip,
9 SevenZip,
10}
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub enum SourceObject {
13 Unix { device: u64, inode: u64 },
14 Windows { volume: u64, file_id: [u8; 16] },
15 SplitSevenZip { manifest_sha256: [u8; 32] },
16}
17#[derive(Clone, Debug, Eq, PartialEq)]
18pub struct ListId {
19 pub catalog_version: u16,
20 pub format: Format,
21 pub source_object: SourceObject,
22 pub archive_bytes: u64,
23 pub archive_sha256: [u8; 32],
24}
25impl ListId {
26 pub fn valid(&self) -> bool {
27 matches!(
28 (self.catalog_version, self.format, &self.source_object),
29 (
30 1,
31 _,
32 SourceObject::Unix { .. } | SourceObject::Windows { .. }
33 ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. })
34 )
35 }
36 pub fn is_split(&self) -> bool {
37 matches!(self.source_object, SourceObject::SplitSevenZip { .. })
38 }
39}
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct VolumeProblem {
42 pub reason: VolumeProblemReason,
43 pub volume: NativePath,
44}
45#[derive(Clone, Debug, Eq, PartialEq)]
46pub enum Selection {
47 All,
48 EntryIds(Vec<u32>),
49}
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum Method {
52 Store,
53 Deflate,
54}
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub enum Start {
57 List {
58 archive: PathBuf,
59 },
60 Extract {
61 archive: PathBuf,
62 destination: PathBuf,
63 selection: Selection,
64 list_id: ListId,
65 gzip_output_name: Option<String>,
66 },
67 Preview {
68 archive: PathBuf,
69 entry_id: u32,
70 list_id: ListId,
71 },
72 RecoverZip {
73 archive: PathBuf,
74 output_file: PathBuf,
75 },
76 CreateSevenZip {
77 sources: Vec<(PathBuf, String)>,
78 output_file: PathBuf,
79 /// 있으면 `output_file`(이름.7z) 대신 이 크기의 `이름.7z.001`, `이름.7z.002`, …로 나눔.
80 volume_size: Option<u64>,
81 },
82 CreateZip {
83 sources: Vec<(PathBuf, String)>,
84 output_file: PathBuf,
85 method: Method,
86 aes256: bool,
87 },
88}
89// 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
90pub struct Secret(Vec<u8>);
91impl Secret {
92 pub fn new(text: String) -> Result<Self, &'static str> {
93 let mut bytes = text.into_bytes();
94 if bytes.is_empty() || bytes.len() > 1024 {
95 bytes.fill(0);
96 return Err("암호는 UTF-8 1~1024바이트로 입력하세요");
97 }
98 Ok(Self(bytes))
99 }
100 pub fn as_bytes(&self) -> &[u8] {
101 &self.0
102 }
103}
104impl Drop for Secret {
105 fn drop(&mut self) {
106 self.0.fill(0);
107 }
108}
109#[derive(Clone, Copy, Debug, Eq, PartialEq)]
110pub enum ConflictChoice {
111 Overwrite,
112 Skip,
113 Rename,
114}
115#[derive(Clone, Debug, Eq, PartialEq)]
116pub struct Conflict {
117 pub challenge_id: u64,
118 pub entry_id: u32,
119 pub relative_name: String,
120 pub incoming_size: u64,
121 pub existing_size: u64,
122}
123#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct Resolution {
125 pub entry_id: u32,
126 pub relative_name: String,
127 pub choice: ConflictChoice,
128}
129pub enum Command {
130 Start(Start),
131 StartExpanded(Start),
132 ResourceReply {
133 challenge_id: u64,
134 scope: ResourceScope,
135 allow: bool,
136 },
137 Password {
138 challenge_id: u64,
139 secret: Secret,
140 },
141 ConflictReply {
142 challenge_id: u64,
143 choice: ConflictChoice,
144 apply_to_remaining: bool,
145 },
146 Cancel,
147}
148pub struct Request {
149 pub job_id: u64,
150 pub sequence: u64,
151 pub command: Command,
152}
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub enum Kind {
155 File,
156 Directory,
157 Link,
158 Other,
159}
160#[derive(Clone, Debug, Eq, PartialEq)]
161pub struct Entry {
162 pub id: u32,
163 pub name: String,
164 pub kind: Kind,
165 pub bytes: Option<u64>,
166 pub packed: Option<u64>,
167 pub encrypted: bool,
168}
169#[derive(Clone, Copy, Debug, Eq, PartialEq)]
170pub enum CancelStatus {
171 Requested,
172 AlreadyRequested,
173 TooLate,
174 Finished,
175}
176#[derive(Clone, Copy, Debug, Eq, PartialEq)]
177pub enum Stage {
178 Scan,
179 Read,
180 Decode,
181 Write,
182 Verify,
183 Commit,
184}
185#[derive(Clone, Copy, Debug, Eq, PartialEq)]
186pub enum Outcome {
187 Completed,
188 Failed,
189 Cancelled,
190}
191#[derive(Clone, Copy, Debug, Eq, PartialEq)]
192pub enum ErrorCode {
193 RecoveryIncomplete,
194 RecoveryImpossible,
195 MissingVolume,
196 Integrity,
197 UnsupportedFormat,
198 UnsupportedFeature,
199 WrongPassword,
200 UnsafePath,
201 Conflict,
202 Limit,
203 Io,
204 DiskFull,
205 Protocol,
206 Internal,
207 SourceChanged,
208 InvalidRequest,
209}
210#[derive(Clone, Copy, Debug, Eq, PartialEq)]
211pub enum Publication {
212 None,
213 Partial,
214 Complete,
215 Uncertain,
216}
217#[derive(Clone, Copy, Debug, Eq, PartialEq)]
218pub enum Durability {
219 NotApplicable,
220 Synced,
221 Unconfirmed,
222 Failed,
223}
224#[derive(Clone, Copy, Debug, Eq, PartialEq)]
225pub enum Cleanup {
226 Complete,
227 Failed,
228 Unconfirmed,
229}
230#[derive(Clone, Copy, Debug, Eq, PartialEq)]
231pub enum Disposition {
232 Created,
233 PartialRetained,
234 Removed,
235 CommitUncertain,
236}
237#[derive(Clone, Debug)]
238pub struct Terminal {
239 pub outcome: Outcome,
240 pub error: Option<ErrorCode>,
241 pub publication: Publication,
242 pub created_count: u64,
243 pub retained_partial_count: u64,
244 pub durability: Durability,
245 pub cleanup: Cleanup,
246}
247pub use worker_protocol::protocol::{
248 ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, RecoveryEnd, RecoveryEntry,
249 RecoveryMode, RecoveryReason, RecoveryStatus, ResourceScope, ResourceUsage,
250 VolumeProblemReason,
251};
252
253pub struct Preview {
254 pub info: PreviewInfo,
255 pub data: Vec<u8>,
256}
257
258struct PreviewBuffer {
259 info: PreviewInfo,
260 data: Vec<u8>,
261 ended: bool,
262}
263
264impl PreviewBuffer {
265 fn chunk(&mut self, entry_id: u32, offset: u64, data: Vec<u8>) -> bool {
266 if self.ended
267 || entry_id != self.info.entry_id
268 || offset != self.data.len() as u64
269 || data.is_empty()
270 || data.len() > 32 * 1024
271 || (data.len() as u64) > self.info.total_bytes.saturating_sub(offset)
272 {
273 return false;
274 }
275 self.data.extend_from_slice(&data);
276 true
277 }
278 fn end(&mut self, entry_id: u32, total_bytes: u64, sha256: [u8; 32]) -> bool {
279 use sha2::{Digest, Sha256};
280 if self.ended
281 || entry_id != self.info.entry_id
282 || total_bytes != self.info.total_bytes
283 || total_bytes != self.data.len() as u64
284 || Sha256::digest(&self.data)[..] != sha256
285 || (self.info.format == PreviewFormat::Utf8Text
286 && std::str::from_utf8(&self.data).is_err())
287 {
288 return false;
289 }
290 self.ended = true;
291 true
292 }
293}
294
295#[derive(Clone, Debug)]
296pub struct ResourceChallenge {
297 pub id: u64,
298 pub action: ActionKind,
299 pub scope: ResourceScope,
300 pub usage: ResourceUsage,
301 pub soft_limits: Limits,
302 pub ceiling: Limits,
303}
304
305#[derive(Clone, Debug)]
306pub enum Event {
307 RecoveryEntry(RecoveryEntry),
308 RecoveryEnd(RecoveryEnd),
309 VolumeProblem(VolumeProblem),
310 PreviewBegin(PreviewInfo),
311 PreviewChunk {
312 entry_id: u32,
313 offset: u64,
314 data: Vec<u8>,
315 },
316 PreviewEnd {
317 entry_id: u32,
318 total_bytes: u64,
319 sha256: [u8; 32],
320 },
321 ResourceRequired(ResourceChallenge),
322 Accepted {
323 encryption: bool,
324 },
325 Entry(Entry),
326 ListEnd {
327 entry_count: u32,
328 list_id: ListId,
329 },
330 PasswordRequired {
331 challenge_id: u64,
332 attempt: u32,
333 encrypt: bool,
334 },
335 ConflictRequired(Conflict),
336 ConflictResolved(Resolution),
337 Progress {
338 stage: Stage,
339 processed: u64,
340 total: Option<u64>,
341 completed_entries: u64,
342 },
343 Output {
344 entry_id: Option<u32>,
345 relative_name: String,
346 disposition: Disposition,
347 },
348 CancelAck {
349 request_sequence: u64,
350 status: CancelStatus,
351 },
352 Terminal(Terminal),
353}
354pub enum HostEvent {
355 Fault(String),
356 CleanupComplete,
357 Frame {
358 job_id: u64,
359 sequence: u64,
360 event: Event,
361 },
362 StdoutEof,
363 StderrEof,
364 Exited {
365 success: bool,
366 },
367}
368// 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함.
369// 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함.
370pub trait Connection {
371 fn send(&mut self, request: Request) -> Result<(), String>;
372 fn poll(&mut self) -> Option<HostEvent>;
373}
374pub trait Factory {
375 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
376}
377pub struct Unavailable;
378impl Factory for Unavailable {
379 fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
380 Err("작업자 연결이 아직 준비되지 않았습니다".into())
381 }
382}
383struct Running {
384 recovery_metadata: usize,
385 volume_problem: Option<VolumeProblem>,
386 preview: Option<PreviewBuffer>,
387 preview_discarded: bool,
388 id: u64,
389 outgoing: u64,
390 incoming: u64,
391 accepted: bool,
392 start_failed: bool,
393 start: Start,
394 connection: Box<dyn Connection>,
395 entries: Vec<Entry>,
396 list_end: Option<(u32, ListId)>,
397 stdout_eof: bool,
398 transport_closed: bool,
399 stderr_eof: bool,
400 exit: Option<bool>,
401 cancel_sequence: Option<u64>,
402 expanded: bool,
403 granted: ResourceScope,
404 last_challenge: u64,
405 estimated: ResourceUsage,
406 conflict_ids: BTreeSet<u64>,
407 resolved_ids: BTreeSet<u32>,
408 file_ids: BTreeSet<u32>,
409}
410#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
411pub enum Close {
412 #[default]
413 Open,
414 Confirm,
415 Waiting,
416 Review,
417 Allowed,
418}
419#[derive(Default)]
420pub struct Model {
421 pub recovery_entries: Vec<RecoveryEntry>,
422 pub recovery_end: Option<RecoveryEnd>,
423 pub volume_problem: Option<VolumeProblem>,
424 running: Option<Running>,
425 pub preview: Option<Preview>,
426 next_id: u64,
427 pub archive: Option<PathBuf>,
428 pub entries: Vec<Entry>,
429 pub list_id: Option<ListId>,
430 pub selected: BTreeSet<u32>,
431 pub terminal: Option<Terminal>,
432 pub challenge: Option<(u64, u32, bool)>,
433 pub resource: Option<ResourceChallenge>,
434 retry_start: Option<Start>,
435 pub conflict: Option<Conflict>,
436 pub resolutions: Vec<Resolution>,
437 pub progress: Option<(Stage, u64, Option<u64>, u64)>,
438 pub outputs: Vec<(String, Disposition)>,
439 pub cancel: Option<CancelStatus>,
440 pub error: Option<String>,
441 pub input_error: Option<String>,
442 pub encryption: bool,
443 pub close: Close,
444 pub confirmed: bool,
445}
446impl Model {
447 pub fn busy(&self) -> bool {
448 self.running.is_some()
449 }
450 pub fn cancellation_requested(&self) -> bool {
451 self.running
452 .as_ref()
453 .is_some_and(|run| run.cancel_sequence.is_some())
454 }
455 pub fn job_id(&self) -> Option<u64> {
456 self.running.as_ref().map(|r| r.id)
457 }
458 pub fn can_extract(&self) -> bool {
459 !self.busy()
460 && self.list_id.is_some()
461 && self.archive.is_some()
462 && self.close == Close::Open
463 }
464 pub fn can_preview(&self) -> bool {
465 self.can_extract()
466 && self.list_id.as_ref().is_some_and(|id| !id.is_split())
467 && self.selected.len() == 1
468 && self
469 .entries
470 .iter()
471 .any(|e| self.selected.contains(&e.id) && e.kind == Kind::File)
472 }
473 pub fn begin_preview(&mut self, factory: &mut dyn Factory) -> bool {
474 if !self.can_preview() {
475 return false;
476 }
477 self.begin(
478 Start::Preview {
479 archive: self.archive.clone().unwrap(),
480 entry_id: *self.selected.first().unwrap(),
481 list_id: self.list_id.clone().unwrap(),
482 },
483 factory,
484 )
485 }
486 pub fn dismiss_preview(&mut self) {
487 self.preview = None;
488 if let Some(run) = self.running.as_mut()
489 && matches!(run.start, Start::Preview { .. })
490 {
491 run.preview = None;
492 run.preview_discarded = true;
493 self.cancel();
494 }
495 }
496 pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
497 let expanded =
498 matches!(start, Start::CreateSevenZip { .. }) || self.needs_expansion(&start);
499 self.begin_with_limits(start, factory, expanded)
500 }
501 pub fn estimated_usage(&self) -> ResourceUsage {
502 self.running
503 .as_ref()
504 .map(|run| run.estimated)
505 .unwrap_or_default()
506 }
507 fn estimate(&self, start: &Start) -> ResourceUsage {
508 let mut usage = ResourceUsage::default();
509 match start {
510 Start::Extract { selection, .. } => {
511 let selected_ids: BTreeSet<_> = match selection {
512 Selection::All => BTreeSet::new(),
513 Selection::EntryIds(ids) => ids.iter().copied().collect(),
514 };
515 let directories: BTreeSet<_> = self
516 .entries
517 .iter()
518 .filter(|e| selected_ids.contains(&e.id) && e.kind == Kind::Directory)
519 .map(|e| e.name.trim_end_matches('/'))
520 .collect();
521 let selected = |entry: &&Entry| {
522 matches!(selection, Selection::All)
523 || selected_ids.contains(&entry.id)
524 || entry
525 .name
526 .match_indices('/')
527 .any(|(n, _)| directories.contains(&entry.name[..n]))
528 };
529 let entries: Vec<_> = self.entries.iter().filter(selected).collect();
530 usage.estimated_entries = u32::try_from(entries.len()).ok();
531 usage.estimated_bytes = entries
532 .iter()
533 .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?));
534 }
535 Start::CreateZip { sources, .. } | Start::CreateSevenZip { sources, .. } => {
536 usage.estimated_bytes = sources.iter().try_fold(0u64, |sum, (path, _)| {
537 let m = std::fs::symlink_metadata(path).ok()?;
538 if !m.is_file() {
539 return None;
540 }
541 sum.checked_add(m.len())
542 });
543 usage.estimated_entries = sources
544 .iter()
545 .all(|(path, _)| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()))
546 .then(|| u32::try_from(sources.len()).ok())
547 .flatten();
548 }
549 Start::Preview { .. } => {
550 usage.estimated_entries = u32::try_from(self.entries.len()).ok();
551 usage.estimated_bytes = self
552 .entries
553 .iter()
554 .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?));
555 }
556 Start::List { .. } | Start::RecoverZip { .. } => {}
557 }
558 usage
559 }
560 fn needs_expansion(&self, start: &Start) -> bool {
561 let usage = self.estimate(start);
562 usage
563 .estimated_bytes
564 .is_some_and(|n| n > Limits::default().output)
565 || usage
566 .estimated_entries
567 .is_some_and(|n| n > Limits::default().entries)
568 }
569 pub fn can_retry_expanded(&self) -> bool {
570 !self.busy() && self.retry_start.is_some() && self.close == Close::Open
571 }
572 pub fn retry_expanded(&mut self, factory: &mut dyn Factory) -> bool {
573 if !self.can_retry_expanded() {
574 return false;
575 }
576 let start = self.retry_start.clone().unwrap();
577 self.begin_with_limits(start, factory, true)
578 }
579 pub fn resource_reply(&mut self, job_id: u64, challenge_id: u64, allow: bool) -> bool {
580 if self.job_id() != Some(job_id) || self.cancellation_requested() {
581 return false;
582 }
583 let Some(question) = self.resource.clone().filter(|q| q.id == challenge_id) else {
584 return false;
585 };
586 if self
587 .send(Command::ResourceReply {
588 challenge_id,
589 scope: question.scope,
590 allow,
591 })
592 .is_none()
593 {
594 return false;
595 }
596 if allow {
597 let granted = &mut self.running.as_mut().unwrap().granted;
598 granted.output |= question.scope.output;
599 granted.entries |= question.scope.entries;
600 granted.ratio |= question.scope.ratio;
601 }
602 self.resource = None;
603 true
604 }
605 fn begin_with_limits(
606 &mut self,
607 start: Start,
608 factory: &mut dyn Factory,
609 expanded: bool,
610 ) -> bool {
611 if self.busy() || self.close != Close::Open {
612 crate::log_debug!("작업을 시작하지 않음: 다른 작업 중이거나 닫는 중");
613 return false;
614 }
615 crate::log_debug!(
616 "작업 시작 요청 (확대 한도: {expanded}): {}",
617 crate::applog::brief(&start, 600)
618 );
619 let selectable: BTreeSet<_> = self
620 .entries
621 .iter()
622 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
623 .map(|e| e.id)
624 .collect();
625 let validation = match &start {
626 Start::RecoverZip {
627 archive,
628 output_file,
629 } => archive.is_absolute() && output_file.is_absolute() && archive != output_file,
630 Start::List { archive } => archive.is_absolute(),
631 Start::Preview {
632 archive,
633 entry_id,
634 list_id,
635 } => {
636 archive.is_absolute()
637 && list_id.valid()
638 && !list_id.is_split()
639 && self.archive.as_ref() == Some(archive)
640 && self.list_id.as_ref() == Some(list_id)
641 && self
642 .entries
643 .iter()
644 .any(|e| e.id == *entry_id && e.kind == Kind::File)
645 }
646 Start::Extract {
647 archive,
648 destination,
649 selection,
650 gzip_output_name,
651 list_id,
652 } => {
653 archive.is_absolute()
654 && destination.is_absolute()
655 && self.archive.as_ref() == Some(archive)
656 && self.list_id.as_ref() == Some(list_id)
657 && match list_id.format {
658 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
659 _ => gzip_output_name.is_none(),
660 }
661 && match selection {
662 Selection::All => true,
663 Selection::EntryIds(ids) => {
664 !ids.is_empty()
665 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
666 && ids.iter().all(|id| selectable.contains(id))
667 }
668 }
669 }
670 Start::CreateZip {
671 sources,
672 output_file,
673 ..
674 }
675 | Start::CreateSevenZip {
676 sources,
677 output_file,
678 ..
679 } => {
680 !sources.is_empty()
681 && output_file.is_absolute()
682 && sources
683 .iter()
684 .all(|(p, n)| p.is_absolute() && valid_relative(n))
685 }
686 } && match &start {
687 // 분할은 `이름.7z`에 볼륨 번호를 붙이므로 .7z 이름과 최소 볼륨 크기를 요구함.
688 Start::CreateSevenZip {
689 output_file,
690 volume_size: Some(size),
691 ..
692 } => {
693 *size >= worker_protocol::protocol::MIN_SEVEN_ZIP_VOLUME_BYTES
694 && output_file
695 .extension()
696 .is_some_and(|ext| ext.eq_ignore_ascii_case("7z"))
697 }
698 _ => true,
699 };
700 if !validation {
701 self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
702 return false;
703 }
704 let Some(id) = self.next_id.checked_add(1) else {
705 self.error = Some("작업 ID 한도에 도달했습니다".into());
706 return false;
707 };
708 self.preview = None;
709 let estimated = self.estimate(&start);
710 self.volume_problem = None;
711 let mut connection = match factory.connect(id) {
712 Ok(c) => c,
713 Err(e) => {
714 self.error = Some(e);
715 return false;
716 }
717 };
718 let send_error = connection
719 .send(Request {
720 job_id: id,
721 sequence: 0,
722 command: if expanded {
723 Command::StartExpanded(start.clone())
724 } else {
725 Command::Start(start.clone())
726 },
727 })
728 .err();
729 let started = send_error.is_none();
730 if let Start::List { archive } = &start
731 && started
732 {
733 self.archive = Some(archive.clone());
734 self.list_id = None;
735 self.entries.clear();
736 self.selected.clear();
737 }
738 self.next_id = id;
739 self.recovery_entries.clear();
740 self.recovery_end = None;
741 self.terminal = None;
742 self.volume_problem = None;
743 self.retry_start = None;
744 self.resource = None;
745 self.challenge = None;
746 self.conflict = None;
747 self.resolutions.clear();
748 self.progress = None;
749 self.outputs.clear();
750 self.cancel = None;
751 self.input_error = None;
752 self.error = send_error;
753 self.confirmed = false;
754 self.running = Some(Running {
755 recovery_metadata: 0,
756 volume_problem: None,
757 preview: None,
758 preview_discarded: false,
759 id,
760 outgoing: 1,
761 incoming: 0,
762 accepted: false,
763 start_failed: !started,
764 start,
765 connection,
766 entries: Vec::new(),
767 list_end: None,
768 stdout_eof: false,
769 transport_closed: false,
770 stderr_eof: false,
771 exit: None,
772 cancel_sequence: None,
773 expanded,
774 granted: ResourceScope::default(),
775 last_challenge: 0,
776 estimated,
777 conflict_ids: BTreeSet::new(),
778 resolved_ids: BTreeSet::new(),
779 file_ids: self
780 .entries
781 .iter()
782 .filter(|e| e.kind == Kind::File)
783 .map(|e| e.id)
784 .collect(),
785 });
786 started
787 }
788 pub fn extract(
789 &mut self,
790 destination: PathBuf,
791 selected_only: bool,
792 gzip_output_name: Option<String>,
793 factory: &mut dyn Factory,
794 ) -> bool {
795 if !self.can_extract() {
796 return false;
797 }
798 self.begin(
799 Start::Extract {
800 archive: self.archive.clone().unwrap(),
801 destination,
802 selection: if selected_only {
803 Selection::EntryIds(self.selected.iter().copied().collect())
804 } else {
805 Selection::All
806 },
807 list_id: self.list_id.clone().unwrap(),
808 gzip_output_name,
809 },
810 factory,
811 )
812 }
813 pub fn password(&mut self, text: String) -> bool {
814 let Some((challenge_id, _, _)) = self.challenge else {
815 return false;
816 };
817 let secret = match Secret::new(text) {
818 Ok(s) => s,
819 Err(e) => {
820 self.input_error = Some(e.into());
821 return false;
822 }
823 };
824 crate::log_debug!("암호 전달 (요청 {challenge_id}, 내용은 기록하지 않음)");
825 if self
826 .send(Command::Password {
827 challenge_id,
828 secret,
829 })
830 .is_some()
831 {
832 self.challenge = None;
833 self.resource = None;
834 self.conflict = None;
835 self.input_error = None;
836 true
837 } else {
838 false
839 }
840 }
841 pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool {
842 let Some(conflict) = &self.conflict else {
843 return false;
844 };
845 if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open {
846 return false;
847 }
848 if self
849 .send(Command::ConflictReply {
850 challenge_id: conflict.challenge_id,
851 choice,
852 apply_to_remaining,
853 })
854 .is_some()
855 {
856 self.conflict = None;
857 self.input_error = None;
858 true
859 } else {
860 false
861 }
862 }
863 fn send(&mut self, command: Command) -> Option<u64> {
864 let run = self.running.as_mut()?;
865 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
866 return None;
867 }
868 let seq = run.outgoing;
869 if crate::applog::enabled(crate::applog::Level::Trace) {
870 // 암호는 내용 없이 요청 번호만 남김.
871 let text = match &command {
872 Command::Start(start) => format!("Start {}", crate::applog::brief(start, 400)),
873 Command::StartExpanded(start) => {
874 format!("StartExpanded {}", crate::applog::brief(start, 400))
875 }
876 Command::ResourceReply {
877 challenge_id,
878 allow,
879 ..
880 } => format!("ResourceReply challenge={challenge_id} allow={allow}"),
881 Command::Password { challenge_id, .. } => {
882 format!("Password challenge={challenge_id}")
883 }
884 Command::ConflictReply {
885 challenge_id,
886 choice,
887 apply_to_remaining,
888 } => format!(
889 "ConflictReply challenge={challenge_id} choice={choice:?} apply={apply_to_remaining}"
890 ),
891 Command::Cancel => "Cancel".into(),
892 };
893 crate::log_trace!("작업 {} #{seq} 송신: {text}", run.id);
894 }
895 let Some(next) = seq.checked_add(1) else {
896 self.error = Some("요청 순서 한도 초과".into());
897 return None;
898 };
899 match run.connection.send(Request {
900 job_id: run.id,
901 sequence: seq,
902 command,
903 }) {
904 Ok(()) => {
905 run.outgoing = next;
906 Some(seq)
907 }
908 Err(e) => {
909 self.error = Some(e);
910 None
911 }
912 }
913 }
914 pub fn cancel(&mut self) {
915 crate::log_debug!("작업 취소 요청");
916 self.preview = None;
917 if let Some(run) = self.running.as_mut()
918 && matches!(run.start, Start::Preview { .. })
919 {
920 run.preview = None;
921 run.preview_discarded = true;
922 }
923 if self
924 .running
925 .as_ref()
926 .is_some_and(|r| r.cancel_sequence.is_none())
927 {
928 if let Some(seq) = self.send(Command::Cancel) {
929 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
930 self.challenge = None;
931 self.resource = None;
932 self.conflict = None;
933 self.input_error = None;
934 }
935 }
936 }
937 pub fn request_close(&mut self) {
938 if self.close == Close::Open {
939 self.close = if self.busy() {
940 Close::Confirm
941 } else {
942 Close::Review
943 };
944 }
945 }
946 pub fn confirm_close(&mut self) {
947 if self.close == Close::Confirm {
948 self.cancel();
949 self.close = if self.busy() {
950 Close::Waiting
951 } else {
952 Close::Review
953 };
954 }
955 }
956 pub fn keep_open(&mut self) {
957 if self.close != Close::Allowed {
958 self.close = Close::Open;
959 }
960 }
961 pub fn acknowledge_close(&mut self) {
962 if !self.busy() && self.close == Close::Review {
963 self.close = Close::Allowed;
964 }
965 }
966 pub fn poll(&mut self) {
967 let changed = self.running.as_ref().is_some_and(|run| {
968 matches!(&run.start, Start::Preview { entry_id, .. }
969 if self.selected.len() != 1 || !self.selected.contains(entry_id))
970 });
971 if changed {
972 self.dismiss_preview();
973 }
974 for _ in 0..128 {
975 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
976 break;
977 };
978 self.receive(event);
979 if self.error.is_some()
980 && self
981 .running
982 .as_ref()
983 .is_some_and(|run| matches!(run.start, Start::Preview { .. }))
984 {
985 self.cancel();
986 }
987 }
988 let complete = self.running.as_ref().is_some_and(|r| {
989 r.exit.is_some()
990 && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
991 });
992 if complete {
993 let mut run = self.running.take().unwrap();
994 self.confirmed =
995 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
996 match (&self.terminal, &self.error) {
997 (_, Some(error)) => crate::log_error!("작업 {} 실패: {error}", run.id),
998 (Some(terminal), None) if terminal.error.is_some() => crate::log_warn!(
999 "작업 {} 끝남: {}",
1000 run.id,
1001 crate::applog::brief(terminal, 400)
1002 ),
1003 (Some(terminal), None) => crate::log_info!(
1004 "작업 {} 끝남: {}",
1005 run.id,
1006 crate::applog::brief(terminal, 400)
1007 ),
1008 (None, None) => crate::log_warn!("작업 {} 종료 결과 없음", run.id),
1009 }
1010 if !self.confirmed {
1011 self.error.get_or_insert(
1012 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
1013 );
1014 }
1015 if self.confirmed
1016 && self
1017 .terminal
1018 .as_ref()
1019 .is_some_and(|t| t.outcome == Outcome::Completed)
1020 {
1021 if matches!(run.start, Start::List { .. }) {
1022 if let Some((count, id)) = run
1023 .list_end
1024 .filter(|(n, _)| *n as usize == run.entries.len())
1025 {
1026 let _ = count;
1027 self.entries = run.entries;
1028 self.list_id = Some(id);
1029 } else {
1030 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
1031 self.confirmed = false;
1032 }
1033 }
1034 }
1035 if matches!(run.start, Start::Preview { .. }) {
1036 if self.confirmed
1037 && self
1038 .terminal
1039 .as_ref()
1040 .is_some_and(|t| t.outcome == Outcome::Completed)
1041 && !run.preview_discarded
1042 {
1043 if let Some(buffer) = run.preview.take().filter(|b| b.ended) {
1044 self.preview = Some(Preview {
1045 info: buffer.info,
1046 data: buffer.data,
1047 });
1048 } else {
1049 self.error = Some("미리보기 완료 정보가 일치하지 않습니다".into());
1050 self.confirmed = false;
1051 }
1052 }
1053 }
1054 if self.terminal.as_ref().is_some_and(|t| {
1055 matches!(
1056 t.error,
1057 Some(ErrorCode::SourceChanged | ErrorCode::MissingVolume)
1058 )
1059 }) {
1060 self.list_id = None;
1061 self.selected.clear();
1062 }
1063 if self.confirmed && run.cancel_sequence.is_none() {
1064 self.volume_problem = run.volume_problem.take();
1065 }
1066 self.retry_start = if !matches!(run.start, Start::Preview { .. })
1067 && !run.expanded
1068 && run.cancel_sequence.is_none()
1069 && self.confirmed
1070 && self.terminal.as_ref().is_some_and(|t| {
1071 t.outcome == Outcome::Failed
1072 && t.error == Some(ErrorCode::Limit)
1073 && t.publication == Publication::None
1074 && t.created_count == 0
1075 && t.retained_partial_count == 0
1076 && t.cleanup == Cleanup::Complete
1077 })
1078 && self.outputs.iter().all(|(_, d)| *d == Disposition::Removed)
1079 {
1080 Some(run.start.clone())
1081 } else {
1082 None
1083 };
1084 self.challenge = None;
1085 self.resource = None;
1086 self.conflict = None;
1087 self.input_error = None;
1088 if matches!(self.close, Close::Waiting | Close::Confirm) {
1089 self.close = Close::Review;
1090 }
1091 }
1092 }
1093 fn receive(&mut self, host: HostEvent) {
1094 let run = self.running.as_mut().unwrap();
1095 match host {
1096 HostEvent::Fault(message) => {
1097 crate::log_error!("작업자 통신 오류: {message}");
1098 self.error = Some(message)
1099 }
1100 HostEvent::CleanupComplete => {
1101 crate::log_trace!("작업 {} 통신 정리 완료", run.id);
1102 run.transport_closed = true
1103 }
1104 HostEvent::StdoutEof => {
1105 crate::log_trace!("작업 {} 표준 출력 끝", run.id);
1106 run.stdout_eof = true
1107 }
1108 HostEvent::StderrEof => {
1109 crate::log_trace!("작업 {} 표준 오류 끝", run.id);
1110 run.stderr_eof = true
1111 }
1112 HostEvent::Exited { success } => {
1113 if success {
1114 crate::log_debug!("작업 {} 작업자 종료 (성공)", run.id);
1115 } else {
1116 crate::log_warn!("작업 {} 작업자 종료 (실패)", run.id);
1117 }
1118 run.exit = Some(success)
1119 }
1120 HostEvent::Frame {
1121 job_id,
1122 sequence,
1123 event,
1124 } => {
1125 if crate::applog::enabled(crate::applog::Level::Trace) {
1126 match &event {
1127 Event::PreviewChunk { offset, data, .. } => crate::log_trace!(
1128 "작업 {job_id} #{sequence} 미리보기 조각 offset={offset} len={}",
1129 data.len()
1130 ),
1131 event => crate::log_trace!(
1132 "작업 {job_id} #{sequence} 수신: {}",
1133 crate::applog::brief(event, 400)
1134 ),
1135 }
1136 }
1137 if job_id != run.id
1138 || sequence != run.incoming
1139 || self.terminal.is_some()
1140 || run.stdout_eof
1141 || sequence >= 1_000_000
1142 {
1143 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
1144 return;
1145 }
1146 run.incoming += 1;
1147 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
1148 self.error = Some("작업 승인 응답이 없습니다".into());
1149 return;
1150 }
1151 match event {
1152 Event::RecoveryEntry(entry) => {
1153 let budget = if run.granted.any() {
1154 64 * 1024 * 1024
1155 } else {
1156 8 * 1024 * 1024
1157 };
1158 let used = run.recovery_metadata;
1159 if !matches!(run.start, Start::RecoverZip { .. })
1160 || self.recovery_end.is_some()
1161 || !entry.valid()
1162 || entry.candidate_id as usize != self.recovery_entries.len()
1163 || entry.name.as_ref().is_some_and(|n| {
1164 n.len() > 4096 || !valid_relative(n.trim_end_matches('/'))
1165 })
1166 || self
1167 .recovery_entries
1168 .last()
1169 .is_some_and(|e| e.source_offset >= entry.source_offset)
1170 || self.recovery_entries.len()
1171 >= if run.granted.entries { 200_000 } else { 10_000 }
1172 || used + 128 + entry.name.as_ref().map_or(0, String::len) > budget
1173 {
1174 self.error = Some("복구 항목 응답이 유효하지 않습니다".into());
1175 } else {
1176 run.recovery_metadata +=
1177 128 + entry.name.as_ref().map_or(0, String::len);
1178 self.recovery_entries.push(entry);
1179 }
1180 }
1181 Event::RecoveryEnd(summary) => {
1182 let count = |status| {
1183 self.recovery_entries
1184 .iter()
1185 .filter(|e| e.status == status)
1186 .count() as u32
1187 };
1188 if !matches!(run.start, Start::RecoverZip { .. })
1189 || self.recovery_end.is_some()
1190 || !summary.valid()
1191 || summary.source_bytes > 4 * 1024 * 1024 * 1024
1192 || self
1193 .recovery_entries
1194 .iter()
1195 .any(|e| e.source_offset >= summary.source_bytes)
1196 || summary.verified_entries != count(RecoveryStatus::Verified)
1197 || summary.lost_entries != count(RecoveryStatus::Lost)
1198 || summary.unverified_entries != count(RecoveryStatus::Unverified)
1199 {
1200 self.error = Some("복구 요약이 항목과 일치하지 않습니다".into());
1201 } else {
1202 self.recovery_end = Some(summary);
1203 }
1204 }
1205 Event::VolumeProblem(problem) => {
1206 if run.cancel_sequence.is_some() {
1207 return;
1208 }
1209 if run.volume_problem.is_some()
1210 || !matches!(run.start, Start::List { .. } | Start::Extract { .. })
1211 || !problem.volume.is_basename()
1212 {
1213 self.error = Some("분할 조각 오류 응답이 유효하지 않습니다".into());
1214 } else {
1215 run.volume_problem = Some(problem);
1216 }
1217 }
1218 Event::PreviewBegin(info) => {
1219 if run.preview_discarded {
1220 return;
1221 }
1222 if !matches!(run.start, Start::Preview { entry_id, .. } if entry_id == info.entry_id)
1223 || run.preview.is_some()
1224 || !info.valid()
1225 || self.error.is_some()
1226 {
1227 self.error = Some("미리보기 메타정보가 유효하지 않습니다".into());
1228 } else {
1229 let mut data = Vec::new();
1230 if data.try_reserve_exact(info.total_bytes as usize).is_err() {
1231 self.error = Some("미리보기 메모리를 확보하지 못했습니다".into());
1232 } else {
1233 run.preview = Some(PreviewBuffer {
1234 info,
1235 data,
1236 ended: false,
1237 });
1238 }
1239 }
1240 }
1241 Event::PreviewChunk {
1242 entry_id,
1243 offset,
1244 data,
1245 } => {
1246 if run.preview_discarded {
1247 return;
1248 }
1249 if self.error.is_some()
1250 || !run
1251 .preview
1252 .as_mut()
1253 .is_some_and(|b| b.chunk(entry_id, offset, data))
1254 {
1255 run.preview = None;
1256 self.error =
1257 Some("미리보기 데이터 순서나 크기가 일치하지 않습니다".into());
1258 }
1259 }
1260 Event::PreviewEnd {
1261 entry_id,
1262 total_bytes,
1263 sha256,
1264 } => {
1265 if run.preview_discarded {
1266 return;
1267 }
1268 if !run
1269 .preview
1270 .as_mut()
1271 .is_some_and(|b| b.end(entry_id, total_bytes, sha256))
1272 {
1273 run.preview = None;
1274 self.error = Some("미리보기 내용 검증에 실패했습니다".into());
1275 }
1276 }
1277 Event::Accepted { encryption } => {
1278 if matches!(
1279 run.start,
1280 Start::CreateSevenZip { .. } | Start::RecoverZip { .. }
1281 ) && encryption
1282 {
1283 self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into());
1284 }
1285 if run.accepted {
1286 self.error = Some("작업 승인 중복".into());
1287 }
1288 run.accepted = true;
1289 self.encryption = encryption;
1290 }
1291 Event::Entry(entry) => {
1292 if !matches!(run.start, Start::List { .. })
1293 || run.list_end.is_some()
1294 || entry.id as usize != run.entries.len()
1295 || entry.name.len() > 4096
1296 || run.entries.len()
1297 >= if run.granted.entries {
1298 200_000
1299 } else {
1300 100_000
1301 }
1302 {
1303 self.error = Some("목록 응답이 유효하지 않습니다".into());
1304 } else {
1305 run.entries.push(entry);
1306 }
1307 }
1308 Event::ListEnd {
1309 entry_count,
1310 list_id,
1311 } => {
1312 if !matches!(run.start, Start::List { .. })
1313 || run.list_end.is_some()
1314 || !list_id.valid()
1315 {
1316 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
1317 } else {
1318 run.list_end = Some((entry_count, list_id));
1319 }
1320 }
1321 Event::PasswordRequired {
1322 challenge_id,
1323 attempt,
1324 encrypt,
1325 } => {
1326 if run.cancel_sequence.is_some() {
1327 return;
1328 }
1329 if matches!(
1330 run.start,
1331 Start::CreateSevenZip { .. } | Start::RecoverZip { .. }
1332 ) || self.challenge.is_some()
1333 || self.resource.is_some()
1334 || challenge_id <= run.last_challenge
1335 || self.conflict.is_some()
1336 {
1337 self.error = Some("암호 요청이 유효하지 않습니다".into());
1338 } else {
1339 run.last_challenge = challenge_id;
1340 self.challenge = Some((challenge_id, attempt, encrypt));
1341 }
1342 }
1343 Event::ResourceRequired(question) => {
1344 if run.cancel_sequence.is_some() {
1345 return;
1346 }
1347 let expected = match run.start {
1348 Start::List { .. } => ActionKind::List,
1349 Start::Extract { .. } => ActionKind::Extract,
1350 Start::CreateZip { .. } => ActionKind::CreateZip,
1351 Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip,
1352 Start::Preview { .. } => ActionKind::Preview,
1353 Start::RecoverZip { .. } => ActionKind::RecoverZip,
1354 };
1355 let ceiling = if run.expanded {
1356 Limits::expanded(expected)
1357 } else {
1358 Limits::default()
1359 };
1360 if self.challenge.is_some()
1361 || self.resource.is_some()
1362 || self.conflict.is_some()
1363 || question.id <= run.last_challenge
1364 || question.action != expected
1365 || !question.scope.any()
1366 || question.soft_limits != Limits::default()
1367 || question.ceiling != ceiling
1368 || (question.scope.output && (!run.expanded || run.granted.output))
1369 || (question.scope.entries && (!run.expanded || run.granted.entries))
1370 || (question.scope.ratio && run.granted.ratio)
1371 {
1372 self.error = Some("자원 승인 요청이 유효하지 않습니다".into());
1373 } else {
1374 run.last_challenge = question.id;
1375 self.resource = Some(question);
1376 }
1377 }
1378 Event::ConflictRequired(conflict) => {
1379 let valid_entry = self
1380 .entries
1381 .iter()
1382 .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File);
1383 if !matches!(run.start, Start::Extract { .. })
1384 || !valid_entry
1385 || self.resource.is_some()
1386 || conflict.challenge_id <= run.last_challenge
1387 || self.challenge.is_some()
1388 || self.conflict.is_some()
1389 || run.conflict_ids.len()
1390 >= if run.granted.entries {
1391 200_000
1392 } else {
1393 100_000
1394 }
1395 || !valid_relative(&conflict.relative_name)
1396 || conflict.relative_name.len() > 4096
1397 || !run.conflict_ids.insert(conflict.challenge_id)
1398 {
1399 self.error = Some("파일 충돌 요청이 유효하지 않습니다".into());
1400 } else if run.cancel_sequence.is_none() {
1401 run.last_challenge = conflict.challenge_id;
1402 self.conflict = Some(conflict);
1403 }
1404 }
1405 Event::ConflictResolved(resolution) => {
1406 if !matches!(run.start, Start::Extract { .. })
1407 || !run.file_ids.contains(&resolution.entry_id)
1408 || self.resolutions.len()
1409 >= if run.granted.entries {
1410 200_000
1411 } else {
1412 100_000
1413 }
1414 || !valid_relative(&resolution.relative_name)
1415 || resolution.relative_name.len() > 4096
1416 || !run.resolved_ids.insert(resolution.entry_id)
1417 {
1418 self.error = Some("파일 충돌 결과가 유효하지 않습니다".into());
1419 } else {
1420 self.resolutions.push(resolution);
1421 }
1422 }
1423 Event::Progress {
1424 stage,
1425 processed,
1426 total,
1427 completed_entries,
1428 } => self.progress = Some((stage, processed, total, completed_entries)),
1429 Event::Output {
1430 relative_name,
1431 disposition,
1432 entry_id,
1433 } => {
1434 if let Start::RecoverZip { output_file, .. } = &run.start {
1435 let final_output = matches!(
1436 disposition,
1437 Disposition::Created | Disposition::CommitUncertain
1438 );
1439 let valid_output = if final_output {
1440 output_file.file_name().and_then(|n| n.to_str())
1441 == Some(relative_name.as_str())
1442 && !self.outputs.iter().any(|(_, d)| {
1443 matches!(
1444 d,
1445 Disposition::Created | Disposition::CommitUncertain
1446 )
1447 })
1448 } else {
1449 valid_leaf(&relative_name)
1450 && (disposition != Disposition::PartialRetained
1451 || output_file.file_name().and_then(|n| n.to_str())
1452 != Some(relative_name.as_str()))
1453 && !self.outputs.iter().any(|(name, d)| {
1454 name == &relative_name && *d == disposition
1455 })
1456 };
1457 if entry_id.is_some() || self.recovery_end.is_none() || !valid_output {
1458 self.error = Some("복구본 출력 응답이 유효하지 않습니다".into());
1459 return;
1460 }
1461 }
1462 if matches!(run.start, Start::Preview { .. }) {
1463 self.error = Some("미리보기 중 파일 출력이 보고됐습니다".into());
1464 return;
1465 }
1466 if self.outputs.len()
1467 < if run.granted.any() {
1468 // 암묵적 상위 폴더도 출력되므로 작업자 노드 예산과 맞춤
1469 262_144
1470 } else {
1471 100_000
1472 }
1473 && relative_name.len() <= 4096
1474 {
1475 self.outputs.push((relative_name, disposition));
1476 } else {
1477 self.error = Some("출력 보고 한도 초과".into());
1478 }
1479 }
1480 Event::CancelAck {
1481 request_sequence,
1482 status,
1483 } => {
1484 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
1485 self.cancel = Some(status);
1486 } else {
1487 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
1488 }
1489 }
1490 Event::Terminal(t) => {
1491 if matches!(run.start, Start::RecoverZip { .. }) {
1492 let business = t.outcome == Outcome::Completed
1493 || matches!(
1494 t.error,
1495 Some(
1496 ErrorCode::RecoveryIncomplete
1497 | ErrorCode::RecoveryImpossible
1498 )
1499 );
1500 if business
1501 && !self.recovery_end.as_ref().is_some_and(|s| {
1502 if s.verified_entries == 0 {
1503 t.outcome == Outcome::Failed
1504 && t.error == Some(ErrorCode::RecoveryImpossible)
1505 && t.publication == Publication::None
1506 && t.created_count == 0
1507 && self.outputs.is_empty()
1508 } else {
1509 t.publication == Publication::Complete
1510 && t.created_count == 1
1511 && self.outputs.len() == 1
1512 && self.outputs[0].1 == Disposition::Created
1513 && if s.complete() {
1514 t.outcome == Outcome::Completed && t.error.is_none()
1515 } else {
1516 t.outcome == Outcome::Failed
1517 && t.error
1518 == Some(ErrorCode::RecoveryIncomplete)
1519 }
1520 }
1521 })
1522 {
1523 self.error =
1524 Some("복구 결과와 저장 상태가 일치하지 않습니다".into());
1525 }
1526 }
1527 if run.cancel_sequence.is_none()
1528 && run.volume_problem.as_ref().is_some_and(|problem| {
1529 t.outcome != Outcome::Failed
1530 || t.error
1531 != match problem.reason {
1532 VolumeProblemReason::FirstVolumeRequired => {
1533 Some(ErrorCode::InvalidRequest)
1534 }
1535 VolumeProblemReason::MissingVolume => {
1536 Some(ErrorCode::MissingVolume)
1537 }
1538 VolumeProblemReason::IncompleteSet => {
1539 Some(ErrorCode::Integrity)
1540 }
1541 }
1542 })
1543 {
1544 self.error =
1545 Some("분할 조각 오류와 종료 상태가 일치하지 않습니다".into());
1546 }
1547 if matches!(run.start, Start::Preview { .. })
1548 && (t.publication != Publication::None
1549 || t.created_count != 0
1550 || t.retained_partial_count != 0
1551 || t.durability != Durability::NotApplicable)
1552 {
1553 self.error = Some("미리보기 종료 상태가 유효하지 않습니다".into());
1554 }
1555 if t.outcome != Outcome::Completed {
1556 run.preview = None;
1557 }
1558 self.challenge = None;
1559 self.conflict = None;
1560 self.terminal = Some(t);
1561 }
1562 }
1563 }
1564 }
1565 }
1566 pub fn status(&self) -> String {
1567 if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) {
1568 return error.clone();
1569 }
1570 if self.busy() {
1571 if self.terminal.is_some() {
1572 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
1573 }
1574 if self.resource.is_some() {
1575 return "사용자 허용 대기".into();
1576 }
1577 if self.conflict.is_some() {
1578 return "같은 이름의 파일을 처리할 방법을 선택하세요".into();
1579 }
1580 if self.challenge.is_some() {
1581 return "암호를 입력하세요".into();
1582 }
1583 if let Some(c) = self.cancel {
1584 return match c {
1585 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
1586 "취소 요청 접수 / 최종 결과 대기"
1587 }
1588 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
1589 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
1590 }
1591 .into();
1592 }
1593 if self
1594 .running
1595 .as_ref()
1596 .is_some_and(|r| r.cancel_sequence.is_some())
1597 {
1598 return "취소 요청 전송 / 최종 결과 대기".into();
1599 }
1600 return "작업 중".into();
1601 }
1602 match self
1603 .terminal
1604 .as_ref()
1605 .filter(|_| self.confirmed)
1606 .map(|t| t.outcome)
1607 {
1608 Some(Outcome::Completed) => "작업 완료",
1609 Some(Outcome::Cancelled) => "작업 취소됨",
1610 Some(Outcome::Failed) => "작업 실패",
1611 None => "압축파일을 열거나 ZIP 파일을 만드세요",
1612 }
1613 .into()
1614 }
1615}
1616pub fn valid_leaf(name: &str) -> bool {
1617 valid_relative(name) && !name.contains('/') && !name.contains('\\')
1618}
1619pub fn valid_relative(name: &str) -> bool {
1620 !name.is_empty()
1621 && !name.contains('\0')
1622 && !name.contains(':')
1623 && !name.starts_with('/')
1624 && !name.starts_with('\\')
1625 && name
1626 .split(['/', '\\'])
1627 .all(|p| !p.is_empty() && p != "." && p != "..")
1628}
1629
1630// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
1631pub fn launch_args(
1632 args: Vec<std::ffi::OsString>,
1633 cwd: PathBuf,
1634) -> Result<(bool, Option<PathBuf>), &'static str> {
1635 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
1636 let paths = args
1637 .into_iter()
1638 .filter(|arg| arg != "--ui-fixture")
1639 .collect::<Vec<_>>();
1640 if paths.len() > 1 {
1641 return Err("압축파일 하나를 지정하세요");
1642 }
1643 let path = paths
1644 .into_iter()
1645 .next()
1646 .map(PathBuf::from)
1647 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
1648 Ok((fixture, path))
1649}
1650
1651pub fn stage_label(stage: Stage) -> &'static str {
1652 match stage {
1653 Stage::Scan => "목록 읽는 중",
1654 Stage::Read => "파일 읽는 중",
1655 Stage::Decode => "압축 푸는 중",
1656 Stage::Write => "파일 쓰는 중",
1657 Stage::Verify => "검증 중",
1658 Stage::Commit => "저장 마무리 중",
1659 }
1660}
1661pub fn disposition_label(disposition: Disposition) -> &'static str {
1662 match disposition {
1663 Disposition::Created => "생성됨",
1664 Disposition::PartialRetained => "일부 파일 남음",
1665 Disposition::Removed => "작업 임시 파일 정리됨",
1666 Disposition::CommitUncertain => "저장 여부 불확실",
1667 }
1668}
1669pub fn terminal_lines(t: &Terminal) -> Vec<String> {
1670 let publication = match t.publication {
1671 Publication::None => "게시된 파일 없음",
1672 Publication::Partial => "일부 파일 게시됨",
1673 Publication::Complete => "파일 게시 완료",
1674 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
1675 };
1676 let durability = match t.durability {
1677 Durability::NotApplicable => "동기화 해당 없음",
1678 Durability::Synced => "디스크 동기화 완료",
1679 Durability::Unconfirmed => "디스크 동기화 미확인",
1680 Durability::Failed => "디스크 동기화 실패",
1681 };
1682 let cleanup = match t.cleanup {
1683 Cleanup::Complete => "작업 임시 파일 정리 완료",
1684 Cleanup::Failed => "작업 임시 파일 정리 실패",
1685 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
1686 };
1687 let mut lines = vec![
1688 publication.into(),
1689 format!(
1690 "생성 {}개 / 남은 임시 파일 {}개",
1691 t.created_count, t.retained_partial_count
1692 ),
1693 format!("{durability} / {cleanup}"),
1694 ];
1695 if let Some(error) = t.error {
1696 lines.push(
1697 match error {
1698 ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다",
1699 ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다",
1700 ErrorCode::MissingVolume => "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 첫 조각을 다시 여세요",
1701 ErrorCode::Integrity => "압축파일이 손상됐습니다",
1702 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
1703 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
1704 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
1705 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
1706 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
1707 ErrorCode::Limit => "처리 한도를 초과했습니다",
1708 ErrorCode::Io => {
1709 "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
1710 }
1711 ErrorCode::DiskFull => {
1712 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
1713 }
1714 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
1715 ErrorCode::Internal => "작업자 처리 오류입니다",
1716 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
1717 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
1718 }
1719 .into(),
1720 );
1721 }
1722 lines
1723}