team-ljyzipelo

공개
741줄25 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::Unix { device, inode } => wire::SourceObject::Unix { device, inode },
139 ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows {
140 volume_serial: volume,
141 file_id,
142 },
143 },
144 archive_bytes: id.archive_bytes,
145 archive_sha256: id.archive_sha256,
146 }
147}
148fn list_to_ui(id: wire::ListId) -> ui::ListId {
149 ui::ListId {
150 catalog_version: id.catalog_version,
151 format: format_to_ui(id.format),
152 source_object: match id.source_object {
153 wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode },
154 wire::SourceObject::Windows {
155 volume_serial,
156 file_id,
157 } => ui::SourceObject::Windows {
158 volume: volume_serial,
159 file_id,
160 },
161 },
162 archive_bytes: id.archive_bytes,
163 archive_sha256: id.archive_sha256,
164 }
165}
166fn start_to_wire(start: ui::Start) -> wire::Start {
167 let action = match start {
168 ui::Start::List { archive } => wire::Action::List {
169 archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)),
170 },
171 ui::Start::Extract {
172 archive,
173 destination,
174 selection,
175 list_id,
176 gzip_output_name,
177 } => wire::Action::Extract {
178 archive: wire::NativePath::from_path(&crate::archive_path::worker_path(&archive)),
179 destination: wire::NativePath::from_path(&crate::archive_path::worker_path(
180 &destination,
181 )),
182 selection: match selection {
183 ui::Selection::All => wire::Selection::All,
184 ui::Selection::EntryIds(ids) => wire::Selection::EntryIds(ids),
185 },
186 list_id: Some(list_to_wire(list_id)),
187 gzip_output_name,
188 },
189 ui::Start::CreateZip {
190 sources,
191 output_file,
192 method,
193 aes256,
194 } => wire::Action::CreateZip {
195 sources: sources
196 .into_iter()
197 .map(|(path, archive_name)| wire::Source {
198 path: wire::NativePath::from_path(&crate::archive_path::worker_path(&path)),
199 archive_name,
200 })
201 .collect(),
202 output_file: wire::NativePath::from_path(&crate::archive_path::worker_path(
203 &output_file,
204 )),
205 method: match method {
206 ui::Method::Store => wire::Method::Store,
207 ui::Method::Deflate => wire::Method::Deflate,
208 },
209 encryption: if aes256 {
210 wire::Encryption::Aes256
211 } else {
212 wire::Encryption::None
213 },
214 },
215 };
216 wire::Start {
217 action,
218 limits: wire::Limits::default(),
219 }
220}
221fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> {
222 Some(match error {
223 wire::ErrorCode::None => return None,
224 wire::ErrorCode::Integrity => ui::ErrorCode::Integrity,
225 wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat,
226 wire::ErrorCode::UnsupportedFeature => ui::ErrorCode::UnsupportedFeature,
227 wire::ErrorCode::WrongPassword => ui::ErrorCode::WrongPassword,
228 wire::ErrorCode::UnsafePath => ui::ErrorCode::UnsafePath,
229 wire::ErrorCode::Conflict => ui::ErrorCode::Conflict,
230 wire::ErrorCode::Limit => ui::ErrorCode::Limit,
231 wire::ErrorCode::Io => ui::ErrorCode::Io,
232 wire::ErrorCode::DiskFull => ui::ErrorCode::DiskFull,
233 wire::ErrorCode::Protocol => ui::ErrorCode::Protocol,
234 wire::ErrorCode::Internal => ui::ErrorCode::Internal,
235 wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged,
236 wire::ErrorCode::InvalidRequest => ui::ErrorCode::InvalidRequest,
237 })
238}
239fn event_to_ui(
240 message: wire::Message,
241 expected: Option<wire::ActionKind>,
242) -> Result<ui::Event, ()> {
243 Ok(match message {
244 wire::Message::Accepted { action, encryption } if expected == Some(action) => {
245 ui::Event::Accepted { encryption }
246 }
247 wire::Message::Entry(entry) => ui::Event::Entry(ui::Entry {
248 id: entry.entry_id,
249 name: entry.name,
250 kind: kind_to_ui(entry.kind),
251 bytes: Some(entry.size),
252 packed: Some(entry.compressed_size),
253 encrypted: entry.encrypted,
254 }),
255 wire::Message::ListEnd {
256 entry_count,
257 list_id,
258 } => ui::Event::ListEnd {
259 entry_count,
260 list_id: list_to_ui(list_id),
261 },
262 wire::Message::PasswordRequired {
263 challenge_id,
264 attempt,
265 purpose,
266 } => ui::Event::PasswordRequired {
267 challenge_id,
268 attempt,
269 encrypt: purpose == wire::PasswordPurpose::Encrypt,
270 },
271 wire::Message::ConflictRequired {
272 challenge_id,
273 entry_id,
274 relative_name,
275 incoming_size,
276 existing_size,
277 } if expected == Some(wire::ActionKind::Extract) => {
278 ui::Event::ConflictRequired(ui::Conflict {
279 challenge_id,
280 entry_id,
281 relative_name,
282 incoming_size,
283 existing_size,
284 })
285 }
286 wire::Message::ConflictResolved {
287 entry_id,
288 relative_name,
289 choice,
290 } if expected == Some(wire::ActionKind::Extract) => {
291 ui::Event::ConflictResolved(ui::Resolution {
292 entry_id,
293 relative_name,
294 choice: conflict_to_ui(choice),
295 })
296 }
297 wire::Message::Progress {
298 stage,
299 processed_bytes,
300 total_bytes,
301 completed_entries,
302 } => ui::Event::Progress {
303 stage: stage_to_ui(stage),
304 processed: processed_bytes,
305 total: total_bytes,
306 completed_entries: completed_entries.into(),
307 },
308 wire::Message::Output {
309 entry_id,
310 relative_name,
311 disposition,
312 } => ui::Event::Output {
313 entry_id,
314 relative_name,
315 disposition: disposition_to_ui(disposition),
316 },
317 wire::Message::CancelAck {
318 request_sequence,
319 status,
320 } => ui::Event::CancelAck {
321 request_sequence,
322 status: cancel_to_ui(status),
323 },
324 wire::Message::Terminal(terminal) => ui::Event::Terminal(ui::Terminal {
325 outcome: outcome_to_ui(terminal.outcome),
326 error: error_to_ui(terminal.error),
327 publication: publication_to_ui(terminal.publication),
328 created_count: terminal.created_count,
329 retained_partial_count: terminal.retained_partial_count,
330 durability: durability_to_ui(terminal.durability),
331 cleanup: cleanup_to_ui(terminal.cleanup),
332 }),
333 _ => return Err(()),
334 })
335}
336
337// 실제 파이프 쓰기는 백그라운드에서 수행하고 UI에서는 한 프레임만 직렬화함.
338#[derive(Clone, Default)]
339struct FrameBuffer(Rc<RefCell<Vec<u8>>>);
340impl Write for FrameBuffer {
341 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
342 let mut buffer = self.0.borrow_mut();
343 if buffer.len().saturating_add(bytes.len()) > codec::MAX_BODY + 32 {
344 return Err(io::Error::other("요청 프레임 한도 초과"));
345 }
346 buffer.extend_from_slice(bytes);
347 Ok(bytes.len())
348 }
349 fn flush(&mut self) -> io::Result<()> {
350 Ok(())
351 }
352}
353struct Frame(Vec<u8>, bool);
354impl Drop for Frame {
355 fn drop(&mut self) {
356 self.0.fill(0);
357 }
358}
359fn notify(events: &SyncSender<ui::HostEvent>, event: ui::HostEvent) -> bool {
360 events.send(event).is_ok()
361}
362fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) {
363 stop.store(true, Ordering::Release);
364 notify(events, ui::HostEvent::Fault(message.into()));
365}
366
367pub struct ProcessFactory {
368 worker: PathBuf,
369}
370impl ProcessFactory {
371 pub fn new(worker: PathBuf) -> Self {
372 Self { worker }
373 }
374 pub fn sibling() -> Result<Self, String> {
375 let executable =
376 std::env::current_exe().map_err(|_| "앱 실행 위치를 확인하지 못했습니다")?;
377 let parent = executable.parent().ok_or("앱 실행 폴더가 없습니다")?;
378 Ok(Self::new(parent.join(if cfg!(windows) {
379 "zipelo-archive-worker.exe"
380 } else {
381 "zipelo-archive-worker"
382 })))
383 }
384}
385impl ui::Factory for ProcessFactory {
386 fn connect(&mut self, job_id: u64) -> Result<Box<dyn ui::Connection>, String> {
387 if !self.worker.is_absolute() || job_id == 0 {
388 return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into());
389 }
390 let (send, requests) = mpsc::sync_channel::<Frame>(8);
391 let (events, receive) = mpsc::sync_channel(64);
392 let (ready, started) = mpsc::sync_channel(1);
393 let stop = Arc::new(AtomicBool::new(false));
394 let done = Arc::new(AtomicBool::new(false));
395 let expected = Arc::new(Mutex::new(None));
396 let worker = self.worker.clone();
397 let worker_stop = stop.clone();
398 let worker_done = done.clone();
399 let worker_expected = expected.clone();
400 let supervisor = thread::Builder::new()
401 .name("zipelo-worker-owner".into())
402 .spawn(move || {
403 let mut command = Command::new(worker);
404 command
405 .stdin(Stdio::piped())
406 .stdout(Stdio::piped())
407 .stderr(Stdio::piped());
408 #[cfg(windows)]
409 {
410 use std::os::windows::process::CommandExt;
411 command.creation_flags(0x08000000);
412 }
413 let child = match command.spawn() {
414 Ok(child) => child,
415 Err(_) => {
416 let _ = ready.send(Err(
417 "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요"
418 .to_string(),
419 ));
420 return;
421 }
422 };
423 if ready.send(Ok(())).is_err() {
424 let mut child = child;
425 let _ = child.kill();
426 let _ = child.wait();
427 return;
428 }
429 supervise(
430 child,
431 job_id,
432 requests,
433 events,
434 worker_stop,
435 worker_done,
436 worker_expected,
437 );
438 })
439 .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?;
440 match started.recv() {
441 Ok(Ok(())) => {
442 let buffer = FrameBuffer::default();
443 Ok(Box::new(ProcessConnection {
444 job_id,
445 next: 0,
446 writer: codec::Writer::new(buffer.clone(), job_id),
447 buffer,
448 send: Some(send),
449 receive: Some(receive),
450 stop,
451 supervisor: Some(supervisor),
452 expected,
453 done,
454 disconnected: false,
455 reaped: false,
456 }))
457 }
458 result => {
459 stop.store(true, Ordering::Release);
460 drop(send);
461 drop(receive);
462 let _ = supervisor.join();
463 Err(result
464 .ok()
465 .and_then(Result::err)
466 .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into()))
467 }
468 }
469 }
470}
471struct ProcessConnection {
472 job_id: u64,
473 next: u64,
474 writer: codec::Writer<FrameBuffer>,
475 buffer: FrameBuffer,
476 send: Option<SyncSender<Frame>>,
477 receive: Option<Receiver<ui::HostEvent>>,
478 stop: Arc<AtomicBool>,
479 supervisor: Option<JoinHandle<()>>,
480 expected: Arc<Mutex<Option<wire::ActionKind>>>,
481 done: Arc<AtomicBool>,
482 disconnected: bool,
483 reaped: bool,
484}
485impl ui::Connection for ProcessConnection {
486 fn send(&mut self, request: ui::Request) -> Result<(), String> {
487 if self.stop.load(Ordering::Acquire)
488 || request.job_id != self.job_id
489 || request.sequence != self.next
490 || self.next >= codec::MAX_FRAMES
491 {
492 self.stop.store(true, Ordering::Release);
493 return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into());
494 }
495 let is_cancel = matches!(request.command, ui::Command::Cancel);
496 let message = match request.command {
497 ui::Command::Start(start) => {
498 let start = start_to_wire(start);
499 *self.expected.lock().map_err(|_| {
500 self.stop.store(true, Ordering::Release);
501 "작업자 요청 상태 오류"
502 })? = Some(start.action.kind());
503 if start.action.kind() == wire::ActionKind::Extract {
504 wire::Message::StartInteractive(start)
505 } else {
506 wire::Message::Start(start)
507 }
508 }
509 ui::Command::ConflictReply {
510 challenge_id,
511 choice,
512 apply_to_remaining,
513 } => wire::Message::ConflictReply {
514 challenge_id,
515 choice: conflict_to_wire(choice),
516 apply_to_remaining,
517 },
518 ui::Command::Cancel => wire::Message::Cancel,
519 ui::Command::Password {
520 challenge_id,
521 secret,
522 } => wire::Message::Password {
523 challenge_id,
524 secret: wire::Secret(secret.as_bytes().to_vec()),
525 },
526 };
527 if self.writer.send(&message).is_err() {
528 self.buffer.0.borrow_mut().fill(0);
529 self.buffer.0.borrow_mut().clear();
530 self.stop.store(true, Ordering::Release);
531 return Err("작업자 요청을 직렬화하지 못했습니다".into());
532 }
533 let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()), is_cancel);
534 if self.send.as_ref().unwrap().try_send(bytes).is_err() {
535 if is_cancel && self.done.load(Ordering::Acquire) {
536 self.next += 1;
537 return Ok(());
538 }
539 self.stop.store(true, Ordering::Release);
540 return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
541 }
542 self.next += 1;
543 Ok(())
544 }
545 fn poll(&mut self) -> Option<ui::HostEvent> {
546 match self.receive.as_ref()?.try_recv() {
547 Ok(event) => {
548 if matches!(event, ui::HostEvent::Exited { .. }) {
549 self.reaped = true;
550 }
551 Some(event)
552 }
553 Err(mpsc::TryRecvError::Empty) => None,
554 Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => {
555 self.disconnected = true;
556 Some(ui::HostEvent::Fault(
557 "작업자 통신 스레드가 종료됐습니다".into(),
558 ))
559 }
560 Err(_) => None,
561 }
562 }
563}
564impl Drop for ProcessConnection {
565 fn drop(&mut self) {
566 self.stop.store(true, Ordering::Release);
567 self.send.take();
568 self.receive.take();
569 if let Some(supervisor) = self.supervisor.take() {
570 let _ = supervisor.join();
571 }
572 }
573}
574
575fn supervise(
576 mut child: std::process::Child,
577 job_id: u64,
578 requests: Receiver<Frame>,
579 events: SyncSender<ui::HostEvent>,
580 stop: Arc<AtomicBool>,
581 done: Arc<AtomicBool>,
582 expected: Arc<Mutex<Option<wire::ActionKind>>>,
583) {
584 let mut input = child.stdin.take().unwrap();
585 let mut output = child.stdout.take().unwrap();
586 let mut errors = child.stderr.take().unwrap();
587 let mut threads = Vec::new();
588 let cancel_write_failed = Arc::new(AtomicBool::new(false));
589 let terminal_received = Arc::new(AtomicBool::new(false));
590 let failed_cancel = cancel_write_failed.clone();
591 let tx = events.clone();
592 let abort = stop.clone();
593 let finished = done.clone();
594 threads.push(
595 thread::Builder::new()
596 .name("zipelo-worker-input".into())
597 .spawn(move || {
598 while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) {
599 match requests.recv_timeout(Duration::from_millis(10)) {
600 Ok(frame) => {
601 if input
602 .write_all(&frame.0)
603 .and_then(|_| input.flush())
604 .is_err()
605 {
606 if frame.1 {
607 // 취소 쓰기 실패는 응답과 실제 종료 결과를 확인한 뒤 판단함.
608 failed_cancel.store(true, Ordering::Release);
609 } else {
610 fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다");
611 }
612 break;
613 }
614 }
615 Err(mpsc::RecvTimeoutError::Timeout) => {}
616 Err(_) => break,
617 }
618 }
619 }),
620 );
621 let tx = events.clone();
622 let abort = stop.clone();
623 let received_terminal = terminal_received.clone();
624 threads.push(
625 thread::Builder::new()
626 .name("zipelo-worker-output".into())
627 .spawn(move || {
628 let eof;
629 {
630 let mut reader = codec::Reader::new(&mut output);
631 eof = loop {
632 match reader.read() {
633 Ok(Some((job, sequence, message))) => {
634 let action = expected.lock().ok().and_then(|value| *value);
635 let event = event_to_ui(message, action);
636 if job != job_id || event.is_err() {
637 fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
638 break false;
639 }
640 if matches!(event, Ok(ui::Event::Terminal(_))) {
641 received_terminal.store(true, Ordering::Release);
642 }
643 if !notify(
644 &tx,
645 ui::HostEvent::Frame {
646 job_id: job,
647 sequence,
648 event: event.unwrap(),
649 },
650 ) {
651 return;
652 }
653 }
654 Ok(None) => break true,
655 Err(_) => {
656 fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다");
657 break false;
658 }
659 }
660 };
661 }
662 if eof || io::copy(&mut output, &mut io::sink()).is_ok() {
663 notify(&tx, ui::HostEvent::StdoutEof);
664 }
665 }),
666 );
667 let tx = events.clone();
668 let abort = stop.clone();
669 threads.push(
670 thread::Builder::new()
671 .name("zipelo-worker-errors".into())
672 .spawn(move || {
673 let mut bytes = [0u8; 4096];
674 loop {
675 match errors.read(&mut bytes) {
676 Ok(0) => {
677 notify(&tx, ui::HostEvent::StderrEof);
678 break;
679 }
680 Ok(_) => {}
681 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
682 Err(_) => {
683 fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다");
684 break;
685 }
686 }
687 }
688 }),
689 );
690 let mut handles = Vec::new();
691 for result in threads {
692 match result {
693 Ok(handle) => handles.push(handle),
694 Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"),
695 }
696 }
697 let started = Instant::now();
698 let status = loop {
699 if started.elapsed() >= Duration::from_secs(310) {
700 fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
701 }
702 if stop.load(Ordering::Acquire) {
703 let _ = child.kill();
704 }
705 match child.try_wait() {
706 Ok(Some(status)) => break Some(status),
707 Ok(None) => thread::sleep(Duration::from_millis(10)),
708 Err(_) => {
709 fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다");
710 let _ = child.kill();
711 break child.wait().ok();
712 }
713 }
714 };
715 done.store(true, Ordering::Release);
716 for handle in handles {
717 if handle.join().is_err() {
718 fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다");
719 }
720 }
721 if cancel_write_failed.load(Ordering::Acquire)
722 && !(terminal_received.load(Ordering::Acquire)
723 && status.as_ref().is_some_and(|status| status.success()))
724 {
725 fault(&events, &stop, "작업자 요청 파이프 쓰기에 실패했습니다");
726 }
727 if let Some(status) = status {
728 // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함.
729 notify(&events, ui::HostEvent::CleanupComplete);
730 notify(
731 &events,
732 ui::HostEvent::Exited {
733 success: status.success(),
734 },
735 );
736 }
737}
738
739#[cfg(test)]
740#[path = "../../../tests/rust-app-ui/conflict_codec.rs"]
741mod conflict_codec_tests;