team-ljyzipelo

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