team-ljyzipelo

공개
850줄29 KB
1use crate::archive_ui as ui;
2use std::{
3 cell::RefCell,
4 io::{self, Read, Write},
5 path::PathBuf,
6 process::{Command, Stdio},
7 rc::Rc,
8 sync::{
9 Arc, Mutex,
10 atomic::{AtomicBool, Ordering},
11 mpsc::{self, Receiver, SyncSender},
12 },
13 thread::{self, JoinHandle},
14 time::{Duration, Instant},
15};
16use worker_protocol::{protocol as wire, wire as codec};
17
18macro_rules! convert_enum {
19 ($name:ident, $from:ty, $to:ty, $($variant:ident),+) => {
20 fn $name(value: $from) -> $to {
21 match value { $(<$from>::$variant => <$to>::$variant),+ }
22 }
23 };
24}
25convert_enum!(
26 format_to_wire,
27 ui::Format,
28 wire::Format,
29 Zip,
30 Tar,
31 Gzip,
32 TarGzip,
33 SevenZip
34);
35convert_enum!(
36 format_to_ui,
37 wire::Format,
38 ui::Format,
39 Zip,
40 Tar,
41 Gzip,
42 TarGzip,
43 SevenZip
44);
45convert_enum!(
46 kind_to_ui,
47 wire::EntryKind,
48 ui::Kind,
49 File,
50 Directory,
51 Link,
52 Other
53);
54convert_enum!(
55 stage_to_ui,
56 wire::Stage,
57 ui::Stage,
58 Scan,
59 Read,
60 Decode,
61 Write,
62 Verify,
63 Commit
64);
65convert_enum!(
66 disposition_to_ui,
67 wire::Disposition,
68 ui::Disposition,
69 Created,
70 PartialRetained,
71 Removed,
72 CommitUncertain
73);
74convert_enum!(
75 outcome_to_ui,
76 wire::Outcome,
77 ui::Outcome,
78 Completed,
79 Failed,
80 Cancelled
81);
82convert_enum!(
83 publication_to_ui,
84 wire::Publication,
85 ui::Publication,
86 None,
87 Partial,
88 Complete,
89 Uncertain
90);
91convert_enum!(
92 durability_to_ui,
93 wire::Durability,
94 ui::Durability,
95 NotApplicable,
96 Synced,
97 Unconfirmed,
98 Failed
99);
100convert_enum!(
101 cleanup_to_ui,
102 wire::Cleanup,
103 ui::Cleanup,
104 Complete,
105 Failed,
106 Unconfirmed
107);
108convert_enum!(
109 cancel_to_ui,
110 wire::CancelStatus,
111 ui::CancelStatus,
112 Requested,
113 AlreadyRequested,
114 TooLate,
115 Finished
116);
117convert_enum!(
118 conflict_to_wire,
119 ui::ConflictChoice,
120 wire::ConflictChoice,
121 Overwrite,
122 Skip,
123 Rename
124);
125convert_enum!(
126 conflict_to_ui,
127 wire::ConflictChoice,
128 ui::ConflictChoice,
129 Overwrite,
130 Skip,
131 Rename
132);
133fn list_to_wire(id: ui::ListId) -> wire::ListId {
134 wire::ListId {
135 catalog_version: id.catalog_version,
136 format: format_to_wire(id.format),
137 source_object: match id.source_object {
138 ui::SourceObject::Unix { device, inode } => wire::SourceObject::Unix { device, inode },
139 ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows {
140 volume_serial: volume,
141 file_id,
142 },
143 },
144 archive_bytes: id.archive_bytes,
145 archive_sha256: id.archive_sha256,
146 }
147}
148fn list_to_ui(id: wire::ListId) -> ui::ListId {
149 ui::ListId {
150 catalog_version: id.catalog_version,
151 format: format_to_ui(id.format),
152 source_object: match id.source_object {
153 wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode },
154 wire::SourceObject::Windows {
155 volume_serial,
156 file_id,
157 } => ui::SourceObject::Windows {
158 volume: volume_serial,
159 file_id,
160 },
161 },
162 archive_bytes: id.archive_bytes,
163 archive_sha256: id.archive_sha256,
164 }
165}
166fn start_to_wire(start: ui::Start) -> wire::Start {
167 let action = match start {
168 ui::Start::List { archive } => wire::Action::List {
169 archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)),
170 },
171 ui::Start::Extract {
172 archive,
173 destination,
174 selection,
175 list_id,
176 gzip_output_name,
177 } => wire::Action::Extract {
178 archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)),
179 destination: wire::NativePath::from_path(&crate::archive_path::worker_path(
180 &destination,
181 )),
182 selection: match selection {
183 ui::Selection::All => wire::Selection::All,
184 ui::Selection::EntryIds(ids) => wire::Selection::EntryIds(ids),
185 },
186 list_id: Some(list_to_wire(list_id)),
187 gzip_output_name,
188 },
189 ui::Start::Preview {
190 archive,
191 entry_id,
192 list_id,
193 } => wire::Action::Preview {
194 archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)),
195 entry_id,
196 list_id: list_to_wire(list_id),
197 },
198 ui::Start::CreateZip {
199 sources,
200 output_file,
201 method,
202 aes256,
203 } => wire::Action::CreateZip {
204 sources: sources
205 .into_iter()
206 .map(|(path, archive_name)| wire::Source {
207 path: wire::NativePath::from_path(&crate::archive_path::worker_path(&path)),
208 archive_name,
209 })
210 .collect(),
211 output_file: wire::NativePath::from_path(&crate::archive_path::worker_path(
212 &output_file,
213 )),
214 method: match method {
215 ui::Method::Store => wire::Method::Store,
216 ui::Method::Deflate => wire::Method::Deflate,
217 },
218 encryption: if aes256 {
219 wire::Encryption::Aes256
220 } else {
221 wire::Encryption::None
222 },
223 },
224 };
225 wire::Start {
226 action,
227 limits: wire::Limits::default(),
228 }
229}
230fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> {
231 Some(match error {
232 wire::ErrorCode::None => return None,
233 wire::ErrorCode::Integrity => ui::ErrorCode::Integrity,
234 wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat,
235 wire::ErrorCode::UnsupportedFeature => ui::ErrorCode::UnsupportedFeature,
236 wire::ErrorCode::WrongPassword => ui::ErrorCode::WrongPassword,
237 wire::ErrorCode::UnsafePath => ui::ErrorCode::UnsafePath,
238 wire::ErrorCode::Conflict => ui::ErrorCode::Conflict,
239 wire::ErrorCode::Limit => ui::ErrorCode::Limit,
240 wire::ErrorCode::Io => ui::ErrorCode::Io,
241 wire::ErrorCode::DiskFull => ui::ErrorCode::DiskFull,
242 wire::ErrorCode::Protocol => ui::ErrorCode::Protocol,
243 wire::ErrorCode::Internal => ui::ErrorCode::Internal,
244 wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged,
245 wire::ErrorCode::InvalidRequest => ui::ErrorCode::InvalidRequest,
246 })
247}
248fn event_to_ui(
249 message: wire::Message,
250 expected: Option<wire::ActionKind>,
251) -> Result<ui::Event, ()> {
252 Ok(match message {
253 wire::Message::Accepted { action, encryption } if expected == Some(action) => {
254 ui::Event::Accepted { encryption }
255 }
256 wire::Message::ResourceRequired {
257 challenge_id,
258 action,
259 scope,
260 usage,
261 soft_limits,
262 ceiling,
263 } if expected == Some(action) => ui::Event::ResourceRequired(ui::ResourceChallenge {
264 id: challenge_id,
265 action,
266 scope,
267 usage,
268 soft_limits,
269 ceiling,
270 }),
271 wire::Message::PreviewBegin(info) if expected == Some(wire::ActionKind::Preview) => {
272 ui::Event::PreviewBegin(info)
273 }
274 wire::Message::PreviewChunk {
275 entry_id,
276 offset,
277 data,
278 } if expected == Some(wire::ActionKind::Preview) => ui::Event::PreviewChunk {
279 entry_id,
280 offset,
281 data,
282 },
283 wire::Message::PreviewEnd {
284 entry_id,
285 total_bytes,
286 sha256,
287 } if expected == Some(wire::ActionKind::Preview) => ui::Event::PreviewEnd {
288 entry_id,
289 total_bytes,
290 sha256,
291 },
292 wire::Message::Entry(entry) => ui::Event::Entry(ui::Entry {
293 id: entry.entry_id,
294 name: entry.name,
295 kind: kind_to_ui(entry.kind),
296 bytes: Some(entry.size),
297 packed: Some(entry.compressed_size),
298 encrypted: entry.encrypted,
299 }),
300 wire::Message::ListEnd {
301 entry_count,
302 list_id,
303 } => ui::Event::ListEnd {
304 entry_count,
305 list_id: list_to_ui(list_id),
306 },
307 wire::Message::PasswordRequired {
308 challenge_id,
309 attempt,
310 purpose,
311 } => ui::Event::PasswordRequired {
312 challenge_id,
313 attempt,
314 encrypt: purpose == wire::PasswordPurpose::Encrypt,
315 },
316 wire::Message::ConflictRequired {
317 challenge_id,
318 entry_id,
319 relative_name,
320 incoming_size,
321 existing_size,
322 } if expected == Some(wire::ActionKind::Extract) => {
323 ui::Event::ConflictRequired(ui::Conflict {
324 challenge_id,
325 entry_id,
326 relative_name,
327 incoming_size,
328 existing_size,
329 })
330 }
331 wire::Message::ConflictResolved {
332 entry_id,
333 relative_name,
334 choice,
335 } if expected == Some(wire::ActionKind::Extract) => {
336 ui::Event::ConflictResolved(ui::Resolution {
337 entry_id,
338 relative_name,
339 choice: conflict_to_ui(choice),
340 })
341 }
342 wire::Message::Progress {
343 stage,
344 processed_bytes,
345 total_bytes,
346 completed_entries,
347 } => ui::Event::Progress {
348 stage: stage_to_ui(stage),
349 processed: processed_bytes,
350 total: total_bytes,
351 completed_entries: completed_entries.into(),
352 },
353 wire::Message::Output {
354 entry_id,
355 relative_name,
356 disposition,
357 } => ui::Event::Output {
358 entry_id,
359 relative_name,
360 disposition: disposition_to_ui(disposition),
361 },
362 wire::Message::CancelAck {
363 request_sequence,
364 status,
365 } => ui::Event::CancelAck {
366 request_sequence,
367 status: cancel_to_ui(status),
368 },
369 wire::Message::Terminal(terminal) => ui::Event::Terminal(ui::Terminal {
370 outcome: outcome_to_ui(terminal.outcome),
371 error: error_to_ui(terminal.error),
372 publication: publication_to_ui(terminal.publication),
373 created_count: terminal.created_count,
374 retained_partial_count: terminal.retained_partial_count,
375 durability: durability_to_ui(terminal.durability),
376 cleanup: cleanup_to_ui(terminal.cleanup),
377 }),
378 _ => return Err(()),
379 })
380}
381
382// 실제 파이프 쓰기는 백그라운드에서 수행하고 UI에서는 한 프레임만 직렬화함.
383#[derive(Clone, Default)]
384struct FrameBuffer(Rc<RefCell<Vec<u8>>>);
385impl Write for FrameBuffer {
386 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
387 let mut buffer = self.0.borrow_mut();
388 if buffer.len().saturating_add(bytes.len()) > codec::MAX_BODY + 32 {
389 return Err(io::Error::other("요청 프레임 한도 초과"));
390 }
391 buffer.extend_from_slice(bytes);
392 Ok(bytes.len())
393 }
394 fn flush(&mut self) -> io::Result<()> {
395 Ok(())
396 }
397}
398struct Frame(Vec<u8>, bool);
399impl Drop for Frame {
400 fn drop(&mut self) {
401 self.0.fill(0);
402 }
403}
404fn notify(events: &SyncSender<ui::HostEvent>, event: ui::HostEvent) -> bool {
405 events.send(event).is_ok()
406}
407fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) {
408 stop.store(true, Ordering::Release);
409 notify(events, ui::HostEvent::Fault(message.into()));
410}
411
412#[derive(Default)]
413struct ResourceDeadline {
414 pending: Option<(u64, wire::ResourceScope)>,
415 approved: bool,
416}
417
418pub struct ProcessFactory {
419 worker: PathBuf,
420}
421impl ProcessFactory {
422 pub fn new(worker: PathBuf) -> Self {
423 Self { worker }
424 }
425 pub fn sibling() -> Result<Self, String> {
426 let executable =
427 std::env::current_exe().map_err(|_| "앱 실행 위치를 확인하지 못했습니다")?;
428 let parent = executable.parent().ok_or("앱 실행 폴더가 없습니다")?;
429 Ok(Self::new(parent.join(if cfg!(windows) {
430 "zipelo-archive-worker.exe"
431 } else {
432 "zipelo-archive-worker"
433 })))
434 }
435}
436impl ui::Factory for ProcessFactory {
437 fn connect(&mut self, job_id: u64) -> Result<Box<dyn ui::Connection>, String> {
438 if !self.worker.is_absolute() || job_id == 0 {
439 return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into());
440 }
441 let (send, requests) = mpsc::sync_channel::<Frame>(8);
442 let (events, receive) = mpsc::sync_channel(64);
443 let (ready, started) = mpsc::sync_channel(1);
444 let stop = Arc::new(AtomicBool::new(false));
445 let done = Arc::new(AtomicBool::new(false));
446 let expected = Arc::new(Mutex::new(None));
447 let resources = Arc::new(Mutex::new(ResourceDeadline::default()));
448 let worker = self.worker.clone();
449 let worker_stop = stop.clone();
450 let worker_done = done.clone();
451 let worker_expected = expected.clone();
452 let worker_resources = resources.clone();
453 let supervisor = thread::Builder::new()
454 .name("zipelo-worker-owner".into())
455 .spawn(move || {
456 let mut command = Command::new(worker);
457 command
458 .stdin(Stdio::piped())
459 .stdout(Stdio::piped())
460 .stderr(Stdio::piped());
461 #[cfg(windows)]
462 {
463 use std::os::windows::process::CommandExt;
464 command.creation_flags(0x08000000);
465 }
466 let child = match command.spawn() {
467 Ok(child) => child,
468 Err(_) => {
469 let _ = ready.send(Err(
470 "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요"
471 .to_string(),
472 ));
473 return;
474 }
475 };
476 if ready.send(Ok(())).is_err() {
477 let mut child = child;
478 let _ = child.kill();
479 let _ = child.wait();
480 return;
481 }
482 supervise(
483 child,
484 job_id,
485 requests,
486 events,
487 worker_stop,
488 worker_done,
489 worker_expected,
490 worker_resources,
491 );
492 })
493 .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?;
494 match started.recv() {
495 Ok(Ok(())) => {
496 let buffer = FrameBuffer::default();
497 Ok(Box::new(ProcessConnection {
498 job_id,
499 next: 0,
500 writer: codec::Writer::new(buffer.clone(), job_id),
501 buffer,
502 send: Some(send),
503 receive: Some(receive),
504 stop,
505 supervisor: Some(supervisor),
506 expected,
507 resources,
508 done,
509 disconnected: false,
510 reaped: false,
511 }))
512 }
513 result => {
514 stop.store(true, Ordering::Release);
515 drop(send);
516 drop(receive);
517 let _ = supervisor.join();
518 Err(result
519 .ok()
520 .and_then(Result::err)
521 .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into()))
522 }
523 }
524 }
525}
526struct ProcessConnection {
527 job_id: u64,
528 next: u64,
529 writer: codec::Writer<FrameBuffer>,
530 buffer: FrameBuffer,
531 send: Option<SyncSender<Frame>>,
532 receive: Option<Receiver<ui::HostEvent>>,
533 stop: Arc<AtomicBool>,
534 supervisor: Option<JoinHandle<()>>,
535 expected: Arc<Mutex<Option<wire::ActionKind>>>,
536 resources: Arc<Mutex<ResourceDeadline>>,
537 done: Arc<AtomicBool>,
538 disconnected: bool,
539 reaped: bool,
540}
541impl ui::Connection for ProcessConnection {
542 fn send(&mut self, request: ui::Request) -> Result<(), String> {
543 if self.stop.load(Ordering::Acquire)
544 || request.job_id != self.job_id
545 || request.sequence != self.next
546 || self.next >= codec::MAX_FRAMES
547 {
548 self.stop.store(true, Ordering::Release);
549 return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into());
550 }
551 let is_cancel = matches!(request.command, ui::Command::Cancel);
552 let expanded = matches!(&request.command, ui::Command::StartExpanded(_));
553 let message = match request.command {
554 ui::Command::Start(start) | ui::Command::StartExpanded(start) => {
555 let start = start_to_wire(start);
556 *self.expected.lock().map_err(|_| {
557 self.stop.store(true, Ordering::Release);
558 "작업자 요청 상태 오류"
559 })? = Some(start.action.kind());
560 let ceiling = if expanded {
561 wire::Limits {
562 input: u64::MAX,
563 output: 64 * 1024 * 1024 * 1024,
564 entries: 200_000,
565 }
566 } else {
567 wire::Limits::default()
568 };
569 let interactive = matches!(
570 start.action.kind(),
571 wire::ActionKind::Extract | wire::ActionKind::Preview
572 );
573 wire::Message::StartGuarded(wire::GuardedStart {
574 start,
575 ceiling,
576 interactive,
577 })
578 }
579 ui::Command::ResourceReply {
580 challenge_id,
581 scope,
582 allow,
583 } => wire::Message::ResourceReply {
584 challenge_id,
585 scope,
586 allow,
587 },
588 ui::Command::ConflictReply {
589 challenge_id,
590 choice,
591 apply_to_remaining,
592 } => wire::Message::ConflictReply {
593 challenge_id,
594 choice: conflict_to_wire(choice),
595 apply_to_remaining,
596 },
597 ui::Command::Cancel => wire::Message::Cancel,
598 ui::Command::Password {
599 challenge_id,
600 secret,
601 } => wire::Message::Password {
602 challenge_id,
603 secret: wire::Secret(secret.as_bytes().to_vec()),
604 },
605 };
606 if self.writer.send(&message).is_err() {
607 self.buffer.0.borrow_mut().fill(0);
608 self.buffer.0.borrow_mut().clear();
609 self.stop.store(true, Ordering::Release);
610 return Err("작업자 요청을 직렬화하지 못했습니다".into());
611 }
612 let mut resources = self.resources.lock().map_err(|_| {
613 self.stop.store(true, Ordering::Release);
614 "작업자 승인 상태 오류"
615 })?;
616 let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel);
617 if self.send.as_ref().unwrap().try_send(bytes).is_err() {
618 if is_cancel && self.done.load(Ordering::Acquire) {
619 self.next += 1;
620 return Ok(());
621 }
622 self.stop.store(true, Ordering::Release);
623 return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
624 }
625 if let wire::Message::ResourceReply {
626 challenge_id,
627 scope,
628 allow,
629 } = message
630 && resources.pending == Some((challenge_id, scope))
631 {
632 resources.approved |= allow;
633 resources.pending = None;
634 }
635 self.next += 1;
636 Ok(())
637 }
638 fn poll(&mut self) -> Option<ui::HostEvent> {
639 match self.receive.as_ref()?.try_recv() {
640 Ok(event) => {
641 if matches!(event, ui::HostEvent::Exited { .. }) {
642 self.reaped = true;
643 }
644 Some(event)
645 }
646 Err(mpsc::TryRecvError::Empty) => None,
647 Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => {
648 self.disconnected = true;
649 Some(ui::HostEvent::Fault(
650 "작업자 통신 스레드가 종료됐습니다".into(),
651 ))
652 }
653 Err(_) => None,
654 }
655 }
656}
657impl Drop for ProcessConnection {
658 fn drop(&mut self) {
659 self.stop.store(true, Ordering::Release);
660 self.send.take();
661 self.receive.take();
662 if let Some(supervisor) = self.supervisor.take() {
663 let _ = supervisor.join();
664 }
665 }
666}
667
668fn supervise(
669 mut child: std::process::Child,
670 job_id: u64,
671 requests: Receiver<Frame>,
672 events: SyncSender<ui::HostEvent>,
673 stop: Arc<AtomicBool>,
674 done: Arc<AtomicBool>,
675 expected: Arc<Mutex<Option<wire::ActionKind>>>,
676 resources: Arc<Mutex<ResourceDeadline>>,
677) {
678 let mut input = child.stdin.take().unwrap();
679 let mut output = child.stdout.take().unwrap();
680 let mut errors = child.stderr.take().unwrap();
681 let mut threads = Vec::new();
682 let cancel_write_failed = Arc::new(AtomicBool::new(false));
683 let terminal_received = Arc::new(AtomicBool::new(false));
684 let failed_cancel = cancel_write_failed.clone();
685 let tx = events.clone();
686 let abort = stop.clone();
687 let finished = done.clone();
688 threads.push(
689 thread::Builder::new()
690 .name("zipelo-worker-input".into())
691 .spawn(move || {
692 while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) {
693 match requests.recv_timeout(Duration::from_millis(10)) {
694 Ok(frame) => {
695 if input
696 .write_all(&frame.0)
697 .and_then(|_| input.flush())
698 .is_err()
699 {
700 if frame.1 {
701 // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함.
702 failed_cancel.store(true, Ordering::Release);
703 } else {
704 fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다");
705 }
706 break;
707 }
708 }
709 Err(mpsc::RecvTimeoutError::Timeout) => {}
710 Err(_) => break,
711 }
712 }
713 }),
714 );
715 let tx = events.clone();
716 let abort = stop.clone();
717 let received_terminal = terminal_received.clone();
718 let pending_resource = resources.clone();
719 threads.push(
720 thread::Builder::new()
721 .name("zipelo-worker-output".into())
722 .spawn(move || {
723 let eof;
724 {
725 let mut reader = codec::Reader::new(&mut output);
726 eof = loop {
727 match reader.read() {
728 Ok(Some((job, sequence, message))) => {
729 let action = expected.lock().ok().and_then(|value| *value);
730 let event = event_to_ui(message, action);
731 if job != job_id || event.is_err() {
732 fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
733 break false;
734 }
735 if let Ok(ui::Event::ResourceRequired(question)) = &event {
736 if let Ok(mut state) = pending_resource.lock() {
737 state.pending = Some((question.id, question.scope));
738 } else {
739 fault(&tx, &abort, "작업자 승인 상태 오류");
740 break false;
741 }
742 }
743 if matches!(event, Ok(ui::Event::Terminal(_))) {
744 received_terminal.store(true, Ordering::Release);
745 }
746 if !notify(
747 &tx,
748 ui::HostEvent::Frame {
749 job_id: job,
750 sequence,
751 event: event.unwrap(),
752 },
753 ) {
754 return;
755 }
756 }
757 Ok(None) => break true,
758 Err(_) => {
759 fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다");
760 break false;
761 }
762 }
763 };
764 }
765 if eof || io::copy(&mut output, &mut io::sink()).is_ok() {
766 notify(&tx, ui::HostEvent::StdoutEof);
767 }
768 }),
769 );
770 let tx = events.clone();
771 let abort = stop.clone();
772 threads.push(
773 thread::Builder::new()
774 .name("zipelo-worker-errors".into())
775 .spawn(move || {
776 let mut bytes = [0u8; 4096];
777 loop {
778 match errors.read(&mut bytes) {
779 Ok(0) => {
780 notify(&tx, ui::HostEvent::StderrEof);
781 break;
782 }
783 Ok(_) => {}
784 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
785 Err(_) => {
786 fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다");
787 break;
788 }
789 }
790 }
791 }),
792 );
793 let mut handles = Vec::new();
794 for result in threads {
795 match result {
796 Ok(handle) => handles.push(handle),
797 Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"),
798 }
799 }
800 let started = Instant::now();
801 let status = loop {
802 // 승인 뒤 실제 진행과 질문 대기 시간은 작업자의 60초 정체 감시로 판단함.
803 // 응답 프레임 간격을 실제 파일 처리 진행으로 간주하지 않음.
804 let approved = resources
805 .lock()
806 .map(|state| state.approved)
807 .unwrap_or(false);
808 if !approved && started.elapsed() >= Duration::from_secs(310) {
809 fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
810 }
811 if stop.load(Ordering::Acquire) {
812 let _ = child.kill();
813 }
814 match child.try_wait() {
815 Ok(Some(status)) => break Some(status),
816 Ok(None) => thread::sleep(Duration::from_millis(10)),
817 Err(_) => {
818 fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다");
819 let _ = child.kill();
820 break child.wait().ok();
821 }
822 }
823 };
824 done.store(true, Ordering::Release);
825 for handle in handles {
826 if handle.join().is_err() {
827 fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다");
828 }
829 }
830 if cancel_write_failed.load(Ordering::Acquire)
831 && !(terminal_received.load(Ordering::Acquire)
832 && status.as_ref().is_some_and(|status| status.success()))
833 {
834 fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다");
835 }
836 if let Some(status) = status {
837 // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함.
838 notify(&events, ui::HostEvent::CleanupComplete);
839 notify(
840 &events,
841 ui::HostEvent::Exited {
842 success: status.success(),
843 },
844 );
845 }
846}
847
848#[cfg(test)]
849#[path = "../../../tests/rust-app-ui/conflict_codec.rs"]
850mod conflict_codec_tests;