team-ljyzipelo

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