team-ljyzipelo

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