team-ljyzipelo

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