team-ljyzipelo

공개
1,406줄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 { entry_id, .. } => {
504 usage.estimated_entries = Some(1);
505 usage.estimated_bytes = self
506 .entries
507 .iter()
508 .find(|e| e.id == *entry_id)
509 .and_then(|e| e.bytes);
510 }
511 Start::List { .. } => {}
512 }
513 usage
514 }
515 fn needs_expansion(&self, start: &Start) -> bool {
516 let usage = self.estimate(start);
517 usage
518 .estimated_bytes
519 .is_some_and(|n| n > Limits::default().output)
520 || usage
521 .estimated_entries
522 .is_some_and(|n| n > Limits::default().entries)
523 }
524 pub fn can_retry_expanded(&self) -> bool {
525 !self.busy() && self.retry_start.is_some() && self.close == Close::Open
526 }
527 pub fn retry_expanded(&mut self, factory: &mut dyn Factory) -> bool {
528 if !self.can_retry_expanded() {
529 return false;
530 }
531 let start = self.retry_start.clone().unwrap();
532 self.begin_with_limits(start, factory, true)
533 }
534 pub fn resource_reply(&mut self, job_id: u64, challenge_id: u64, allow: bool) -> bool {
535 if self.job_id() != Some(job_id) || self.cancellation_requested() {
536 return false;
537 }
538 let Some(question) = self.resource.clone().filter(|q| q.id == challenge_id) else {
539 return false;
540 };
541 if self
542 .send(Command::ResourceReply {
543 challenge_id,
544 scope: question.scope,
545 allow,
546 })
547 .is_none()
548 {
549 return false;
550 }
551 if allow {
552 let granted = &mut self.running.as_mut().unwrap().granted;
553 granted.output |= question.scope.output;
554 granted.entries |= question.scope.entries;
555 granted.ratio |= question.scope.ratio;
556 }
557 self.resource = None;
558 true
559 }
560 fn begin_with_limits(
561 &mut self,
562 start: Start,
563 factory: &mut dyn Factory,
564 expanded: bool,
565 ) -> bool {
566 if self.busy() || self.close != Close::Open {
567 return false;
568 }
569 let selectable: BTreeSet<_> = self
570 .entries
571 .iter()
572 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
573 .map(|e| e.id)
574 .collect();
575 let validation = match &start {
576 Start::List { archive } => archive.is_absolute(),
577 Start::Preview {
578 archive,
579 entry_id,
580 list_id,
581 } => {
582 archive.is_absolute()
583 && self.archive.as_ref() == Some(archive)
584 && self.list_id.as_ref() == Some(list_id)
585 && self
586 .entries
587 .iter()
588 .any(|e| e.id == *entry_id && e.kind == Kind::File)
589 }
590 Start::Extract {
591 archive,
592 destination,
593 selection,
594 gzip_output_name,
595 list_id,
596 } => {
597 archive.is_absolute()
598 && destination.is_absolute()
599 && self.archive.as_ref() == Some(archive)
600 && self.list_id.as_ref() == Some(list_id)
601 && match list_id.format {
602 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
603 _ => gzip_output_name.is_none(),
604 }
605 && match selection {
606 Selection::All => true,
607 Selection::EntryIds(ids) => {
608 !ids.is_empty()
609 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
610 && ids.iter().all(|id| selectable.contains(id))
611 }
612 }
613 }
614 Start::CreateZip {
615 sources,
616 output_file,
617 ..
618 } => {
619 !sources.is_empty()
620 && output_file.is_absolute()
621 && sources
622 .iter()
623 .all(|(p, n)| p.is_absolute() && valid_relative(n))
624 }
625 };
626 if !validation {
627 self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
628 return false;
629 }
630 let Some(id) = self.next_id.checked_add(1) else {
631 self.error = Some("작업 ID 한도에 도달했습니다".into());
632 return false;
633 };
634 self.preview = None;
635 let estimated = self.estimate(&start);
636 let mut connection = match factory.connect(id) {
637 Ok(c) => c,
638 Err(e) => {
639 self.error = Some(e);
640 return false;
641 }
642 };
643 let send_error = connection
644 .send(Request {
645 job_id: id,
646 sequence: 0,
647 command: if expanded {
648 Command::StartExpanded(start.clone())
649 } else {
650 Command::Start(start.clone())
651 },
652 })
653 .err();
654 let started = send_error.is_none();
655 if let Start::List { archive } = &start
656 && started
657 {
658 self.archive = Some(archive.clone());
659 self.list_id = None;
660 self.entries.clear();
661 self.selected.clear();
662 }
663 self.next_id = id;
664 self.terminal = None;
665 self.retry_start = None;
666 self.resource = None;
667 self.challenge = None;
668 self.conflict = None;
669 self.resolutions.clear();
670 self.progress = None;
671 self.outputs.clear();
672 self.cancel = None;
673 self.input_error = None;
674 self.error = send_error;
675 self.confirmed = false;
676 self.running = Some(Running {
677 preview: None,
678 preview_discarded: false,
679 id,
680 outgoing: 1,
681 incoming: 0,
682 accepted: false,
683 start_failed: !started,
684 start,
685 connection,
686 entries: Vec::new(),
687 list_end: None,
688 stdout_eof: false,
689 transport_closed: false,
690 stderr_eof: false,
691 exit: None,
692 cancel_sequence: None,
693 expanded,
694 granted: ResourceScope::default(),
695 last_challenge: 0,
696 estimated,
697 conflict_ids: BTreeSet::new(),
698 resolved_ids: BTreeSet::new(),
699 file_ids: self
700 .entries
701 .iter()
702 .filter(|e| e.kind == Kind::File)
703 .map(|e| e.id)
704 .collect(),
705 });
706 started
707 }
708 pub fn extract(
709 &mut self,
710 destination: PathBuf,
711 selected_only: bool,
712 gzip_output_name: Option<String>,
713 factory: &mut dyn Factory,
714 ) -> bool {
715 if !self.can_extract() {
716 return false;
717 }
718 self.begin(
719 Start::Extract {
720 archive: self.archive.clone().unwrap(),
721 destination,
722 selection: if selected_only {
723 Selection::EntryIds(self.selected.iter().copied().collect())
724 } else {
725 Selection::All
726 },
727 list_id: self.list_id.clone().unwrap(),
728 gzip_output_name,
729 },
730 factory,
731 )
732 }
733 pub fn password(&mut self, text: String) -> bool {
734 let Some((challenge_id, _, _)) = self.challenge else {
735 return false;
736 };
737 let secret = match Secret::new(text) {
738 Ok(s) => s,
739 Err(e) => {
740 self.input_error = Some(e.into());
741 return false;
742 }
743 };
744 if self
745 .send(Command::Password {
746 challenge_id,
747 secret,
748 })
749 .is_some()
750 {
751 self.challenge = None;
752 self.resource = None;
753 self.conflict = None;
754 self.input_error = None;
755 true
756 } else {
757 false
758 }
759 }
760 pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool {
761 let Some(conflict) = &self.conflict else {
762 return false;
763 };
764 if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open {
765 return false;
766 }
767 if self
768 .send(Command::ConflictReply {
769 challenge_id: conflict.challenge_id,
770 choice,
771 apply_to_remaining,
772 })
773 .is_some()
774 {
775 self.conflict = None;
776 self.input_error = None;
777 true
778 } else {
779 false
780 }
781 }
782 fn send(&mut self, command: Command) -> Option<u64> {
783 let run = self.running.as_mut()?;
784 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
785 return None;
786 }
787 let seq = run.outgoing;
788 let Some(next) = seq.checked_add(1) else {
789 self.error = Some("요청 순서 한도 초과".into());
790 return None;
791 };
792 match run.connection.send(Request {
793 job_id: run.id,
794 sequence: seq,
795 command,
796 }) {
797 Ok(()) => {
798 run.outgoing = next;
799 Some(seq)
800 }
801 Err(e) => {
802 self.error = Some(e);
803 None
804 }
805 }
806 }
807 pub fn cancel(&mut self) {
808 self.preview = None;
809 if let Some(run) = self.running.as_mut()
810 && matches!(run.start, Start::Preview { .. })
811 {
812 run.preview = None;
813 run.preview_discarded = true;
814 }
815 if self
816 .running
817 .as_ref()
818 .is_some_and(|r| r.cancel_sequence.is_none())
819 {
820 if let Some(seq) = self.send(Command::Cancel) {
821 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
822 self.challenge = None;
823 self.resource = None;
824 self.conflict = None;
825 self.input_error = None;
826 }
827 }
828 }
829 pub fn request_close(&mut self) {
830 if self.close == Close::Open {
831 self.close = if self.busy() {
832 Close::Confirm
833 } else {
834 Close::Review
835 };
836 }
837 }
838 pub fn confirm_close(&mut self) {
839 if self.close == Close::Confirm {
840 self.cancel();
841 self.close = if self.busy() {
842 Close::Waiting
843 } else {
844 Close::Review
845 };
846 }
847 }
848 pub fn keep_open(&mut self) {
849 if self.close != Close::Allowed {
850 self.close = Close::Open;
851 }
852 }
853 pub fn acknowledge_close(&mut self) {
854 if !self.busy() && self.close == Close::Review {
855 self.close = Close::Allowed;
856 }
857 }
858 pub fn poll(&mut self) {
859 let changed = self.running.as_ref().is_some_and(|run| {
860 matches!(&run.start, Start::Preview { entry_id, .. }
861 if self.selected.len() != 1 || !self.selected.contains(entry_id))
862 });
863 if changed {
864 self.dismiss_preview();
865 }
866 for _ in 0..128 {
867 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
868 break;
869 };
870 self.receive(event);
871 if self.error.is_some()
872 && self
873 .running
874 .as_ref()
875 .is_some_and(|run| matches!(run.start, Start::Preview { .. }))
876 {
877 self.cancel();
878 }
879 }
880 let complete = self.running.as_ref().is_some_and(|r| {
881 r.exit.is_some()
882 && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
883 });
884 if complete {
885 let mut run = self.running.take().unwrap();
886 self.confirmed =
887 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
888 if !self.confirmed {
889 self.error.get_or_insert(
890 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
891 );
892 }
893 if self.confirmed
894 && self
895 .terminal
896 .as_ref()
897 .is_some_and(|t| t.outcome == Outcome::Completed)
898 {
899 if matches!(run.start, Start::List { .. }) {
900 if let Some((count, id)) = run
901 .list_end
902 .filter(|(n, _)| *n as usize == run.entries.len())
903 {
904 let _ = count;
905 self.entries = run.entries;
906 self.list_id = Some(id);
907 } else {
908 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
909 self.confirmed = false;
910 }
911 }
912 }
913 if matches!(run.start, Start::Preview { .. }) {
914 if self.confirmed
915 && self
916 .terminal
917 .as_ref()
918 .is_some_and(|t| t.outcome == Outcome::Completed)
919 && !run.preview_discarded
920 {
921 if let Some(buffer) = run.preview.take().filter(|b| b.ended) {
922 self.preview = Some(Preview {
923 info: buffer.info,
924 data: buffer.data,
925 });
926 } else {
927 self.error = Some("미리보기 완료 정보가 일치하지 않습니다".into());
928 self.confirmed = false;
929 }
930 }
931 }
932 if self
933 .terminal
934 .as_ref()
935 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
936 {
937 self.list_id = None;
938 self.selected.clear();
939 }
940 self.retry_start = if !matches!(run.start, Start::Preview { .. })
941 && !run.expanded
942 && run.cancel_sequence.is_none()
943 && self.confirmed
944 && self.terminal.as_ref().is_some_and(|t| {
945 t.outcome == Outcome::Failed
946 && t.error == Some(ErrorCode::Limit)
947 && t.publication == Publication::None
948 && t.created_count == 0
949 && t.retained_partial_count == 0
950 && t.cleanup == Cleanup::Complete
951 })
952 && self.outputs.iter().all(|(_, d)| *d == Disposition::Removed)
953 {
954 Some(run.start.clone())
955 } else {
956 None
957 };
958 self.challenge = None;
959 self.resource = None;
960 self.conflict = None;
961 self.input_error = None;
962 if matches!(self.close, Close::Waiting | Close::Confirm) {
963 self.close = Close::Review;
964 }
965 }
966 }
967 fn receive(&mut self, host: HostEvent) {
968 let run = self.running.as_mut().unwrap();
969 match host {
970 HostEvent::Fault(message) => self.error = Some(message),
971 HostEvent::CleanupComplete => run.transport_closed = true,
972 HostEvent::StdoutEof => run.stdout_eof = true,
973 HostEvent::StderrEof => run.stderr_eof = true,
974 HostEvent::Exited { success } => run.exit = Some(success),
975 HostEvent::Frame {
976 job_id,
977 sequence,
978 event,
979 } => {
980 if job_id != run.id
981 || sequence != run.incoming
982 || self.terminal.is_some()
983 || run.stdout_eof
984 || sequence >= 1_000_000
985 {
986 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
987 return;
988 }
989 run.incoming += 1;
990 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
991 self.error = Some("작업 승인 응답이 없습니다".into());
992 return;
993 }
994 match event {
995 Event::PreviewBegin(info) => {
996 if run.preview_discarded {
997 return;
998 }
999 if !matches!(run.start, Start::Preview { entry_id, .. } if entry_id == info.entry_id)
1000 || run.preview.is_some()
1001 || !info.valid()
1002 || self.error.is_some()
1003 {
1004 self.error = Some("미리보기 메타정보가 유효하지 않습니다".into());
1005 } else {
1006 let mut data = Vec::new();
1007 if data.try_reserve_exact(info.total_bytes as usize).is_err() {
1008 self.error = Some("미리보기 메모리를 확보하지 못했습니다".into());
1009 } else {
1010 run.preview = Some(PreviewBuffer {
1011 info,
1012 data,
1013 ended: false,
1014 });
1015 }
1016 }
1017 }
1018 Event::PreviewChunk {
1019 entry_id,
1020 offset,
1021 data,
1022 } => {
1023 if run.preview_discarded {
1024 return;
1025 }
1026 if self.error.is_some()
1027 || !run
1028 .preview
1029 .as_mut()
1030 .is_some_and(|b| b.chunk(entry_id, offset, data))
1031 {
1032 run.preview = None;
1033 self.error =
1034 Some("미리보기 데이터 순서나 크기가 일치하지 않습니다".into());
1035 }
1036 }
1037 Event::PreviewEnd {
1038 entry_id,
1039 total_bytes,
1040 sha256,
1041 } => {
1042 if run.preview_discarded {
1043 return;
1044 }
1045 if !run
1046 .preview
1047 .as_mut()
1048 .is_some_and(|b| b.end(entry_id, total_bytes, sha256))
1049 {
1050 run.preview = None;
1051 self.error = Some("미리보기 내용 검증에 실패했습니다".into());
1052 }
1053 }
1054 Event::Accepted { encryption } => {
1055 if run.accepted {
1056 self.error = Some("작업 승인 중복".into());
1057 }
1058 run.accepted = true;
1059 self.encryption = encryption;
1060 }
1061 Event::Entry(entry) => {
1062 if !matches!(run.start, Start::List { .. })
1063 || run.list_end.is_some()
1064 || entry.id as usize != run.entries.len()
1065 || entry.name.len() > 4096
1066 || run.entries.len()
1067 >= if run.granted.entries {
1068 200_000
1069 } else {
1070 100_000
1071 }
1072 {
1073 self.error = Some("목록 응답이 유효하지 않습니다".into());
1074 } else {
1075 run.entries.push(entry);
1076 }
1077 }
1078 Event::ListEnd {
1079 entry_count,
1080 list_id,
1081 } => {
1082 if !matches!(run.start, Start::List { .. })
1083 || run.list_end.is_some()
1084 || list_id.catalog_version != 1
1085 {
1086 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
1087 } else {
1088 run.list_end = Some((entry_count, list_id));
1089 }
1090 }
1091 Event::PasswordRequired {
1092 challenge_id,
1093 attempt,
1094 encrypt,
1095 } => {
1096 if run.cancel_sequence.is_some() {
1097 return;
1098 }
1099 if self.challenge.is_some()
1100 || self.resource.is_some()
1101 || challenge_id <= run.last_challenge
1102 || self.conflict.is_some()
1103 {
1104 self.error = Some("암호 요청이 유효하지 않습니다".into());
1105 } else {
1106 run.last_challenge = challenge_id;
1107 self.challenge = Some((challenge_id, attempt, encrypt));
1108 }
1109 }
1110 Event::ResourceRequired(question) => {
1111 if run.cancel_sequence.is_some() {
1112 return;
1113 }
1114 let expected = match run.start {
1115 Start::List { .. } => ActionKind::List,
1116 Start::Extract { .. } => ActionKind::Extract,
1117 Start::CreateZip { .. } => ActionKind::CreateZip,
1118 Start::Preview { .. } => ActionKind::Preview,
1119 };
1120 let hard = Limits {
1121 input: u64::MAX,
1122 output: 64 * 1024 * 1024 * 1024,
1123 entries: 200_000,
1124 };
1125 let ceiling = if run.expanded {
1126 hard
1127 } else {
1128 Limits::default()
1129 };
1130 if self.challenge.is_some()
1131 || self.resource.is_some()
1132 || self.conflict.is_some()
1133 || question.id <= run.last_challenge
1134 || question.action != expected
1135 || !question.scope.any()
1136 || question.soft_limits != Limits::default()
1137 || question.ceiling != ceiling
1138 || (question.scope.output && (!run.expanded || run.granted.output))
1139 || (question.scope.entries && (!run.expanded || run.granted.entries))
1140 || (question.scope.ratio && run.granted.ratio)
1141 {
1142 self.error = Some("자원 승인 요청이 유효하지 않습니다".into());
1143 } else {
1144 run.last_challenge = question.id;
1145 self.resource = Some(question);
1146 }
1147 }
1148 Event::ConflictRequired(conflict) => {
1149 let valid_entry = self
1150 .entries
1151 .iter()
1152 .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File);
1153 if !matches!(run.start, Start::Extract { .. })
1154 || !valid_entry
1155 || self.resource.is_some()
1156 || conflict.challenge_id <= run.last_challenge
1157 || self.challenge.is_some()
1158 || self.conflict.is_some()
1159 || run.conflict_ids.len()
1160 >= if run.granted.entries {
1161 200_000
1162 } else {
1163 100_000
1164 }
1165 || !valid_relative(&conflict.relative_name)
1166 || conflict.relative_name.len() > 4096
1167 || !run.conflict_ids.insert(conflict.challenge_id)
1168 {
1169 self.error = Some("파일 충돌 요청이 유효하지 않습니다".into());
1170 } else if run.cancel_sequence.is_none() {
1171 run.last_challenge = conflict.challenge_id;
1172 self.conflict = Some(conflict);
1173 }
1174 }
1175 Event::ConflictResolved(resolution) => {
1176 if !matches!(run.start, Start::Extract { .. })
1177 || !run.file_ids.contains(&resolution.entry_id)
1178 || self.resolutions.len()
1179 >= if run.granted.entries {
1180 200_000
1181 } else {
1182 100_000
1183 }
1184 || !valid_relative(&resolution.relative_name)
1185 || resolution.relative_name.len() > 4096
1186 || !run.resolved_ids.insert(resolution.entry_id)
1187 {
1188 self.error = Some("파일 충돌 결과가 유효하지 않습니다".into());
1189 } else {
1190 self.resolutions.push(resolution);
1191 }
1192 }
1193 Event::Progress {
1194 stage,
1195 processed,
1196 total,
1197 completed_entries,
1198 } => self.progress = Some((stage, processed, total, completed_entries)),
1199 Event::Output {
1200 relative_name,
1201 disposition,
1202 ..
1203 } => {
1204 if matches!(run.start, Start::Preview { .. }) {
1205 self.error = Some("미리보기 중 파일 출력이 보고됐습니다".into());
1206 return;
1207 }
1208 if self.outputs.len()
1209 < if run.granted.any() {
1210 // 암묵적 상위 폴더도 출력되므로 작업자 노드 예산과 맞춤
1211 262_144
1212 } else {
1213 100_000
1214 }
1215 && relative_name.len() <= 4096
1216 {
1217 self.outputs.push((relative_name, disposition));
1218 } else {
1219 self.error = Some("출력 보고 한도 초과".into());
1220 }
1221 }
1222 Event::CancelAck {
1223 request_sequence,
1224 status,
1225 } => {
1226 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
1227 self.cancel = Some(status);
1228 } else {
1229 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
1230 }
1231 }
1232 Event::Terminal(t) => {
1233 if matches!(run.start, Start::Preview { .. })
1234 && (t.publication != Publication::None
1235 || t.created_count != 0
1236 || t.retained_partial_count != 0
1237 || t.durability != Durability::NotApplicable)
1238 {
1239 self.error = Some("미리보기 종료 상태가 유효하지 않습니다".into());
1240 }
1241 if t.outcome != Outcome::Completed {
1242 run.preview = None;
1243 }
1244 self.challenge = None;
1245 self.conflict = None;
1246 self.terminal = Some(t);
1247 }
1248 }
1249 }
1250 }
1251 }
1252 pub fn status(&self) -> String {
1253 if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) {
1254 return error.clone();
1255 }
1256 if self.busy() {
1257 if self.terminal.is_some() {
1258 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
1259 }
1260 if self.resource.is_some() {
1261 return "사용자 허용 대기".into();
1262 }
1263 if self.conflict.is_some() {
1264 return "같은 이름의 파일을 처리할 방법을 선택하세요".into();
1265 }
1266 if self.challenge.is_some() {
1267 return "암호를 입력하세요".into();
1268 }
1269 if let Some(c) = self.cancel {
1270 return match c {
1271 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
1272 "취소 요청 접수 / 최종 결과 대기"
1273 }
1274 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
1275 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
1276 }
1277 .into();
1278 }
1279 if self
1280 .running
1281 .as_ref()
1282 .is_some_and(|r| r.cancel_sequence.is_some())
1283 {
1284 return "취소 요청 전송 / 최종 결과 대기".into();
1285 }
1286 return "작업 중".into();
1287 }
1288 match self
1289 .terminal
1290 .as_ref()
1291 .filter(|_| self.confirmed)
1292 .map(|t| t.outcome)
1293 {
1294 Some(Outcome::Completed) => "작업 완료",
1295 Some(Outcome::Cancelled) => "작업 취소됨",
1296 Some(Outcome::Failed) => "작업 실패",
1297 None => "압축파일을 열거나 ZIP 파일을 만드세요",
1298 }
1299 .into()
1300 }
1301}
1302pub fn valid_leaf(name: &str) -> bool {
1303 valid_relative(name) && !name.contains('/') && !name.contains('\\')
1304}
1305pub fn valid_relative(name: &str) -> bool {
1306 !name.is_empty()
1307 && !name.contains('\0')
1308 && !name.contains(':')
1309 && !name.starts_with('/')
1310 && !name.starts_with('\\')
1311 && name
1312 .split(['/', '\\'])
1313 .all(|p| !p.is_empty() && p != "." && p != "..")
1314}
1315
1316// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
1317pub fn launch_args(
1318 args: Vec<std::ffi::OsString>,
1319 cwd: PathBuf,
1320) -> Result<(bool, Option<PathBuf>), &'static str> {
1321 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
1322 let paths = args
1323 .into_iter()
1324 .filter(|arg| arg != "--ui-fixture")
1325 .collect::<Vec<_>>();
1326 if paths.len() > 1 {
1327 return Err("압축파일 하나를 지정하세요");
1328 }
1329 let path = paths
1330 .into_iter()
1331 .next()
1332 .map(PathBuf::from)
1333 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
1334 Ok((fixture, path))
1335}
1336
1337pub fn stage_label(stage: Stage) -> &'static str {
1338 match stage {
1339 Stage::Scan => "목록 읽는 중",
1340 Stage::Read => "파일 읽는 중",
1341 Stage::Decode => "압축 푸는 중",
1342 Stage::Write => "파일 쓰는 중",
1343 Stage::Verify => "검증 중",
1344 Stage::Commit => "저장 마무리 중",
1345 }
1346}
1347pub fn disposition_label(disposition: Disposition) -> &'static str {
1348 match disposition {
1349 Disposition::Created => "생성됨",
1350 Disposition::PartialRetained => "일부 파일 남음",
1351 Disposition::Removed => "작업 임시 파일 정리됨",
1352 Disposition::CommitUncertain => "저장 여부 불확실",
1353 }
1354}
1355pub fn terminal_lines(t: &Terminal) -> Vec<String> {
1356 let publication = match t.publication {
1357 Publication::None => "게시된 파일 없음",
1358 Publication::Partial => "일부 파일 게시됨",
1359 Publication::Complete => "파일 게시 완료",
1360 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
1361 };
1362 let durability = match t.durability {
1363 Durability::NotApplicable => "동기화 해당 없음",
1364 Durability::Synced => "디스크 동기화 완료",
1365 Durability::Unconfirmed => "디스크 동기화 미확인",
1366 Durability::Failed => "디스크 동기화 실패",
1367 };
1368 let cleanup = match t.cleanup {
1369 Cleanup::Complete => "작업 임시 파일 정리 완료",
1370 Cleanup::Failed => "작업 임시 파일 정리 실패",
1371 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
1372 };
1373 let mut lines = vec![
1374 publication.into(),
1375 format!(
1376 "생성 {}개 / 남은 임시 파일 {}개",
1377 t.created_count, t.retained_partial_count
1378 ),
1379 format!("{durability} / {cleanup}"),
1380 ];
1381 if let Some(error) = t.error {
1382 lines.push(
1383 match error {
1384 ErrorCode::Integrity => "압축파일이 손상됐습니다",
1385 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
1386 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
1387 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
1388 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
1389 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
1390 ErrorCode::Limit => "처리 한도를 초과했습니다",
1391 ErrorCode::Io => {
1392 "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
1393 }
1394 ErrorCode::DiskFull => {
1395 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
1396 }
1397 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
1398 ErrorCode::Internal => "작업자 처리 오류입니다",
1399 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
1400 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
1401 }
1402 .into(),
1403 );
1404 }
1405 lines
1406}