team-ljyzipelo

공개
1,052줄35 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 CreateZip {
47 sources: Vec<(PathBuf, String)>,
48 output_file: PathBuf,
49 method: Method,
50 aes256: bool,
51 },
52}
53// 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
54pub struct Secret(Vec<u8>);
55impl Secret {
56 pub fn new(text: String) -> Result<Self, &'static str> {
57 let mut bytes = text.into_bytes();
58 if bytes.is_empty() || bytes.len() > 1024 {
59 bytes.fill(0);
60 return Err("암호는 UTF-8 1~1024바이트로 입력하세요");
61 }
62 Ok(Self(bytes))
63 }
64 pub fn as_bytes(&self) -> &[u8] {
65 &self.0
66 }
67}
68impl Drop for Secret {
69 fn drop(&mut self) {
70 self.0.fill(0);
71 }
72}
73pub enum Command {
74 Start(Start),
75 StartExpanded(Start),
76 ResourceReply {
77 challenge_id: u64,
78 scope: ResourceScope,
79 allow: bool,
80 },
81 Password {
82 challenge_id: u64,
83 secret: Secret,
84 },
85 Cancel,
86}
87pub struct Request {
88 pub job_id: u64,
89 pub sequence: u64,
90 pub command: Command,
91}
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub enum Kind {
94 File,
95 Directory,
96 Link,
97 Other,
98}
99#[derive(Clone, Debug, Eq, PartialEq)]
100pub struct Entry {
101 pub id: u32,
102 pub name: String,
103 pub kind: Kind,
104 pub bytes: Option<u64>,
105 pub packed: Option<u64>,
106 pub encrypted: bool,
107}
108#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109pub enum CancelStatus {
110 Requested,
111 AlreadyRequested,
112 TooLate,
113 Finished,
114}
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
116pub enum Stage {
117 Scan,
118 Read,
119 Decode,
120 Write,
121 Verify,
122 Commit,
123}
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum Outcome {
126 Completed,
127 Failed,
128 Cancelled,
129}
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub enum ErrorCode {
132 Integrity,
133 UnsupportedFormat,
134 UnsupportedFeature,
135 WrongPassword,
136 UnsafePath,
137 Conflict,
138 Limit,
139 Io,
140 DiskFull,
141 Protocol,
142 Internal,
143 SourceChanged,
144 InvalidRequest,
145}
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub enum Publication {
148 None,
149 Partial,
150 Complete,
151 Uncertain,
152}
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub enum Durability {
155 NotApplicable,
156 Synced,
157 Unconfirmed,
158 Failed,
159}
160#[derive(Clone, Copy, Debug, Eq, PartialEq)]
161pub enum Cleanup {
162 Complete,
163 Failed,
164 Unconfirmed,
165}
166#[derive(Clone, Copy, Debug, Eq, PartialEq)]
167pub enum Disposition {
168 Created,
169 PartialRetained,
170 Removed,
171 CommitUncertain,
172}
173#[derive(Clone, Debug)]
174pub struct Terminal {
175 pub outcome: Outcome,
176 pub error: Option<ErrorCode>,
177 pub publication: Publication,
178 pub created_count: u64,
179 pub retained_partial_count: u64,
180 pub durability: Durability,
181 pub cleanup: Cleanup,
182}
183pub use worker_protocol::protocol::{ActionKind, Limits, ResourceScope, ResourceUsage};
184#[derive(Clone, Debug)]
185pub struct ResourceChallenge {
186 pub id: u64,
187 pub action: ActionKind,
188 pub scope: ResourceScope,
189 pub usage: ResourceUsage,
190 pub soft_limits: Limits,
191 pub ceiling: Limits,
192}
193
194#[derive(Clone, Debug)]
195pub enum Event {
196 ResourceRequired(ResourceChallenge),
197 Accepted {
198 encryption: bool,
199 },
200 Entry(Entry),
201 ListEnd {
202 entry_count: u32,
203 list_id: ListId,
204 },
205 PasswordRequired {
206 challenge_id: u64,
207 attempt: u32,
208 encrypt: bool,
209 },
210 Progress {
211 stage: Stage,
212 processed: u64,
213 total: Option<u64>,
214 completed_entries: u64,
215 },
216 Output {
217 entry_id: Option<u32>,
218 relative_name: String,
219 disposition: Disposition,
220 },
221 CancelAck {
222 request_sequence: u64,
223 status: CancelStatus,
224 },
225 Terminal(Terminal),
226}
227pub enum HostEvent {
228 Fault(String),
229 CleanupComplete,
230 Frame {
231 job_id: u64,
232 sequence: u64,
233 event: Event,
234 },
235 StdoutEof,
236 StderrEof,
237 Exited {
238 success: bool,
239 },
240}
241// 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함.
242// 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함.
243pub trait Connection {
244 fn send(&mut self, request: Request) -> Result<(), String>;
245 fn poll(&mut self) -> Option<HostEvent>;
246}
247pub trait Factory {
248 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
249}
250pub struct Unavailable;
251impl Factory for Unavailable {
252 fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
253 Err("작업자 연결이 아직 준비되지 않았습니다".into())
254 }
255}
256struct Running {
257 id: u64,
258 outgoing: u64,
259 incoming: u64,
260 accepted: bool,
261 start_failed: bool,
262 start: Start,
263 connection: Box<dyn Connection>,
264 entries: Vec<Entry>,
265 list_end: Option<(u32, ListId)>,
266 stdout_eof: bool,
267 transport_closed: bool,
268 stderr_eof: bool,
269 exit: Option<bool>,
270 cancel_sequence: Option<u64>,
271 expanded: bool,
272 granted: ResourceScope,
273 last_challenge: u64,
274 estimated: ResourceUsage,
275}
276#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
277pub enum Close {
278 #[default]
279 Open,
280 Confirm,
281 Waiting,
282 Review,
283 Allowed,
284}
285#[derive(Default)]
286pub struct Model {
287 running: Option<Running>,
288 next_id: u64,
289 pub archive: Option<PathBuf>,
290 pub entries: Vec<Entry>,
291 pub list_id: Option<ListId>,
292 pub selected: BTreeSet<u32>,
293 pub terminal: Option<Terminal>,
294 pub challenge: Option<(u64, u32, bool)>,
295 pub resource: Option<ResourceChallenge>,
296 retry_start: Option<Start>,
297 pub progress: Option<(Stage, u64, Option<u64>, u64)>,
298 pub outputs: Vec<(String, Disposition)>,
299 pub cancel: Option<CancelStatus>,
300 pub error: Option<String>,
301 pub input_error: Option<String>,
302 pub encryption: bool,
303 pub close: Close,
304 pub confirmed: bool,
305}
306impl Model {
307 pub fn busy(&self) -> bool {
308 self.running.is_some()
309 }
310 pub fn cancellation_requested(&self) -> bool {
311 self.running
312 .as_ref()
313 .is_some_and(|run| run.cancel_sequence.is_some())
314 }
315 pub fn job_id(&self) -> Option<u64> {
316 self.running.as_ref().map(|r| r.id)
317 }
318 pub fn can_extract(&self) -> bool {
319 !self.busy()
320 && self.list_id.is_some()
321 && self.archive.is_some()
322 && self.close == Close::Open
323 }
324 pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
325 let expanded = self.needs_expansion(&start);
326 self.begin_with_limits(start, factory, expanded)
327 }
328 pub fn estimated_usage(&self) -> ResourceUsage {
329 self.running
330 .as_ref()
331 .map(|run| run.estimated)
332 .unwrap_or_default()
333 }
334 fn estimate(&self, start: &Start) -> ResourceUsage {
335 let mut usage = ResourceUsage::default();
336 match start {
337 Start::Extract { selection, .. } => {
338 let selected_ids: BTreeSet<_> = match selection {
339 Selection::All => BTreeSet::new(),
340 Selection::EntryIds(ids) => ids.iter().copied().collect(),
341 };
342 let directories: BTreeSet<_> = self
343 .entries
344 .iter()
345 .filter(|e| selected_ids.contains(&e.id) && e.kind == Kind::Directory)
346 .map(|e| e.name.trim_end_matches('/'))
347 .collect();
348 let selected = |entry: &&Entry| {
349 matches!(selection, Selection::All)
350 || selected_ids.contains(&entry.id)
351 || entry
352 .name
353 .match_indices('/')
354 .any(|(n, _)| directories.contains(&entry.name[..n]))
355 };
356 let entries: Vec<_> = self.entries.iter().filter(selected).collect();
357 usage.estimated_entries = u32::try_from(entries.len()).ok();
358 usage.estimated_bytes = entries
359 .iter()
360 .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?));
361 }
362 Start::CreateZip { sources, .. } => {
363 usage.estimated_bytes = sources.iter().try_fold(0u64, |sum, (path, _)| {
364 let m = std::fs::symlink_metadata(path).ok()?;
365 if !m.is_file() {
366 return None;
367 }
368 sum.checked_add(m.len())
369 });
370 usage.estimated_entries = sources
371 .iter()
372 .all(|(path, _)| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()))
373 .then(|| u32::try_from(sources.len()).ok())
374 .flatten();
375 }
376 Start::List { .. } => {}
377 }
378 usage
379 }
380 fn needs_expansion(&self, start: &Start) -> bool {
381 let usage = self.estimate(start);
382 usage
383 .estimated_bytes
384 .is_some_and(|n| n > Limits::default().output)
385 || usage
386 .estimated_entries
387 .is_some_and(|n| n > Limits::default().entries)
388 }
389 pub fn can_retry_expanded(&self) -> bool {
390 !self.busy() && self.retry_start.is_some() && self.close == Close::Open
391 }
392 pub fn retry_expanded(&mut self, factory: &mut dyn Factory) -> bool {
393 if !self.can_retry_expanded() {
394 return false;
395 }
396 let start = self.retry_start.clone().unwrap();
397 self.begin_with_limits(start, factory, true)
398 }
399 pub fn resource_reply(&mut self, job_id: u64, challenge_id: u64, allow: bool) -> bool {
400 if self.job_id() != Some(job_id) || self.cancellation_requested() {
401 return false;
402 }
403 let Some(question) = self.resource.clone().filter(|q| q.id == challenge_id) else {
404 return false;
405 };
406 if self
407 .send(Command::ResourceReply {
408 challenge_id,
409 scope: question.scope,
410 allow,
411 })
412 .is_none()
413 {
414 return false;
415 }
416 if allow {
417 let granted = &mut self.running.as_mut().unwrap().granted;
418 granted.output |= question.scope.output;
419 granted.entries |= question.scope.entries;
420 granted.ratio |= question.scope.ratio;
421 }
422 self.resource = None;
423 true
424 }
425 fn begin_with_limits(
426 &mut self,
427 start: Start,
428 factory: &mut dyn Factory,
429 expanded: bool,
430 ) -> bool {
431 if self.busy() || self.close != Close::Open {
432 return false;
433 }
434 let selectable: BTreeSet<_> = self
435 .entries
436 .iter()
437 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
438 .map(|e| e.id)
439 .collect();
440 let validation = match &start {
441 Start::List { archive } => archive.is_absolute(),
442 Start::Extract {
443 archive,
444 destination,
445 selection,
446 gzip_output_name,
447 list_id,
448 } => {
449 archive.is_absolute()
450 && destination.is_absolute()
451 && self.archive.as_ref() == Some(archive)
452 && self.list_id.as_ref() == Some(list_id)
453 && match list_id.format {
454 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
455 _ => gzip_output_name.is_none(),
456 }
457 && match selection {
458 Selection::All => true,
459 Selection::EntryIds(ids) => {
460 !ids.is_empty()
461 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
462 && ids.iter().all(|id| selectable.contains(id))
463 }
464 }
465 }
466 Start::CreateZip {
467 sources,
468 output_file,
469 ..
470 } => {
471 !sources.is_empty()
472 && output_file.is_absolute()
473 && sources
474 .iter()
475 .all(|(p, n)| p.is_absolute() && valid_relative(n))
476 }
477 };
478 if !validation {
479 self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
480 return false;
481 }
482 let Some(id) = self.next_id.checked_add(1) else {
483 self.error = Some("작업 ID 한도에 도달했습니다".into());
484 return false;
485 };
486 let estimated = self.estimate(&start);
487 let mut connection = match factory.connect(id) {
488 Ok(c) => c,
489 Err(e) => {
490 self.error = Some(e);
491 return false;
492 }
493 };
494 let send_error = connection
495 .send(Request {
496 job_id: id,
497 sequence: 0,
498 command: if expanded {
499 Command::StartExpanded(start.clone())
500 } else {
501 Command::Start(start.clone())
502 },
503 })
504 .err();
505 let started = send_error.is_none();
506 if let Start::List { archive } = &start
507 && started
508 {
509 self.archive = Some(archive.clone());
510 self.list_id = None;
511 self.entries.clear();
512 self.selected.clear();
513 }
514 self.next_id = id;
515 self.terminal = None;
516 self.retry_start = None;
517 self.resource = None;
518 self.challenge = None;
519 self.progress = None;
520 self.outputs.clear();
521 self.cancel = None;
522 self.input_error = None;
523 self.error = send_error;
524 self.confirmed = false;
525 self.running = Some(Running {
526 id,
527 outgoing: 1,
528 incoming: 0,
529 accepted: false,
530 start_failed: !started,
531 start,
532 connection,
533 entries: Vec::new(),
534 list_end: None,
535 stdout_eof: false,
536 transport_closed: false,
537 stderr_eof: false,
538 exit: None,
539 cancel_sequence: None,
540 expanded,
541 granted: ResourceScope::default(),
542 last_challenge: 0,
543 estimated,
544 });
545 started
546 }
547 pub fn extract(
548 &mut self,
549 destination: PathBuf,
550 selected_only: bool,
551 gzip_output_name: Option<String>,
552 factory: &mut dyn Factory,
553 ) -> bool {
554 if !self.can_extract() {
555 return false;
556 }
557 self.begin(
558 Start::Extract {
559 archive: self.archive.clone().unwrap(),
560 destination,
561 selection: if selected_only {
562 Selection::EntryIds(self.selected.iter().copied().collect())
563 } else {
564 Selection::All
565 },
566 list_id: self.list_id.clone().unwrap(),
567 gzip_output_name,
568 },
569 factory,
570 )
571 }
572 pub fn password(&mut self, text: String) -> bool {
573 let Some((challenge_id, _, _)) = self.challenge else {
574 return false;
575 };
576 let secret = match Secret::new(text) {
577 Ok(s) => s,
578 Err(e) => {
579 self.input_error = Some(e.into());
580 return false;
581 }
582 };
583 if self
584 .send(Command::Password {
585 challenge_id,
586 secret,
587 })
588 .is_some()
589 {
590 self.challenge = None;
591 self.resource = None;
592 self.input_error = None;
593 true
594 } else {
595 false
596 }
597 }
598 fn send(&mut self, command: Command) -> Option<u64> {
599 let run = self.running.as_mut()?;
600 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
601 return None;
602 }
603 let seq = run.outgoing;
604 let Some(next) = seq.checked_add(1) else {
605 self.error = Some("요청 순서 한도 초과".into());
606 return None;
607 };
608 match run.connection.send(Request {
609 job_id: run.id,
610 sequence: seq,
611 command,
612 }) {
613 Ok(()) => {
614 run.outgoing = next;
615 Some(seq)
616 }
617 Err(e) => {
618 self.error = Some(e);
619 None
620 }
621 }
622 }
623 pub fn cancel(&mut self) {
624 if self
625 .running
626 .as_ref()
627 .is_some_and(|r| r.cancel_sequence.is_none())
628 {
629 if let Some(seq) = self.send(Command::Cancel) {
630 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
631 self.challenge = None;
632 self.resource = None;
633 self.input_error = None;
634 }
635 }
636 }
637 pub fn request_close(&mut self) {
638 if self.close == Close::Open {
639 self.close = if self.busy() {
640 Close::Confirm
641 } else {
642 Close::Review
643 };
644 }
645 }
646 pub fn confirm_close(&mut self) {
647 if self.close == Close::Confirm {
648 self.cancel();
649 self.close = if self.busy() {
650 Close::Waiting
651 } else {
652 Close::Review
653 };
654 }
655 }
656 pub fn keep_open(&mut self) {
657 if self.close != Close::Allowed {
658 self.close = Close::Open;
659 }
660 }
661 pub fn acknowledge_close(&mut self) {
662 if !self.busy() && self.close == Close::Review {
663 self.close = Close::Allowed;
664 }
665 }
666 pub fn poll(&mut self) {
667 for _ in 0..128 {
668 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
669 break;
670 };
671 self.receive(event);
672 }
673 let complete = self.running.as_ref().is_some_and(|r| {
674 r.exit.is_some()
675 && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
676 });
677 if complete {
678 let run = self.running.take().unwrap();
679 self.confirmed =
680 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
681 if !self.confirmed {
682 self.error.get_or_insert(
683 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
684 );
685 }
686 if self.confirmed
687 && self
688 .terminal
689 .as_ref()
690 .is_some_and(|t| t.outcome == Outcome::Completed)
691 {
692 if matches!(run.start, Start::List { .. }) {
693 if let Some((count, id)) = run
694 .list_end
695 .filter(|(n, _)| *n as usize == run.entries.len())
696 {
697 let _ = count;
698 self.entries = run.entries;
699 self.list_id = Some(id);
700 } else {
701 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
702 self.confirmed = false;
703 }
704 }
705 }
706 if self
707 .terminal
708 .as_ref()
709 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
710 {
711 self.list_id = None;
712 self.selected.clear();
713 }
714 self.retry_start = if !run.expanded
715 && run.cancel_sequence.is_none()
716 && self.confirmed
717 && self.terminal.as_ref().is_some_and(|t| {
718 t.outcome == Outcome::Failed
719 && t.error == Some(ErrorCode::Limit)
720 && t.publication == Publication::None
721 && t.created_count == 0
722 && t.retained_partial_count == 0
723 && t.cleanup == Cleanup::Complete
724 })
725 && self.outputs.iter().all(|(_, d)| *d == Disposition::Removed)
726 {
727 Some(run.start.clone())
728 } else {
729 None
730 };
731 self.challenge = None;
732 self.resource = None;
733 self.input_error = None;
734 if matches!(self.close, Close::Waiting | Close::Confirm) {
735 self.close = Close::Review;
736 }
737 }
738 }
739 fn receive(&mut self, host: HostEvent) {
740 let run = self.running.as_mut().unwrap();
741 match host {
742 HostEvent::Fault(message) => self.error = Some(message),
743 HostEvent::CleanupComplete => run.transport_closed = true,
744 HostEvent::StdoutEof => run.stdout_eof = true,
745 HostEvent::StderrEof => run.stderr_eof = true,
746 HostEvent::Exited { success } => run.exit = Some(success),
747 HostEvent::Frame {
748 job_id,
749 sequence,
750 event,
751 } => {
752 if job_id != run.id
753 || sequence != run.incoming
754 || self.terminal.is_some()
755 || run.stdout_eof
756 || sequence >= 1_000_000
757 {
758 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
759 return;
760 }
761 run.incoming += 1;
762 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
763 self.error = Some("작업 승인 응답이 없습니다".into());
764 return;
765 }
766 match event {
767 Event::Accepted { encryption } => {
768 if run.accepted {
769 self.error = Some("작업 승인 중복".into());
770 }
771 run.accepted = true;
772 self.encryption = encryption;
773 }
774 Event::Entry(entry) => {
775 if !matches!(run.start, Start::List { .. })
776 || run.list_end.is_some()
777 || entry.id as usize != run.entries.len()
778 || entry.name.len() > 4096
779 || run.entries.len()
780 >= if run.granted.entries {
781 200_000
782 } else {
783 100_000
784 }
785 {
786 self.error = Some("목록 응답이 유효하지 않습니다".into());
787 } else {
788 run.entries.push(entry);
789 }
790 }
791 Event::ListEnd {
792 entry_count,
793 list_id,
794 } => {
795 if !matches!(run.start, Start::List { .. })
796 || run.list_end.is_some()
797 || list_id.catalog_version != 1
798 {
799 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
800 } else {
801 run.list_end = Some((entry_count, list_id));
802 }
803 }
804 Event::PasswordRequired {
805 challenge_id,
806 attempt,
807 encrypt,
808 } => {
809 if run.cancel_sequence.is_some() {
810 return;
811 }
812 if self.challenge.is_some()
813 || self.resource.is_some()
814 || challenge_id <= run.last_challenge
815 {
816 self.error = Some("암호 요청이 유효하지 않습니다".into());
817 } else {
818 run.last_challenge = challenge_id;
819 self.challenge = Some((challenge_id, attempt, encrypt));
820 }
821 }
822 Event::ResourceRequired(question) => {
823 if run.cancel_sequence.is_some() {
824 return;
825 }
826 let expected = match run.start {
827 Start::List { .. } => ActionKind::List,
828 Start::Extract { .. } => ActionKind::Extract,
829 Start::CreateZip { .. } => ActionKind::CreateZip,
830 };
831 let hard = Limits {
832 input: u64::MAX,
833 output: 64 * 1024 * 1024 * 1024,
834 entries: 200_000,
835 };
836 let ceiling = if run.expanded {
837 hard
838 } else {
839 Limits::default()
840 };
841 if self.challenge.is_some()
842 || self.resource.is_some()
843 || question.id <= run.last_challenge
844 || question.action != expected
845 || !question.scope.any()
846 || question.soft_limits != Limits::default()
847 || question.ceiling != ceiling
848 || (question.scope.output && (!run.expanded || run.granted.output))
849 || (question.scope.entries && (!run.expanded || run.granted.entries))
850 || (question.scope.ratio && run.granted.ratio)
851 {
852 self.error = Some("자원 승인 요청이 유효하지 않습니다".into());
853 } else {
854 run.last_challenge = question.id;
855 self.resource = Some(question);
856 }
857 }
858 Event::Progress {
859 stage,
860 processed,
861 total,
862 completed_entries,
863 } => self.progress = Some((stage, processed, total, completed_entries)),
864 Event::Output {
865 relative_name,
866 disposition,
867 ..
868 } => {
869 if self.outputs.len()
870 < if run.granted.any() {
871 // 암묵적 상위 폴더도 출력되므로 작업자 노드 예산과 맞춤
872 262_144
873 } else {
874 100_000
875 }
876 && relative_name.len() <= 4096
877 {
878 self.outputs.push((relative_name, disposition));
879 } else {
880 self.error = Some("출력 보고 한도 초과".into());
881 }
882 }
883 Event::CancelAck {
884 request_sequence,
885 status,
886 } => {
887 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
888 self.cancel = Some(status);
889 } else {
890 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
891 }
892 }
893 Event::Terminal(t) => {
894 self.challenge = None;
895 self.terminal = Some(t);
896 }
897 }
898 }
899 }
900 }
901 pub fn status(&self) -> String {
902 if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) {
903 return error.clone();
904 }
905 if self.busy() {
906 if self.terminal.is_some() {
907 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
908 }
909 if self.resource.is_some() {
910 return "사용자 허용 대기".into();
911 }
912 if self.challenge.is_some() {
913 return "암호를 입력하세요".into();
914 }
915 if let Some(c) = self.cancel {
916 return match c {
917 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
918 "취소 요청 접수 / 최종 결과 대기"
919 }
920 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
921 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
922 }
923 .into();
924 }
925 if self
926 .running
927 .as_ref()
928 .is_some_and(|r| r.cancel_sequence.is_some())
929 {
930 return "취소 요청 전송 / 최종 결과 대기".into();
931 }
932 return "작업 중".into();
933 }
934 match self
935 .terminal
936 .as_ref()
937 .filter(|_| self.confirmed)
938 .map(|t| t.outcome)
939 {
940 Some(Outcome::Completed) => "작업 완료",
941 Some(Outcome::Cancelled) => "작업 취소됨",
942 Some(Outcome::Failed) => "작업 실패",
943 None => "압축파일을 열거나 ZIP 파일을 만드세요",
944 }
945 .into()
946 }
947}
948pub fn valid_leaf(name: &str) -> bool {
949 valid_relative(name) && !name.contains('/') && !name.contains('\\')
950}
951pub fn valid_relative(name: &str) -> bool {
952 !name.is_empty()
953 && !name.contains('\0')
954 && !name.contains(':')
955 && !name.starts_with('/')
956 && !name.starts_with('\\')
957 && name
958 .split(['/', '\\'])
959 .all(|p| !p.is_empty() && p != "." && p != "..")
960}
961
962// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
963pub fn launch_args(
964 args: Vec<std::ffi::OsString>,
965 cwd: PathBuf,
966) -> Result<(bool, Option<PathBuf>), &'static str> {
967 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
968 let paths = args
969 .into_iter()
970 .filter(|arg| arg != "--ui-fixture")
971 .collect::<Vec<_>>();
972 if paths.len() > 1 {
973 return Err("압축파일 하나를 지정하세요");
974 }
975 let path = paths
976 .into_iter()
977 .next()
978 .map(PathBuf::from)
979 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
980 Ok((fixture, path))
981}
982
983pub fn stage_label(stage: Stage) -> &'static str {
984 match stage {
985 Stage::Scan => "목록 읽는 중",
986 Stage::Read => "파일 읽는 중",
987 Stage::Decode => "압축 푸는 중",
988 Stage::Write => "파일 쓰는 중",
989 Stage::Verify => "검증 중",
990 Stage::Commit => "저장 마무리 중",
991 }
992}
993pub fn disposition_label(disposition: Disposition) -> &'static str {
994 match disposition {
995 Disposition::Created => "생성됨",
996 Disposition::PartialRetained => "일부 파일 남음",
997 Disposition::Removed => "작업 임시 파일 정리됨",
998 Disposition::CommitUncertain => "저장 여부 불확실",
999 }
1000}
1001pub fn terminal_lines(t: &Terminal) -> Vec<String> {
1002 let publication = match t.publication {
1003 Publication::None => "게시된 파일 없음",
1004 Publication::Partial => "일부 파일 게시됨",
1005 Publication::Complete => "파일 게시 완료",
1006 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
1007 };
1008 let durability = match t.durability {
1009 Durability::NotApplicable => "동기화 해당 없음",
1010 Durability::Synced => "디스크 동기화 완료",
1011 Durability::Unconfirmed => "디스크 동기화 미확인",
1012 Durability::Failed => "디스크 동기화 실패",
1013 };
1014 let cleanup = match t.cleanup {
1015 Cleanup::Complete => "작업 임시 파일 정리 완료",
1016 Cleanup::Failed => "작업 임시 파일 정리 실패",
1017 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
1018 };
1019 let mut lines = vec![
1020 publication.into(),
1021 format!(
1022 "생성 {}개 / 남은 임시 파일 {}개",
1023 t.created_count, t.retained_partial_count
1024 ),
1025 format!("{durability} / {cleanup}"),
1026 ];
1027 if let Some(error) = t.error {
1028 lines.push(
1029 match error {
1030 ErrorCode::Integrity => "압축파일이 손상됐습니다",
1031 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
1032 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
1033 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
1034 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
1035 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
1036 ErrorCode::Limit => "처리 한도를 초과했습니다",
1037 ErrorCode::Io => {
1038 "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
1039 }
1040 ErrorCode::DiskFull => {
1041 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
1042 }
1043 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
1044 ErrorCode::Internal => "작업자 처리 오류입니다",
1045 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
1046 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
1047 }
1048 .into(),
1049 );
1050 }
1051 lines
1052}