team-ljyzipelo

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