team-ljyzipelo

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