team-ljyzipelo

공개
912줄32 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 {
617 input: u64::MAX,
618 output: 64 * 1024 * 1024 * 1024,
619 entries: 200_000,
620 }
621 } else {
622 wire::Limits::default()
623 };
624 let interactive = matches!(
625 start.action.kind(),
626 wire::ActionKind::Extract | wire::ActionKind::Preview
627 );
628 wire::Message::StartGuarded(wire::GuardedStart {
629 start,
630 ceiling,
631 interactive,
632 })
633 }
634 ui::Command::ResourceReply {
635 challenge_id,
636 scope,
637 allow,
638 } => wire::Message::ResourceReply {
639 challenge_id,
640 scope,
641 allow,
642 },
643 ui::Command::ConflictReply {
644 challenge_id,
645 choice,
646 apply_to_remaining,
647 } => wire::Message::ConflictReply {
648 challenge_id,
649 choice: conflict_to_wire(choice),
650 apply_to_remaining,
651 },
652 ui::Command::Cancel => wire::Message::Cancel,
653 ui::Command::Password {
654 challenge_id,
655 secret,
656 } => wire::Message::Password {
657 challenge_id,
658 secret: wire::Secret(secret.as_bytes().to_vec()),
659 },
660 };
661 if self.writer.send(&message).is_err() {
662 self.buffer.0.borrow_mut().fill(0);
663 self.buffer.0.borrow_mut().clear();
664 self.stop.store(true, Ordering::Release);
665 return Err("작업자 요청을 직렬화하지 못했습니다".into());
666 }
667 let mut resources = self.resources.lock().map_err(|_| {
668 self.stop.store(true, Ordering::Release);
669 "작업자 승인 상태 오류"
670 })?;
671 let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel);
672 if self.send.as_ref().unwrap().try_send(bytes).is_err() {
673 if is_cancel && self.done.load(Ordering::Acquire) {
674 self.next += 1;
675 return Ok(());
676 }
677 self.stop.store(true, Ordering::Release);
678 return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
679 }
680 if let wire::Message::ResourceReply {
681 challenge_id,
682 scope,
683 allow,
684 } = message
685 && resources.pending == Some((challenge_id, scope))
686 {
687 resources.approved |= allow;
688 resources.pending = None;
689 }
690 self.next += 1;
691 Ok(())
692 }
693 fn poll(&mut self) -> Option<ui::HostEvent> {
694 match self.receive.as_ref()?.try_recv() {
695 Ok(event) => {
696 if matches!(event, ui::HostEvent::Exited { .. }) {
697 self.reaped = true;
698 }
699 Some(event)
700 }
701 Err(mpsc::TryRecvError::Empty) => None,
702 Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => {
703 self.disconnected = true;
704 Some(ui::HostEvent::Fault(
705 "작업자 통신 스레드가 종료됐습니다".into(),
706 ))
707 }
708 Err(_) => None,
709 }
710 }
711}
712impl Drop for ProcessConnection {
713 fn drop(&mut self) {
714 self.stop.store(true, Ordering::Release);
715 self.send.take();
716 self.receive.take();
717 if let Some(supervisor) = self.supervisor.take() {
718 let _ = supervisor.join();
719 }
720 }
721}
722
723fn supervise(
724 mut child: std::process::Child,
725 job_id: u64,
726 requests: Receiver<Frame>,
727 events: SyncSender<ui::HostEvent>,
728 stop: Arc<AtomicBool>,
729 done: Arc<AtomicBool>,
730 expected: Arc<Mutex<Option<wire::ActionKind>>>,
731 resources: Arc<Mutex<ResourceDeadline>>,
732) {
733 let mut input = child.stdin.take().unwrap();
734 let mut output = child.stdout.take().unwrap();
735 let mut errors = child.stderr.take().unwrap();
736 let mut threads = Vec::new();
737 let cancel_write_failed = Arc::new(AtomicBool::new(false));
738 let terminal_received = Arc::new(AtomicBool::new(false));
739 let failed_cancel = cancel_write_failed.clone();
740 let tx = events.clone();
741 let abort = stop.clone();
742 let finished = done.clone();
743 threads.push(
744 thread::Builder::new()
745 .name("zipelo-worker-input".into())
746 .spawn(move || {
747 while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) {
748 match requests.recv_timeout(Duration::from_millis(10)) {
749 Ok(frame) => {
750 if input
751 .write_all(&frame.0)
752 .and_then(|_| input.flush())
753 .is_err()
754 {
755 if frame.1 {
756 // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함.
757 failed_cancel.store(true, Ordering::Release);
758 } else {
759 fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다");
760 }
761 break;
762 }
763 }
764 Err(mpsc::RecvTimeoutError::Timeout) => {}
765 Err(_) => break,
766 }
767 }
768 }),
769 );
770 let tx = events.clone();
771 let abort = stop.clone();
772 let received_terminal = terminal_received.clone();
773 let pending_resource = resources.clone();
774 threads.push(
775 thread::Builder::new()
776 .name("zipelo-worker-output".into())
777 .spawn(move || {
778 let eof;
779 {
780 let mut reader = codec::Reader::new(&mut output);
781 eof = loop {
782 match reader.read() {
783 Ok(Some((job, sequence, message))) => {
784 let action = expected.lock().ok().and_then(|value| *value);
785 let event = event_to_ui(message, action);
786 if job != job_id || event.is_err() {
787 fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
788 break false;
789 }
790 if let Ok(ui::Event::ResourceRequired(question)) = &event {
791 if let Ok(mut state) = pending_resource.lock() {
792 state.pending = Some((question.id, question.scope));
793 } else {
794 fault(&tx, &abort, "작업자 승인 상태 오류");
795 break false;
796 }
797 }
798 if matches!(event, Ok(ui::Event::Terminal(_))) {
799 received_terminal.store(true, Ordering::Release);
800 }
801 if !notify(
802 &tx,
803 ui::HostEvent::Frame {
804 job_id: job,
805 sequence,
806 event: event.unwrap(),
807 },
808 ) {
809 return;
810 }
811 }
812 Ok(None) => break true,
813 Err(_) => {
814 fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다");
815 break false;
816 }
817 }
818 };
819 }
820 if eof || io::copy(&mut output, &mut io::sink()).is_ok() {
821 notify(&tx, ui::HostEvent::StdoutEof);
822 }
823 }),
824 );
825 let tx = events.clone();
826 let abort = stop.clone();
827 threads.push(
828 thread::Builder::new()
829 .name("zipelo-worker-errors".into())
830 .spawn(move || {
831 let mut bytes = [0u8; 4096];
832 loop {
833 match errors.read(&mut bytes) {
834 Ok(0) => {
835 notify(&tx, ui::HostEvent::StderrEof);
836 break;
837 }
838 Ok(count) => {
839 // 작업자가 표준 오류에 남긴 내용은 디버그 로그로만 옮김.
840 crate::log_debug!(
841 "작업자 표준 오류: {}",
842 String::from_utf8_lossy(&bytes[..count]).trim_end()
843 );
844 }
845 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
846 Err(error) => {
847 crate::log_error!("작업자 오류 파이프 읽기 실패: {error}");
848 fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다");
849 break;
850 }
851 }
852 }
853 }),
854 );
855 let mut handles = Vec::new();
856 for result in threads {
857 match result {
858 Ok(handle) => handles.push(handle),
859 Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"),
860 }
861 }
862 let started = Instant::now();
863 let status = loop {
864 // 승인 뒤 실제 진행과 질문 대기 시간은 작업자의 60초 정체 감시로 판단함.
865 // 응답 프레임 간격을 실제 파일 처리 진행으로 간주하지 않음.
866 let approved = resources
867 .lock()
868 .map(|state| state.approved)
869 .unwrap_or(false);
870 if !approved && started.elapsed() >= Duration::from_secs(310) {
871 fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
872 }
873 if stop.load(Ordering::Acquire) {
874 let _ = child.kill();
875 }
876 match child.try_wait() {
877 Ok(Some(status)) => break Some(status),
878 Ok(None) => thread::sleep(Duration::from_millis(10)),
879 Err(_) => {
880 fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다");
881 let _ = child.kill();
882 break child.wait().ok();
883 }
884 }
885 };
886 done.store(true, Ordering::Release);
887 for handle in handles {
888 if handle.join().is_err() {
889 fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다");
890 }
891 }
892 if cancel_write_failed.load(Ordering::Acquire)
893 && !(terminal_received.load(Ordering::Acquire)
894 && status.as_ref().is_some_and(|status| status.success()))
895 {
896 fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다");
897 }
898 if let Some(status) = status {
899 // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함.
900 notify(&events, ui::HostEvent::CleanupComplete);
901 notify(
902 &events,
903 ui::HostEvent::Exited {
904 success: status.success(),
905 },
906 );
907 }
908}
909
910#[cfg(test)]
911#[path = "../../../tests/rust-app-ui/conflict_codec.rs"]
912mod conflict_codec_tests;