team-ljyzipelo

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