team-ljyzipelo

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