team-ljyzipelo

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