team-ljyzipelo

공개
908줄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 crate::log_error!("작업자 경로 또는 작업 ID가 올바르지 않음: job={job_id}");
492 return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into());
493 }
494 crate::log_debug!("작업 {job_id} 작업자 실행: {}", self.worker.display());
495 let (send, requests) = mpsc::sync_channel::<Frame>(8);
496 let (events, receive) = mpsc::sync_channel(64);
497 let (ready, started) = mpsc::sync_channel(1);
498 let stop = Arc::new(AtomicBool::new(false));
499 let done = Arc::new(AtomicBool::new(false));
500 let expected = Arc::new(Mutex::new(None));
501 let resources = Arc::new(Mutex::new(ResourceDeadline::default()));
502 let worker = self.worker.clone();
503 let worker_stop = stop.clone();
504 let worker_done = done.clone();
505 let worker_expected = expected.clone();
506 let worker_resources = resources.clone();
507 let supervisor = thread::Builder::new()
508 .name("zipelo-worker-owner".into())
509 .spawn(move || {
510 let mut command = Command::new(worker);
511 command
512 .stdin(Stdio::piped())
513 .stdout(Stdio::piped())
514 .stderr(Stdio::piped());
515 #[cfg(windows)]
516 {
517 use std::os::windows::process::CommandExt;
518 command.creation_flags(0x08000000);
519 }
520 let child = match command.spawn() {
521 Ok(child) => child,
522 Err(error) => {
523 crate::log_error!("작업자를 실행하지 못함: {error}");
524 let _ = ready.send(Err(
525 "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요"
526 .to_string(),
527 ));
528 return;
529 }
530 };
531 if ready.send(Ok(())).is_err() {
532 let mut child = child;
533 let _ = child.kill();
534 let _ = child.wait();
535 return;
536 }
537 supervise(
538 child,
539 job_id,
540 requests,
541 events,
542 worker_stop,
543 worker_done,
544 worker_expected,
545 worker_resources,
546 );
547 })
548 .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?;
549 match started.recv() {
550 Ok(Ok(())) => {
551 let buffer = FrameBuffer::default();
552 Ok(Box::new(ProcessConnection {
553 job_id,
554 next: 0,
555 writer: codec::Writer::new(buffer.clone(), job_id),
556 buffer,
557 send: Some(send),
558 receive: Some(receive),
559 stop,
560 supervisor: Some(supervisor),
561 expected,
562 resources,
563 done,
564 disconnected: false,
565 reaped: false,
566 }))
567 }
568 result => {
569 stop.store(true, Ordering::Release);
570 drop(send);
571 drop(receive);
572 let _ = supervisor.join();
573 Err(result
574 .ok()
575 .and_then(Result::err)
576 .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into()))
577 }
578 }
579 }
580}
581struct ProcessConnection {
582 job_id: u64,
583 next: u64,
584 writer: codec::Writer<FrameBuffer>,
585 buffer: FrameBuffer,
586 send: Option<SyncSender<Frame>>,
587 receive: Option<Receiver<ui::HostEvent>>,
588 stop: Arc<AtomicBool>,
589 supervisor: Option<JoinHandle<()>>,
590 expected: Arc<Mutex<Option<wire::ActionKind>>>,
591 resources: Arc<Mutex<ResourceDeadline>>,
592 done: Arc<AtomicBool>,
593 disconnected: bool,
594 reaped: bool,
595}
596impl ui::Connection for ProcessConnection {
597 fn send(&mut self, request: ui::Request) -> Result<(), String> {
598 if self.stop.load(Ordering::Acquire)
599 || request.job_id != self.job_id
600 || request.sequence != self.next
601 || self.next >= codec::MAX_FRAMES
602 {
603 self.stop.store(true, Ordering::Release);
604 return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into());
605 }
606 let is_cancel = matches!(request.command, ui::Command::Cancel);
607 let expanded = matches!(&request.command, ui::Command::StartExpanded(_));
608 let message = match request.command {
609 ui::Command::Start(start) | ui::Command::StartExpanded(start) => {
610 let start = start_to_wire(start);
611 *self.expected.lock().map_err(|_| {
612 self.stop.store(true, Ordering::Release);
613 "작업자 요청 상태 오류"
614 })? = Some(start.action.kind());
615 let ceiling = if expanded {
616 wire::Limits::expanded(start.action.kind())
617 } else {
618 wire::Limits::default()
619 };
620 let interactive = matches!(
621 start.action.kind(),
622 wire::ActionKind::Extract | wire::ActionKind::Preview
623 );
624 wire::Message::StartGuarded(wire::GuardedStart {
625 start,
626 ceiling,
627 interactive,
628 })
629 }
630 ui::Command::ResourceReply {
631 challenge_id,
632 scope,
633 allow,
634 } => wire::Message::ResourceReply {
635 challenge_id,
636 scope,
637 allow,
638 },
639 ui::Command::ConflictReply {
640 challenge_id,
641 choice,
642 apply_to_remaining,
643 } => wire::Message::ConflictReply {
644 challenge_id,
645 choice: conflict_to_wire(choice),
646 apply_to_remaining,
647 },
648 ui::Command::Cancel => wire::Message::Cancel,
649 ui::Command::Password {
650 challenge_id,
651 secret,
652 } => wire::Message::Password {
653 challenge_id,
654 secret: wire::Secret(secret.as_bytes().to_vec()),
655 },
656 };
657 if self.writer.send(&message).is_err() {
658 self.buffer.0.borrow_mut().fill(0);
659 self.buffer.0.borrow_mut().clear();
660 self.stop.store(true, Ordering::Release);
661 return Err("작업자 요청을 직렬화하지 못했습니다".into());
662 }
663 let mut resources = self.resources.lock().map_err(|_| {
664 self.stop.store(true, Ordering::Release);
665 "작업자 승인 상태 오류"
666 })?;
667 let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel);
668 if self.send.as_ref().unwrap().try_send(bytes).is_err() {
669 if is_cancel && self.done.load(Ordering::Acquire) {
670 self.next += 1;
671 return Ok(());
672 }
673 self.stop.store(true, Ordering::Release);
674 return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
675 }
676 if let wire::Message::ResourceReply {
677 challenge_id,
678 scope,
679 allow,
680 } = message
681 && resources.pending == Some((challenge_id, scope))
682 {
683 resources.approved |= allow;
684 resources.pending = None;
685 }
686 self.next += 1;
687 Ok(())
688 }
689 fn poll(&mut self) -> Option<ui::HostEvent> {
690 match self.receive.as_ref()?.try_recv() {
691 Ok(event) => {
692 if matches!(event, ui::HostEvent::Exited { .. }) {
693 self.reaped = true;
694 }
695 Some(event)
696 }
697 Err(mpsc::TryRecvError::Empty) => None,
698 Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => {
699 self.disconnected = true;
700 Some(ui::HostEvent::Fault(
701 "작업자 통신 스레드가 종료됐습니다".into(),
702 ))
703 }
704 Err(_) => None,
705 }
706 }
707}
708impl Drop for ProcessConnection {
709 fn drop(&mut self) {
710 self.stop.store(true, Ordering::Release);
711 self.send.take();
712 self.receive.take();
713 if let Some(supervisor) = self.supervisor.take() {
714 let _ = supervisor.join();
715 }
716 }
717}
718
719fn supervise(
720 mut child: std::process::Child,
721 job_id: u64,
722 requests: Receiver<Frame>,
723 events: SyncSender<ui::HostEvent>,
724 stop: Arc<AtomicBool>,
725 done: Arc<AtomicBool>,
726 expected: Arc<Mutex<Option<wire::ActionKind>>>,
727 resources: Arc<Mutex<ResourceDeadline>>,
728) {
729 let mut input = child.stdin.take().unwrap();
730 let mut output = child.stdout.take().unwrap();
731 let mut errors = child.stderr.take().unwrap();
732 let mut threads = Vec::new();
733 let cancel_write_failed = Arc::new(AtomicBool::new(false));
734 let terminal_received = Arc::new(AtomicBool::new(false));
735 let failed_cancel = cancel_write_failed.clone();
736 let tx = events.clone();
737 let abort = stop.clone();
738 let finished = done.clone();
739 threads.push(
740 thread::Builder::new()
741 .name("zipelo-worker-input".into())
742 .spawn(move || {
743 while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) {
744 match requests.recv_timeout(Duration::from_millis(10)) {
745 Ok(frame) => {
746 if input
747 .write_all(&frame.0)
748 .and_then(|_| input.flush())
749 .is_err()
750 {
751 if frame.1 {
752 // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함.
753 failed_cancel.store(true, Ordering::Release);
754 } else {
755 fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다");
756 }
757 break;
758 }
759 }
760 Err(mpsc::RecvTimeoutError::Timeout) => {}
761 Err(_) => break,
762 }
763 }
764 }),
765 );
766 let tx = events.clone();
767 let abort = stop.clone();
768 let received_terminal = terminal_received.clone();
769 let pending_resource = resources.clone();
770 threads.push(
771 thread::Builder::new()
772 .name("zipelo-worker-output".into())
773 .spawn(move || {
774 let eof;
775 {
776 let mut reader = codec::Reader::new(&mut output);
777 eof = loop {
778 match reader.read() {
779 Ok(Some((job, sequence, message))) => {
780 let action = expected.lock().ok().and_then(|value| *value);
781 let event = event_to_ui(message, action);
782 if job != job_id || event.is_err() {
783 fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
784 break false;
785 }
786 if let Ok(ui::Event::ResourceRequired(question)) = &event {
787 if let Ok(mut state) = pending_resource.lock() {
788 state.pending = Some((question.id, question.scope));
789 } else {
790 fault(&tx, &abort, "작업자 승인 상태 오류");
791 break false;
792 }
793 }
794 if matches!(event, Ok(ui::Event::Terminal(_))) {
795 received_terminal.store(true, Ordering::Release);
796 }
797 if !notify(
798 &tx,
799 ui::HostEvent::Frame {
800 job_id: job,
801 sequence,
802 event: event.unwrap(),
803 },
804 ) {
805 return;
806 }
807 }
808 Ok(None) => break true,
809 Err(_) => {
810 fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다");
811 break false;
812 }
813 }
814 };
815 }
816 if eof || io::copy(&mut output, &mut io::sink()).is_ok() {
817 notify(&tx, ui::HostEvent::StdoutEof);
818 }
819 }),
820 );
821 let tx = events.clone();
822 let abort = stop.clone();
823 threads.push(
824 thread::Builder::new()
825 .name("zipelo-worker-errors".into())
826 .spawn(move || {
827 let mut bytes = [0u8; 4096];
828 loop {
829 match errors.read(&mut bytes) {
830 Ok(0) => {
831 notify(&tx, ui::HostEvent::StderrEof);
832 break;
833 }
834 Ok(count) => {
835 // 작업자가 표준 오류에 남긴 내용은 디버그 로그로만 옮김.
836 crate::log_debug!(
837 "작업자 표준 오류: {}",
838 String::from_utf8_lossy(&bytes[..count]).trim_end()
839 );
840 }
841 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
842 Err(error) => {
843 crate::log_error!("작업자 오류 파이프 읽기 실패: {error}");
844 fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다");
845 break;
846 }
847 }
848 }
849 }),
850 );
851 let mut handles = Vec::new();
852 for result in threads {
853 match result {
854 Ok(handle) => handles.push(handle),
855 Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"),
856 }
857 }
858 let started = Instant::now();
859 let status = loop {
860 // 승인 뒤 실제 진행과 질문 대기 시간은 작업자의 60초 정체 감시로 판단함.
861 // 응답 프레임 간격을 실제 파일 처리 진행으로 간주하지 않음.
862 let approved = resources
863 .lock()
864 .map(|state| state.approved)
865 .unwrap_or(false);
866 if !approved && started.elapsed() >= Duration::from_secs(310) {
867 fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
868 }
869 if stop.load(Ordering::Acquire) {
870 let _ = child.kill();
871 }
872 match child.try_wait() {
873 Ok(Some(status)) => break Some(status),
874 Ok(None) => thread::sleep(Duration::from_millis(10)),
875 Err(_) => {
876 fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다");
877 let _ = child.kill();
878 break child.wait().ok();
879 }
880 }
881 };
882 done.store(true, Ordering::Release);
883 for handle in handles {
884 if handle.join().is_err() {
885 fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다");
886 }
887 }
888 if cancel_write_failed.load(Ordering::Acquire)
889 && !(terminal_received.load(Ordering::Acquire)
890 && status.as_ref().is_some_and(|status| status.success()))
891 {
892 fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다");
893 }
894 if let Some(status) = status {
895 // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함.
896 notify(&events, ui::HostEvent::CleanupComplete);
897 notify(
898 &events,
899 ui::HostEvent::Exited {
900 success: status.success(),
901 },
902 );
903 }
904}
905
906#[cfg(test)]
907#[path = "../../../tests/rust-app-ui/conflict_codec.rs"]
908mod conflict_codec_tests;