team-ljyzipelo

공개

화면을 실제 압축 작업자 프로세스에 연결함

작성자
호시노 히나타
작성 시각
커밋
fdb38ec1a6032351ee7b2d4b76242d2e7ccfc084
이 시점의 파일 보기

변경된 파일 22개

+2,673-1

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정experiments/rust-ui-memory-app/Cargo.lock+9-0
@@ -3948,6 +3948,14 @@ dependencies = [
39483948 "zipelo-rust-memory-zip-create",
39493949]
39503950
3951추가: [[package]]
3952추가: name = "zipelo-archive-worker"
3953추가: version = "0.1.0"
3954추가: dependencies = [
3955추가: "sha2",
3956추가: "zlib-rs",
3957추가: ]
3958추가:
39513959[[package]]
39523960name = "zipelo-memory-gzip-reader"
39533961version = "0.1.0"
@@ -3976,6 +3984,7 @@ version = "0.1.0"
39763984dependencies = [
39773985 "eframe",
39783986 "zipelo-app-core-memory",
3987추가: "zipelo-archive-worker",
39793988]
39803989
39813990[[package]]
수정experiments/rust-ui-memory-app/Cargo.toml+11-1
@@ -15,16 +15,26 @@ doctest = false
1515[features]
1616default = []
1717ui = ["dep:eframe"]
18추가: ui-fixture = ["ui"]
1819
1920[dependencies]
21추가: worker_protocol = { package = "zipelo-archive-worker", path = "../rust-archive-worker" }
2022core_memory = { package = "zipelo-app-core-memory", path = "../rust-app-core-memory" }
2123eframe = { version = "=0.37.0", optional = true, default-features = false, features = ["accesskit", "clipboard", "glow", "system_fonts", "wayland", "x11"] }
2224
2325[[bin]]
2426name = "zipelo-ui-memory-app"
25삭제: path = "src/app.rs"
27추가: path = "src/desktop.rs"
2628required-features = ["ui"]
2729
2830[[test]]
2931name = "ui_memory"
3032path = "../../tests/rust-ui-memory-app/regressions.rs"
33추가:
34추가: [[test]]
35추가: name = "archive_ui"
36추가: path = "../../tests/rust-app-ui/regressions.rs"
37추가:
38추가: [[test]]
39추가: name = "real_worker"
40추가: path = "../../tests/rust-app-real-worker/flows.rs"
추가experiments/rust-ui-memory-app/src/archive_process.rs+657-0
@@ -0,0 +1,657 @@
1추가: use crate::archive_ui as ui;
2추가: use 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추가: };
16추가: use worker_protocol::{protocol as wire, wire as codec};
17추가:
18추가: macro_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추가: }
25추가: convert_enum!(
26추가: format_to_wire,
27추가: ui::Format,
28추가: wire::Format,
29추가: Zip,
30추가: Tar,
31추가: Gzip,
32추가: TarGzip
33추가: );
34추가: convert_enum!(
35추가: format_to_ui,
36추가: wire::Format,
37추가: ui::Format,
38추가: Zip,
39추가: Tar,
40추가: Gzip,
41추가: TarGzip
42추가: );
43추가: convert_enum!(
44추가: kind_to_ui,
45추가: wire::EntryKind,
46추가: ui::Kind,
47추가: File,
48추가: Directory,
49추가: Link,
50추가: Other
51추가: );
52추가: convert_enum!(
53추가: stage_to_ui,
54추가: wire::Stage,
55추가: ui::Stage,
56추가: Scan,
57추가: Read,
58추가: Decode,
59추가: Write,
60추가: Verify,
61추가: Commit
62추가: );
63추가: convert_enum!(
64추가: disposition_to_ui,
65추가: wire::Disposition,
66추가: ui::Disposition,
67추가: Created,
68추가: PartialRetained,
69추가: Removed,
70추가: CommitUncertain
71추가: );
72추가: convert_enum!(
73추가: outcome_to_ui,
74추가: wire::Outcome,
75추가: ui::Outcome,
76추가: Completed,
77추가: Failed,
78추가: Cancelled
79추가: );
80추가: convert_enum!(
81추가: publication_to_ui,
82추가: wire::Publication,
83추가: ui::Publication,
84추가: None,
85추가: Partial,
86추가: Complete,
87추가: Uncertain
88추가: );
89추가: convert_enum!(
90추가: durability_to_ui,
91추가: wire::Durability,
92추가: ui::Durability,
93추가: NotApplicable,
94추가: Synced,
95추가: Unconfirmed,
96추가: Failed
97추가: );
98추가: convert_enum!(
99추가: cleanup_to_ui,
100추가: wire::Cleanup,
101추가: ui::Cleanup,
102추가: Complete,
103추가: Failed,
104추가: Unconfirmed
105추가: );
106추가: convert_enum!(
107추가: cancel_to_ui,
108추가: wire::CancelStatus,
109추가: ui::CancelStatus,
110추가: Requested,
111추가: AlreadyRequested,
112추가: TooLate,
113추가: Finished
114추가: );
115추가: fn list_to_wire(id: ui::ListId) -> wire::ListId {
116추가: wire::ListId {
117추가: catalog_version: id.catalog_version,
118추가: format: format_to_wire(id.format),
119추가: source_object: match id.source_object {
120추가: ui::SourceObject::Unix { device, inode } => wire::SourceObject::Unix { device, inode },
121추가: ui::SourceObject::Windows { volume, file_id } => wire::SourceObject::Windows {
122추가: volume_serial: volume,
123추가: file_id,
124추가: },
125추가: },
126추가: archive_bytes: id.archive_bytes,
127추가: archive_sha256: id.archive_sha256,
128추가: }
129추가: }
130추가: fn list_to_ui(id: wire::ListId) -> ui::ListId {
131추가: ui::ListId {
132추가: catalog_version: id.catalog_version,
133추가: format: format_to_ui(id.format),
134추가: source_object: match id.source_object {
135추가: wire::SourceObject::Unix { device, inode } => ui::SourceObject::Unix { device, inode },
136추가: wire::SourceObject::Windows {
137추가: volume_serial,
138추가: file_id,
139추가: } => ui::SourceObject::Windows {
140추가: volume: volume_serial,
141추가: file_id,
142추가: },
143추가: },
144추가: archive_bytes: id.archive_bytes,
145추가: archive_sha256: id.archive_sha256,
146추가: }
147추가: }
148추가: fn start_to_wire(start: ui::Start) -> wire::Start {
149추가: let action = match start {
150추가: ui::Start::List { archive } => wire::Action::List {
151추가: archive: wire::NativePath::from_path(&archive),
152추가: },
153추가: ui::Start::Extract {
154추가: archive,
155추가: destination,
156추가: selection,
157추가: list_id,
158추가: gzip_output_name,
159추가: } => wire::Action::Extract {
160추가: archive: wire::NativePath::from_path(&archive),
161추가: destination: wire::NativePath::from_path(&destination),
162추가: selection: match selection {
163추가: ui::Selection::All => wire::Selection::All,
164추가: ui::Selection::EntryIds(ids) => wire::Selection::EntryIds(ids),
165추가: },
166추가: list_id: Some(list_to_wire(list_id)),
167추가: gzip_output_name,
168추가: },
169추가: ui::Start::CreateZip {
170추가: sources,
171추가: output_file,
172추가: method,
173추가: aes256,
174추가: } => wire::Action::CreateZip {
175추가: sources: sources
176추가: .into_iter()
177추가: .map(|(path, archive_name)| wire::Source {
178추가: path: wire::NativePath::from_path(&path),
179추가: archive_name,
180추가: })
181추가: .collect(),
182추가: output_file: wire::NativePath::from_path(&output_file),
183추가: method: match method {
184추가: ui::Method::Store => wire::Method::Store,
185추가: ui::Method::Deflate => wire::Method::Deflate,
186추가: },
187추가: encryption: if aes256 {
188추가: wire::Encryption::Aes256
189추가: } else {
190추가: wire::Encryption::None
191추가: },
192추가: },
193추가: };
194추가: wire::Start {
195추가: action,
196추가: limits: wire::Limits::default(),
197추가: }
198추가: }
199추가: fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> {
200추가: Some(match error {
201추가: wire::ErrorCode::None => return None,
202추가: wire::ErrorCode::Integrity => ui::ErrorCode::Integrity,
203추가: wire::ErrorCode::UnsupportedFormat => ui::ErrorCode::UnsupportedFormat,
204추가: wire::ErrorCode::UnsupportedFeature => ui::ErrorCode::UnsupportedFeature,
205추가: wire::ErrorCode::WrongPassword => ui::ErrorCode::WrongPassword,
206추가: wire::ErrorCode::UnsafePath => ui::ErrorCode::UnsafePath,
207추가: wire::ErrorCode::Conflict => ui::ErrorCode::Conflict,
208추가: wire::ErrorCode::Limit => ui::ErrorCode::Limit,
209추가: wire::ErrorCode::Io => ui::ErrorCode::Io,
210추가: wire::ErrorCode::Protocol => ui::ErrorCode::Protocol,
211추가: wire::ErrorCode::Internal => ui::ErrorCode::Internal,
212추가: wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged,
213추가: wire::ErrorCode::InvalidRequest => ui::ErrorCode::InvalidRequest,
214추가: })
215추가: }
216추가: fn event_to_ui(
217추가: message: wire::Message,
218추가: expected: Option<wire::ActionKind>,
219추가: ) -> Result<ui::Event, ()> {
220추가: Ok(match message {
221추가: wire::Message::Accepted { action, encryption } if expected == Some(action) => {
222추가: ui::Event::Accepted { encryption }
223추가: }
224추가: wire::Message::Entry(entry) => ui::Event::Entry(ui::Entry {
225추가: id: entry.entry_id,
226추가: name: entry.name,
227추가: kind: kind_to_ui(entry.kind),
228추가: bytes: Some(entry.size),
229추가: packed: Some(entry.compressed_size),
230추가: encrypted: entry.encrypted,
231추가: }),
232추가: wire::Message::ListEnd {
233추가: entry_count,
234추가: list_id,
235추가: } => ui::Event::ListEnd {
236추가: entry_count,
237추가: list_id: list_to_ui(list_id),
238추가: },
239추가: wire::Message::PasswordRequired {
240추가: challenge_id,
241추가: attempt,
242추가: purpose,
243추가: } => ui::Event::PasswordRequired {
244추가: challenge_id,
245추가: attempt,
246추가: encrypt: purpose == wire::PasswordPurpose::Encrypt,
247추가: },
248추가: wire::Message::Progress {
249추가: stage,
250추가: processed_bytes,
251추가: total_bytes,
252추가: completed_entries,
253추가: } => ui::Event::Progress {
254추가: stage: stage_to_ui(stage),
255추가: processed: processed_bytes,
256추가: total: total_bytes,
257추가: completed_entries: completed_entries.into(),
258추가: },
259추가: wire::Message::Output {
260추가: entry_id,
261추가: relative_name,
262추가: disposition,
263추가: } => ui::Event::Output {
264추가: entry_id,
265추가: relative_name,
266추가: disposition: disposition_to_ui(disposition),
267추가: },
268추가: wire::Message::CancelAck {
269추가: request_sequence,
270추가: status,
271추가: } => ui::Event::CancelAck {
272추가: request_sequence,
273추가: status: cancel_to_ui(status),
274추가: },
275추가: wire::Message::Terminal(terminal) => ui::Event::Terminal(ui::Terminal {
276추가: outcome: outcome_to_ui(terminal.outcome),
277추가: error: error_to_ui(terminal.error),
278추가: publication: publication_to_ui(terminal.publication),
279추가: created_count: terminal.created_count,
280추가: retained_partial_count: terminal.retained_partial_count,
281추가: durability: durability_to_ui(terminal.durability),
282추가: cleanup: cleanup_to_ui(terminal.cleanup),
283추가: }),
284추가: _ => return Err(()),
285추가: })
286추가: }
287추가:
288추가: // 실제 파이프 쓰기는 백그라운드에서 수행하고 UI에서는 한 프레임만 직렬화함.
289추가: #[derive(Clone, Default)]
290추가: struct FrameBuffer(Rc<RefCell<Vec<u8>>>);
291추가: impl Write for FrameBuffer {
292추가: fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
293추가: let mut buffer = self.0.borrow_mut();
294추가: if buffer.len().saturating_add(bytes.len()) > codec::MAX_BODY + 32 {
295추가: return Err(io::Error::other("요청 프레임 한도 초과"));
296추가: }
297추가: buffer.extend_from_slice(bytes);
298추가: Ok(bytes.len())
299추가: }
300추가: fn flush(&mut self) -> io::Result<()> {
301추가: Ok(())
302추가: }
303추가: }
304추가: struct Frame(Vec<u8>);
305추가: impl Drop for Frame {
306추가: fn drop(&mut self) {
307추가: self.0.fill(0);
308추가: }
309추가: }
310추가: fn notify(events: &SyncSender<ui::HostEvent>, event: ui::HostEvent) -> bool {
311추가: events.send(event).is_ok()
312추가: }
313추가: fn fault(events: &SyncSender<ui::HostEvent>, stop: &AtomicBool, message: &str) {
314추가: stop.store(true, Ordering::Release);
315추가: notify(events, ui::HostEvent::Fault(message.into()));
316추가: }
317추가:
318추가: pub struct ProcessFactory {
319추가: worker: PathBuf,
320추가: }
321추가: impl ProcessFactory {
322추가: pub fn new(worker: PathBuf) -> Self {
323추가: Self { worker }
324추가: }
325추가: pub fn sibling() -> Result<Self, String> {
326추가: let executable =
327추가: std::env::current_exe().map_err(|_| "앱 실행 위치를 확인하지 못했습니다")?;
328추가: let parent = executable.parent().ok_or("앱 실행 폴더가 없습니다")?;
329추가: Ok(Self::new(parent.join(if cfg!(windows) {
330추가: "zipelo-archive-worker.exe"
331추가: } else {
332추가: "zipelo-archive-worker"
333추가: })))
334추가: }
335추가: }
336추가: impl ui::Factory for ProcessFactory {
337추가: fn connect(&mut self, job_id: u64) -> Result<Box<dyn ui::Connection>, String> {
338추가: if !self.worker.is_absolute() || job_id == 0 {
339추가: return Err("작업자 경로 또는 작업 ID가 올바르지 않습니다".into());
340추가: }
341추가: let (send, requests) = mpsc::sync_channel::<Frame>(8);
342추가: let (events, receive) = mpsc::sync_channel(64);
343추가: let (ready, started) = mpsc::sync_channel(1);
344추가: let stop = Arc::new(AtomicBool::new(false));
345추가: let done = Arc::new(AtomicBool::new(false));
346추가: let expected = Arc::new(Mutex::new(None));
347추가: let worker = self.worker.clone();
348추가: let worker_stop = stop.clone();
349추가: let worker_done = done.clone();
350추가: let worker_expected = expected.clone();
351추가: let supervisor = thread::Builder::new()
352추가: .name("zipelo-worker-owner".into())
353추가: .spawn(move || {
354추가: let mut command = Command::new(worker);
355추가: command
356추가: .stdin(Stdio::piped())
357추가: .stdout(Stdio::piped())
358추가: .stderr(Stdio::piped());
359추가: #[cfg(windows)]
360추가: {
361추가: use std::os::windows::process::CommandExt;
362추가: command.creation_flags(0x08000000);
363추가: }
364추가: let child = match command.spawn() {
365추가: Ok(child) => child,
366추가: Err(_) => {
367추가: let _ = ready.send(Err(
368추가: "작업자를 실행하지 못했습니다. 앱과 작업자를 함께 설치하세요"
369추가: .to_string(),
370추가: ));
371추가: return;
372추가: }
373추가: };
374추가: if ready.send(Ok(())).is_err() {
375추가: let mut child = child;
376추가: let _ = child.kill();
377추가: let _ = child.wait();
378추가: return;
379추가: }
380추가: supervise(
381추가: child,
382추가: job_id,
383추가: requests,
384추가: events,
385추가: worker_stop,
386추가: worker_done,
387추가: worker_expected,
388추가: );
389추가: })
390추가: .map_err(|_| "작업자 관리 스레드를 시작하지 못했습니다")?;
391추가: match started.recv() {
392추가: Ok(Ok(())) => {
393추가: let buffer = FrameBuffer::default();
394추가: Ok(Box::new(ProcessConnection {
395추가: job_id,
396추가: next: 0,
397추가: writer: codec::Writer::new(buffer.clone(), job_id),
398추가: buffer,
399추가: send: Some(send),
400추가: receive: Some(receive),
401추가: stop,
402추가: supervisor: Some(supervisor),
403추가: expected,
404추가: done,
405추가: disconnected: false,
406추가: reaped: false,
407추가: }))
408추가: }
409추가: result => {
410추가: stop.store(true, Ordering::Release);
411추가: drop(send);
412추가: drop(receive);
413추가: let _ = supervisor.join();
414추가: Err(result
415추가: .ok()
416추가: .and_then(Result::err)
417추가: .unwrap_or_else(|| "작업자 시작 결과가 없습니다".into()))
418추가: }
419추가: }
420추가: }
421추가: }
422추가: struct ProcessConnection {
423추가: job_id: u64,
424추가: next: u64,
425추가: writer: codec::Writer<FrameBuffer>,
426추가: buffer: FrameBuffer,
427추가: send: Option<SyncSender<Frame>>,
428추가: receive: Option<Receiver<ui::HostEvent>>,
429추가: stop: Arc<AtomicBool>,
430추가: supervisor: Option<JoinHandle<()>>,
431추가: expected: Arc<Mutex<Option<wire::ActionKind>>>,
432추가: done: Arc<AtomicBool>,
433추가: disconnected: bool,
434추가: reaped: bool,
435추가: }
436추가: impl ui::Connection for ProcessConnection {
437추가: fn send(&mut self, request: ui::Request) -> Result<(), String> {
438추가: if self.stop.load(Ordering::Acquire)
439추가: || request.job_id != self.job_id
440추가: || request.sequence != self.next
441추가: || self.next >= codec::MAX_FRAMES
442추가: {
443추가: self.stop.store(true, Ordering::Release);
444추가: return Err("작업자 요청 채널이 닫혔거나 순서가 올바르지 않습니다".into());
445추가: }
446추가: let is_cancel = matches!(request.command, ui::Command::Cancel);
447추가: let message = match request.command {
448추가: ui::Command::Start(start) => {
449추가: let start = start_to_wire(start);
450추가: *self.expected.lock().map_err(|_| {
451추가: self.stop.store(true, Ordering::Release);
452추가: "작업자 요청 상태 오류"
453추가: })? = Some(start.action.kind());
454추가: wire::Message::Start(start)
455추가: }
456추가: ui::Command::Cancel => wire::Message::Cancel,
457추가: ui::Command::Password {
458추가: challenge_id,
459추가: secret,
460추가: } => wire::Message::Password {
461추가: challenge_id,
462추가: secret: wire::Secret(secret.as_bytes().to_vec()),
463추가: },
464추가: };
465추가: if self.writer.send(&message).is_err() {
466추가: self.buffer.0.borrow_mut().fill(0);
467추가: self.buffer.0.borrow_mut().clear();
468추가: self.stop.store(true, Ordering::Release);
469추가: return Err("작업자 요청을 직렬화하지 못했습니다".into());
470추가: }
471추가: let bytes = Frame(std::mem::take(&mut *self.buffer.0.borrow_mut()));
472추가: if self.send.as_ref().unwrap().try_send(bytes).is_err() {
473추가: if is_cancel && self.done.load(Ordering::Acquire) {
474추가: self.next += 1;
475추가: return Ok(());
476추가: }
477추가: self.stop.store(true, Ordering::Release);
478추가: return Err("작업자 요청 대기열이 닫혔거나 가득 찼습니다".into());
479추가: }
480추가: self.next += 1;
481추가: Ok(())
482추가: }
483추가: fn poll(&mut self) -> Option<ui::HostEvent> {
484추가: match self.receive.as_ref()?.try_recv() {
485추가: Ok(event) => {
486추가: if matches!(event, ui::HostEvent::Exited { .. }) {
487추가: self.reaped = true;
488추가: }
489추가: Some(event)
490추가: }
491추가: Err(mpsc::TryRecvError::Empty) => None,
492추가: Err(mpsc::TryRecvError::Disconnected) if !self.reaped && !self.disconnected => {
493추가: self.disconnected = true;
494추가: Some(ui::HostEvent::Fault(
495추가: "작업자 통신 스레드가 종료됐습니다".into(),
496추가: ))
497추가: }
498추가: Err(_) => None,
499추가: }
500추가: }
501추가: }
502추가: impl Drop for ProcessConnection {
503추가: fn drop(&mut self) {
504추가: self.stop.store(true, Ordering::Release);
505추가: self.send.take();
506추가: self.receive.take();
507추가: if let Some(supervisor) = self.supervisor.take() {
508추가: let _ = supervisor.join();
509추가: }
510추가: }
511추가: }
512추가:
513추가: fn supervise(
514추가: mut child: std::process::Child,
515추가: job_id: u64,
516추가: requests: Receiver<Frame>,
517추가: events: SyncSender<ui::HostEvent>,
518추가: stop: Arc<AtomicBool>,
519추가: done: Arc<AtomicBool>,
520추가: expected: Arc<Mutex<Option<wire::ActionKind>>>,
521추가: ) {
522추가: let mut input = child.stdin.take().unwrap();
523추가: let mut output = child.stdout.take().unwrap();
524추가: let mut errors = child.stderr.take().unwrap();
525추가: let mut threads = Vec::new();
526추가: let tx = events.clone();
527추가: let abort = stop.clone();
528추가: let finished = done.clone();
529추가: threads.push(
530추가: thread::Builder::new()
531추가: .name("zipelo-worker-input".into())
532추가: .spawn(move || {
533추가: while !finished.load(Ordering::Acquire) && !abort.load(Ordering::Acquire) {
534추가: match requests.recv_timeout(Duration::from_millis(10)) {
535추가: Ok(frame) => {
536추가: if input
537추가: .write_all(&frame.0)
538추가: .and_then(|_| input.flush())
539추가: .is_err()
540추가: {
541추가: fault(&tx, &abort, "작업자 요청 파이프 쓰기에 실패했습니다");
542추가: break;
543추가: }
544추가: }
545추가: Err(mpsc::RecvTimeoutError::Timeout) => {}
546추가: Err(_) => break,
547추가: }
548추가: }
549추가: }),
550추가: );
551추가: let tx = events.clone();
552추가: let abort = stop.clone();
553추가: threads.push(
554추가: thread::Builder::new()
555추가: .name("zipelo-worker-output".into())
556추가: .spawn(move || {
557추가: let eof;
558추가: {
559추가: let mut reader = codec::Reader::new(&mut output);
560추가: eof = loop {
561추가: match reader.read() {
562추가: Ok(Some((job, sequence, message))) => {
563추가: let action = expected.lock().ok().and_then(|value| *value);
564추가: let event = event_to_ui(message, action);
565추가: if job != job_id || event.is_err() {
566추가: fault(&tx, &abort, "작업자 응답이 요청과 일치하지 않습니다");
567추가: break false;
568추가: }
569추가: if !notify(
570추가: &tx,
571추가: ui::HostEvent::Frame {
572추가: job_id: job,
573추가: sequence,
574추가: event: event.unwrap(),
575추가: },
576추가: ) {
577추가: return;
578추가: }
579추가: }
580추가: Ok(None) => break true,
581추가: Err(_) => {
582추가: fault(&tx, &abort, "작업자 응답 프레임을 읽지 못했습니다");
583추가: break false;
584추가: }
585추가: }
586추가: };
587추가: }
588추가: if eof || io::copy(&mut output, &mut io::sink()).is_ok() {
589추가: notify(&tx, ui::HostEvent::StdoutEof);
590추가: }
591추가: }),
592추가: );
593추가: let tx = events.clone();
594추가: let abort = stop.clone();
595추가: threads.push(
596추가: thread::Builder::new()
597추가: .name("zipelo-worker-errors".into())
598추가: .spawn(move || {
599추가: let mut bytes = [0u8; 4096];
600추가: loop {
601추가: match errors.read(&mut bytes) {
602추가: Ok(0) => {
603추가: notify(&tx, ui::HostEvent::StderrEof);
604추가: break;
605추가: }
606추가: Ok(_) => {}
607추가: Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
608추가: Err(_) => {
609추가: fault(&tx, &abort, "작업자 오류 파이프를 읽지 못했습니다");
610추가: break;
611추가: }
612추가: }
613추가: }
614추가: }),
615추가: );
616추가: let mut handles = Vec::new();
617추가: for result in threads {
618추가: match result {
619추가: Ok(handle) => handles.push(handle),
620추가: Err(_) => fault(&events, &stop, "작업자 통신 스레드를 시작하지 못했습니다"),
621추가: }
622추가: }
623추가: let started = Instant::now();
624추가: let status = loop {
625추가: if started.elapsed() >= Duration::from_secs(310) {
626추가: fault(&events, &stop, "작업자 처리 제한 시간을 초과했습니다");
627추가: }
628추가: if stop.load(Ordering::Acquire) {
629추가: let _ = child.kill();
630추가: }
631추가: match child.try_wait() {
632추가: Ok(Some(status)) => break Some(status),
633추가: Ok(None) => thread::sleep(Duration::from_millis(10)),
634추가: Err(_) => {
635추가: fault(&events, &stop, "작업자 종료 상태를 확인하지 못했습니다");
636추가: let _ = child.kill();
637추가: break child.wait().ok();
638추가: }
639추가: }
640추가: };
641추가: done.store(true, Ordering::Release);
642추가: for handle in handles {
643추가: if handle.join().is_err() {
644추가: fault(&events, &stop, "작업자 통신 스레드 회수에 실패했습니다");
645추가: }
646추가: }
647추가: if let Some(status) = status {
648추가: // 회수와 모든 파이프 핸들 정리가 끝난 뒤에만 닫기 허용 근거를 전달함.
649추가: notify(&events, ui::HostEvent::CleanupComplete);
650추가: notify(
651추가: &events,
652추가: ui::HostEvent::Exited {
653추가: success: status.success(),
654추가: },
655추가: );
656추가: }
657추가: }
추가experiments/rust-ui-memory-app/src/archive_screen.rs+383-0
@@ -0,0 +1,383 @@
1추가: use crate::archive_ui::*;
2추가: use eframe::egui;
3추가: use std::path::PathBuf;
4추가:
5추가: pub struct ArchiveApp {
6추가: pub model: Model,
7추가: factory: Box<dyn Factory>,
8추가: open_text: String,
9추가: destination: String,
10추가: gzip_name: String,
11추가: sources: String,
12추가: zip_output: String,
13추가: password: String,
14추가: create: bool,
15추가: open: bool,
16추가: selected_only: bool,
17추가: method: Method,
18추가: fixture: bool,
19추가: }
20추가: impl ArchiveApp {
21추가: pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, fixture: bool) -> Self {
22추가: let mut app = Self {
23추가: model: Model::default(),
24추가: factory,
25추가: open_text: String::new(),
26추가: destination: String::new(),
27추가: gzip_name: String::new(),
28추가: sources: String::new(),
29추가: zip_output: String::new(),
30추가: password: String::new(),
31추가: create: false,
32추가: open: false,
33추가: selected_only: false,
34추가: method: Method::Deflate,
35추가: fixture,
36추가: };
37추가: if let Some(path) = startup {
38추가: app.open_path(path);
39추가: }
40추가: app
41추가: }
42추가: pub fn open_path(&mut self, archive: PathBuf) {
43추가: self.password.clear();
44추가: self.model
45추가: .begin(Start::List { archive }, self.factory.as_mut());
46추가: }
47추가: fn on_drop(&mut self, paths: Vec<PathBuf>) {
48추가: if self.model.busy() || paths.is_empty() {
49추가: return;
50추가: }
51추가: if paths.len() == 1 && !self.create {
52추가: self.open_path(paths[0].clone());
53추가: } else if paths.iter().all(|p| p.to_str().is_some()) {
54추가: self.sources = paths
55추가: .iter()
56추가: .map(|p| p.to_str().unwrap())
57추가: .collect::<Vec<_>>()
58추가: .join("\n");
59추가: self.create = true;
60추가: } else {
61추가: self.model.error = Some("ZIP 생성 경로는 현재 UTF-8 입력만 지원합니다".into());
62추가: }
63추가: }
64추가: }
65추가: impl ArchiveApp {
66추가: pub fn show(&mut self, root: &mut egui::Ui) {
67추가: self.model.poll();
68추가: if self.model.challenge.is_none() {
69추가: self.password.clear();
70추가: }
71추가: let ctx = root.ctx().clone();
72추가: let dropped = ctx.input(|i| {
73추가: i.raw
74추가: .dropped_files
75추가: .iter()
76추가: .map(|f| f.path().to_path_buf())
77추가: .collect::<Vec<_>>()
78추가: });
79추가: self.on_drop(dropped);
80추가: if ctx.input(|i| i.viewport().close_requested()) {
81추가: self.model.request_close();
82추가: if self.model.close != Close::Allowed {
83추가: ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
84추가: }
85추가: }
86추가: if self.model.close == Close::Allowed {
87추가: ctx.send_viewport_cmd(egui::ViewportCommand::Close);
88추가: }
89추가: egui::Panel::top("archive-actions").show(root, |ui| {
90추가: ui.horizontal_wrapped(|ui| {
91추가: ui.heading("Zipelo");
92추가: ui.add_enabled_ui(
93추가: !self.model.busy() && self.model.close == Close::Open,
94추가: |ui| {
95추가: if ui.button("파일 열기").clicked() {
96추가: self.open = true;
97추가: }
98추가: if ui.button("ZIP 만들기").clicked() {
99추가: self.create = true;
100추가: }
101추가: },
102추가: );
103추가: if ui
104추가: .add_enabled(self.model.busy(), egui::Button::new("취소 요청"))
105추가: .clicked()
106추가: {
107추가: self.password.clear();
108추가: self.model.cancel();
109추가: }
110추가: });
111추가: if self.fixture {
112추가: ui.colored_label(
113추가: egui::Color32::from_rgb(143, 69, 0),
114추가: "화면 시험 모드 / 파일을 읽거나 저장하지 않습니다",
115추가: );
116추가: }
117추가: });
118추가: egui::Panel::bottom("archive-status").show(root, |ui| {
119추가: ui.label(self.model.status());
120추가: if let Some((stage, done, total, entries)) =
121추가: self.model.progress.filter(|_| self.model.busy())
122추가: {
123추가: ui.label(format!(
124추가: "{} / {done}바이트 / {entries}개 처리",
125추가: stage_label(stage)
126추가: ));
127추가: if let Some(total) = total.filter(|n| *n > 0) {
128추가: ui.add(
129추가: egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
130추가: .show_percentage(),
131추가: );
132추가: } else if self.model.busy() {
133추가: ui.spinner();
134추가: }
135추가: }
136추가: if !self.model.busy() {
137추가: if let Some(t) = &self.model.terminal {
138추가: for line in terminal_lines(t) {
139추가: ui.label(line);
140추가: }
141추가: }
142추가: }
143추가: });
144추가: egui::CentralPanel::default_margins().show(root, |ui| {
145추가: if let Some(path) = &self.model.archive {
146추가: ui.heading(
147추가: path.file_name()
148추가: .unwrap_or(path.as_os_str())
149추가: .to_string_lossy(),
150추가: );
151추가: ui.label(path.display().to_string());
152추가: } else {
153추가: ui.heading("압축파일을 여기로 끌어 놓으세요");
154추가: }
155추가: if self.model.list_id.is_some() {
156추가: ui.add_enabled_ui(self.model.can_extract(), |ui| {
157추가: ui.horizontal_wrapped(|ui| {
158추가: ui.label("출력 폴더");
159추가: ui.text_edit_singleline(&mut self.destination);
160추가: });
161추가: if self
162추가: .model
163추가: .list_id
164추가: .as_ref()
165추가: .is_some_and(|id| id.format == Format::Gzip)
166추가: {
167추가: ui.horizontal(|ui| {
168추가: ui.label("출력 파일명");
169추가: ui.text_edit_singleline(&mut self.gzip_name);
170추가: });
171추가: }
172추가: ui.horizontal_wrapped(|ui| {
173추가: ui.checkbox(&mut self.selected_only, "선택한 항목만 풀기");
174추가: if ui.button("풀기").clicked() {
175추가: self.model.extract(
176추가: PathBuf::from(&self.destination),
177추가: self.selected_only,
178추가: self.model
179추가: .list_id
180추가: .as_ref()
181추가: .filter(|id| id.format == Format::Gzip)
182추가: .map(|_| self.gzip_name.clone()),
183추가: self.factory.as_mut(),
184추가: );
185추가: }
186추가: });
187추가: });
188추가: }
189추가: ui.separator();
190추가: egui::ScrollArea::both().show(ui, |ui| {
191추가: egui::Grid::new("archive-list")
192추가: .striped(true)
193추가: .min_col_width(90.0)
194추가: .show(ui, |ui| {
195추가: ui.label("선택");
196추가: ui.label("이름");
197추가: ui.label("크기");
198추가: ui.label("형식");
199추가: ui.label("암호");
200추가: ui.end_row();
201추가: for entry in &self.model.entries {
202추가: let mut selected = self.model.selected.contains(&entry.id);
203추가: if ui
204추가: .add_enabled(
205추가: !self.model.busy()
206추가: && matches!(entry.kind, Kind::File | Kind::Directory),
207추가: egui::Checkbox::without_text(&mut selected),
208추가: )
209추가: .on_hover_text(format!("{} 선택", entry.name))
210추가: .changed()
211추가: {
212추가: if selected {
213추가: self.model.selected.insert(entry.id);
214추가: } else {
215추가: self.model.selected.remove(&entry.id);
216추가: }
217추가: }
218추가: ui.label(&entry.name);
219추가: ui.label(
220추가: entry
221추가: .bytes
222추가: .map_or("알 수 없음".into(), |n| format!("{n} B")),
223추가: );
224추가: ui.label(match entry.kind {
225추가: Kind::File => "파일",
226추가: Kind::Directory => "폴더",
227추가: Kind::Link => "링크",
228추가: Kind::Other => "기타",
229추가: });
230추가: ui.label(if entry.encrypted { "있음" } else { "없음" });
231추가: ui.end_row();
232추가: }
233추가: });
234추가: if self.model.entries.is_empty() && self.model.list_id.is_some() {
235추가: ui.label("압축파일에 항목이 없습니다");
236추가: }
237추가: for (name, state) in &self.model.outputs {
238추가: ui.label(format!("{name}: {}", disposition_label(*state)));
239추가: }
240추가: });
241추가: });
242추가: if self.open {
243추가: egui::Window::new("파일 열기")
244추가: .collapsible(false)
245추가: .show(&ctx, |ui| {
246추가: ui.label("압축파일 절대 경로");
247추가: ui.text_edit_singleline(&mut self.open_text);
248추가: if ui.button("열기").clicked() {
249추가: self.open_path(self.open_text.clone().into());
250추가: self.open = false;
251추가: }
252추가: if ui.button("닫기").clicked() {
253추가: self.open = false;
254추가: }
255추가: });
256추가: }
257추가: if self.create {
258추가: egui::Window::new("ZIP 만들기")
259추가: .collapsible(false)
260추가: .show(&ctx, |ui| {
261추가: ui.add_enabled_ui(!self.model.busy(), |ui| {
262추가: ui.label("원본 파일 절대 경로 / 한 줄에 하나");
263추가: ui.add(egui::TextEdit::multiline(&mut self.sources).desired_rows(4));
264추가: ui.label("저장할 ZIP 절대 경로");
265추가: ui.text_edit_singleline(&mut self.zip_output);
266추가: ui.horizontal(|ui| {
267추가: ui.selectable_value(&mut self.method, Method::Deflate, "압축");
268추가: ui.selectable_value(&mut self.method, Method::Store, "묶기");
269추가: });
270추가: ui.label("암호 ZIP 생성은 작업자 지원 후 활성화됩니다");
271추가: if ui.button("ZIP 만들기").clicked() {
272추가: let sources = self
273추가: .sources
274추가: .lines()
275추가: .map(|s| {
276추가: let path = PathBuf::from(s);
277추가: let name = path
278추가: .file_name()
279추가: .and_then(|n| n.to_str())
280추가: .unwrap_or("")
281추가: .to_owned();
282추가: (path, name)
283추가: })
284추가: .collect();
285추가: if self.model.begin(
286추가: Start::CreateZip {
287추가: sources,
288추가: output_file: self.zip_output.clone().into(),
289추가: method: self.method,
290추가: aes256: false,
291추가: },
292추가: self.factory.as_mut(),
293추가: ) {
294추가: self.create = false;
295추가: }
296추가: }
297추가: });
298추가: if ui.button("닫기").clicked() {
299추가: self.create = false;
300추가: }
301추가: });
302추가: }
303추가: if let Some((_, attempt, encrypt)) = self.model.challenge {
304추가: egui::Window::new(if encrypt {
305추가: "ZIP 암호 설정"
306추가: } else {
307추가: "압축파일 암호"
308추가: })
309추가: .collapsible(false)
310추가: .show(&ctx, |ui| {
311추가: ui.label(format!("암호 입력 요청 {attempt}"));
312추가: let edit = ui.add(
313추가: egui::TextEdit::singleline(&mut self.password)
314추가: .password(true)
315추가: .char_limit(1024),
316추가: );
317추가: if ui.button("암호 전달").clicked()
318추가: || (edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)))
319추가: {
320추가: let text = std::mem::take(&mut self.password);
321추가: self.model.password(text);
322추가: }
323추가: if ui.button("작업 취소").clicked() {
324추가: self.password.clear();
325추가: self.model.cancel();
326추가: }
327추가: });
328추가: }
329추가: match self.model.close {
330추가: Close::Confirm => {
331추가: egui::Window::new("작업 중 닫기")
332추가: .collapsible(false)
333추가: .show(&ctx, |ui| {
334추가: ui.label("취소를 요청하고 작업자 종료를 기다릴까요?");
335추가: if ui.button("계속 열기").clicked() {
336추가: self.model.keep_open();
337추가: }
338추가: if ui.button("취소 후 기다리기").clicked() {
339추가: self.model.confirm_close();
340추가: }
341추가: });
342추가: }
343추가: Close::Waiting => {
344추가: egui::Window::new("종료 확인 중")
345추가: .collapsible(false)
346추가: .show(&ctx, |ui| {
347추가: ui.label("취소 결과와 프로세스 종료를 기다립니다");
348추가: if ui.button("닫기 철회").clicked() {
349추가: self.model.keep_open();
350추가: }
351추가: });
352추가: }
353추가: Close::Review => {
354추가: egui::Window::new("결과 확인 후 닫기")
355추가: .collapsible(false)
356추가: .show(&ctx, |ui| {
357추가: ui.label(self.model.status());
358추가: if let Some(t) = &self.model.terminal {
359추가: for line in terminal_lines(t) {
360추가: ui.label(line);
361추가: }
362추가: }
363추가: if ui.button("계속 열기").clicked() {
364추가: self.model.keep_open();
365추가: }
366추가: if ui.button("닫기").clicked() {
367추가: self.model.acknowledge_close();
368추가: }
369추가: });
370추가: }
371추가: _ => {}
372추가: }
373추가: if self.model.busy() {
374추가: ctx.request_repaint_after(std::time::Duration::from_millis(30));
375추가: }
376추가: }
377추가: }
378추가:
379추가: impl eframe::App for ArchiveApp {
380추가: fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
381추가: self.show(root);
382추가: }
383추가: }
추가experiments/rust-ui-memory-app/src/archive_ui.rs+812-0
@@ -0,0 +1,812 @@
1추가: use std::{collections::BTreeSet, path::PathBuf};
2추가:
3추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
4추가: pub enum Format {
5추가: Zip,
6추가: Tar,
7추가: Gzip,
8추가: TarGzip,
9추가: }
10추가: #[derive(Clone, Debug, Eq, PartialEq)]
11추가: pub enum SourceObject {
12추가: Unix { device: u64, inode: u64 },
13추가: Windows { volume: u64, file_id: [u8; 16] },
14추가: }
15추가: #[derive(Clone, Debug, Eq, PartialEq)]
16추가: pub struct ListId {
17추가: pub catalog_version: u16,
18추가: pub format: Format,
19추가: pub source_object: SourceObject,
20추가: pub archive_bytes: u64,
21추가: pub archive_sha256: [u8; 32],
22추가: }
23추가: #[derive(Clone, Debug, Eq, PartialEq)]
24추가: pub enum Selection {
25추가: All,
26추가: EntryIds(Vec<u32>),
27추가: }
28추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
29추가: pub enum Method {
30추가: Store,
31추가: Deflate,
32추가: }
33추가: #[derive(Clone, Debug, Eq, PartialEq)]
34추가: pub enum Start {
35추가: List {
36추가: archive: PathBuf,
37추가: },
38추가: Extract {
39추가: archive: PathBuf,
40추가: destination: PathBuf,
41추가: selection: Selection,
42추가: list_id: ListId,
43추가: gzip_output_name: Option<String>,
44추가: },
45추가: CreateZip {
46추가: sources: Vec<(PathBuf, String)>,
47추가: output_file: PathBuf,
48추가: method: Method,
49추가: aes256: bool,
50추가: },
51추가: }
52추가: // 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
53추가: pub struct Secret(Vec<u8>);
54추가: impl Secret {
55추가: pub fn new(text: String) -> Result<Self, &'static str> {
56추가: if text.is_empty() || text.len() > 1024 {
57추가: return Err("암호는 UTF-8 1~1024바이트로 입력하세요");
58추가: }
59추가: Ok(Self(text.into_bytes()))
60추가: }
61추가: pub fn as_bytes(&self) -> &[u8] {
62추가: &self.0
63추가: }
64추가: }
65추가: impl Drop for Secret {
66추가: fn drop(&mut self) {
67추가: self.0.fill(0);
68추가: }
69추가: }
70추가: pub enum Command {
71추가: Start(Start),
72추가: Password { challenge_id: u64, secret: Secret },
73추가: Cancel,
74추가: }
75추가: pub struct Request {
76추가: pub job_id: u64,
77추가: pub sequence: u64,
78추가: pub command: Command,
79추가: }
80추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
81추가: pub enum Kind {
82추가: File,
83추가: Directory,
84추가: Link,
85추가: Other,
86추가: }
87추가: #[derive(Clone, Debug, Eq, PartialEq)]
88추가: pub struct Entry {
89추가: pub id: u32,
90추가: pub name: String,
91추가: pub kind: Kind,
92추가: pub bytes: Option<u64>,
93추가: pub packed: Option<u64>,
94추가: pub encrypted: bool,
95추가: }
96추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
97추가: pub enum CancelStatus {
98추가: Requested,
99추가: AlreadyRequested,
100추가: TooLate,
101추가: Finished,
102추가: }
103추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
104추가: pub enum Stage {
105추가: Scan,
106추가: Read,
107추가: Decode,
108추가: Write,
109추가: Verify,
110추가: Commit,
111추가: }
112추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
113추가: pub enum Outcome {
114추가: Completed,
115추가: Failed,
116추가: Cancelled,
117추가: }
118추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
119추가: pub enum ErrorCode {
120추가: Integrity,
121추가: UnsupportedFormat,
122추가: UnsupportedFeature,
123추가: WrongPassword,
124추가: UnsafePath,
125추가: Conflict,
126추가: Limit,
127추가: Io,
128추가: Protocol,
129추가: Internal,
130추가: SourceChanged,
131추가: InvalidRequest,
132추가: }
133추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
134추가: pub enum Publication {
135추가: None,
136추가: Partial,
137추가: Complete,
138추가: Uncertain,
139추가: }
140추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
141추가: pub enum Durability {
142추가: NotApplicable,
143추가: Synced,
144추가: Unconfirmed,
145추가: Failed,
146추가: }
147추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
148추가: pub enum Cleanup {
149추가: Complete,
150추가: Failed,
151추가: Unconfirmed,
152추가: }
153추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)]
154추가: pub enum Disposition {
155추가: Created,
156추가: PartialRetained,
157추가: Removed,
158추가: CommitUncertain,
159추가: }
160추가: #[derive(Clone, Debug)]
161추가: pub struct Terminal {
162추가: pub outcome: Outcome,
163추가: pub error: Option<ErrorCode>,
164추가: pub publication: Publication,
165추가: pub created_count: u64,
166추가: pub retained_partial_count: u64,
167추가: pub durability: Durability,
168추가: pub cleanup: Cleanup,
169추가: }
170추가: #[derive(Clone, Debug)]
171추가: pub enum Event {
172추가: Accepted {
173추가: encryption: bool,
174추가: },
175추가: Entry(Entry),
176추가: ListEnd {
177추가: entry_count: u32,
178추가: list_id: ListId,
179추가: },
180추가: PasswordRequired {
181추가: challenge_id: u64,
182추가: attempt: u32,
183추가: encrypt: bool,
184추가: },
185추가: Progress {
186추가: stage: Stage,
187추가: processed: u64,
188추가: total: Option<u64>,
189추가: completed_entries: u64,
190추가: },
191추가: Output {
192추가: entry_id: Option<u32>,
193추가: relative_name: String,
194추가: disposition: Disposition,
195추가: },
196추가: CancelAck {
197추가: request_sequence: u64,
198추가: status: CancelStatus,
199추가: },
200추가: Terminal(Terminal),
201추가: }
202추가: pub enum HostEvent {
203추가: Fault(String),
204추가: CleanupComplete,
205추가: Frame {
206추가: job_id: u64,
207추가: sequence: u64,
208추가: event: Event,
209추가: },
210추가: StdoutEof,
211추가: StderrEof,
212추가: Exited {
213추가: success: bool,
214추가: },
215추가: }
216추가: // 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함.
217추가: // 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함.
218추가: pub trait Connection {
219추가: fn send(&mut self, request: Request) -> Result<(), String>;
220추가: fn poll(&mut self) -> Option<HostEvent>;
221추가: }
222추가: pub trait Factory {
223추가: fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
224추가: }
225추가: pub struct Unavailable;
226추가: impl Factory for Unavailable {
227추가: fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
228추가: Err("작업자 연결이 아직 준비되지 않았습니다".into())
229추가: }
230추가: }
231추가: struct Running {
232추가: id: u64,
233추가: outgoing: u64,
234추가: incoming: u64,
235추가: accepted: bool,
236추가: start_failed: bool,
237추가: start: Start,
238추가: connection: Box<dyn Connection>,
239추가: entries: Vec<Entry>,
240추가: list_end: Option<(u32, ListId)>,
241추가: stdout_eof: bool,
242추가: transport_closed: bool,
243추가: stderr_eof: bool,
244추가: exit: Option<bool>,
245추가: cancel_sequence: Option<u64>,
246추가: }
247추가: #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
248추가: pub enum Close {
249추가: #[default]
250추가: Open,
251추가: Confirm,
252추가: Waiting,
253추가: Review,
254추가: Allowed,
255추가: }
256추가: #[derive(Default)]
257추가: pub struct Model {
258추가: running: Option<Running>,
259추가: next_id: u64,
260추가: pub archive: Option<PathBuf>,
261추가: pub entries: Vec<Entry>,
262추가: pub list_id: Option<ListId>,
263추가: pub selected: BTreeSet<u32>,
264추가: pub terminal: Option<Terminal>,
265추가: pub challenge: Option<(u64, u32, bool)>,
266추가: pub progress: Option<(Stage, u64, Option<u64>, u64)>,
267추가: pub outputs: Vec<(String, Disposition)>,
268추가: pub cancel: Option<CancelStatus>,
269추가: pub error: Option<String>,
270추가: pub encryption: bool,
271추가: pub close: Close,
272추가: pub confirmed: bool,
273추가: }
274추가: impl Model {
275추가: pub fn busy(&self) -> bool {
276추가: self.running.is_some()
277추가: }
278추가: pub fn job_id(&self) -> Option<u64> {
279추가: self.running.as_ref().map(|r| r.id)
280추가: }
281추가: pub fn can_extract(&self) -> bool {
282추가: !self.busy()
283추가: && self.list_id.is_some()
284추가: && self.archive.is_some()
285추가: && self.close == Close::Open
286추가: }
287추가: pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
288추가: if self.busy() || self.close != Close::Open {
289추가: return false;
290추가: }
291추가: let validation = match &start {
292추가: Start::List { archive } => archive.is_absolute(),
293추가: Start::Extract {
294추가: archive,
295추가: destination,
296추가: selection,
297추가: gzip_output_name,
298추가: list_id,
299추가: } => {
300추가: archive.is_absolute()
301추가: && destination.is_absolute()
302추가: && self.archive.as_ref() == Some(archive)
303추가: && self.list_id.as_ref() == Some(list_id)
304추가: && match list_id.format {
305추가: Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
306추가: _ => gzip_output_name.is_none(),
307추가: }
308추가: && match selection {
309추가: Selection::All => true,
310추가: Selection::EntryIds(ids) => {
311추가: !ids.is_empty()
312추가: && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
313추가: && ids.iter().all(|id| {
314추가: self.entries.iter().any(|e| {
315추가: e.id == *id
316추가: && matches!(e.kind, Kind::File | Kind::Directory)
317추가: })
318추가: })
319추가: }
320추가: }
321추가: }
322추가: Start::CreateZip {
323추가: sources,
324추가: output_file,
325추가: aes256,
326추가: ..
327추가: } => {
328추가: !sources.is_empty()
329추가: && output_file.is_absolute()
330추가: && (!aes256 || self.encryption)
331추가: && sources
332추가: .iter()
333추가: .all(|(p, n)| p.is_absolute() && valid_relative(n))
334추가: }
335추가: };
336추가: if !validation {
337추가: self.error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
338추가: return false;
339추가: }
340추가: let Some(id) = self.next_id.checked_add(1) else {
341추가: self.error = Some("작업 ID 한도에 도달했습니다".into());
342추가: return false;
343추가: };
344추가: let mut connection = match factory.connect(id) {
345추가: Ok(c) => c,
346추가: Err(e) => {
347추가: self.error = Some(e);
348추가: return false;
349추가: }
350추가: };
351추가: let send_error = connection
352추가: .send(Request {
353추가: job_id: id,
354추가: sequence: 0,
355추가: command: Command::Start(start.clone()),
356추가: })
357추가: .err();
358추가: let started = send_error.is_none();
359추가: if let Start::List { archive } = &start
360추가: && started
361추가: {
362추가: self.archive = Some(archive.clone());
363추가: self.list_id = None;
364추가: self.entries.clear();
365추가: self.selected.clear();
366추가: }
367추가: self.next_id = id;
368추가: self.terminal = None;
369추가: self.challenge = None;
370추가: self.progress = None;
371추가: self.outputs.clear();
372추가: self.cancel = None;
373추가: self.error = send_error;
374추가: self.confirmed = false;
375추가: self.running = Some(Running {
376추가: id,
377추가: outgoing: 1,
378추가: incoming: 0,
379추가: accepted: false,
380추가: start_failed: !started,
381추가: start,
382추가: connection,
383추가: entries: Vec::new(),
384추가: list_end: None,
385추가: stdout_eof: false,
386추가: transport_closed: false,
387추가: stderr_eof: false,
388추가: exit: None,
389추가: cancel_sequence: None,
390추가: });
391추가: started
392추가: }
393추가: pub fn extract(
394추가: &mut self,
395추가: destination: PathBuf,
396추가: selected_only: bool,
397추가: gzip_output_name: Option<String>,
398추가: factory: &mut dyn Factory,
399추가: ) -> bool {
400추가: if !self.can_extract() {
401추가: return false;
402추가: }
403추가: self.begin(
404추가: Start::Extract {
405추가: archive: self.archive.clone().unwrap(),
406추가: destination,
407추가: selection: if selected_only {
408추가: Selection::EntryIds(self.selected.iter().copied().collect())
409추가: } else {
410추가: Selection::All
411추가: },
412추가: list_id: self.list_id.clone().unwrap(),
413추가: gzip_output_name,
414추가: },
415추가: factory,
416추가: )
417추가: }
418추가: pub fn password(&mut self, text: String) -> bool {
419추가: let Some((challenge_id, _, _)) = self.challenge else {
420추가: return false;
421추가: };
422추가: let secret = match Secret::new(text) {
423추가: Ok(s) => s,
424추가: Err(e) => {
425추가: self.error = Some(e.into());
426추가: return false;
427추가: }
428추가: };
429추가: if self
430추가: .send(Command::Password {
431추가: challenge_id,
432추가: secret,
433추가: })
434추가: .is_some()
435추가: {
436추가: self.challenge = None;
437추가: self.error = None;
438추가: true
439추가: } else {
440추가: false
441추가: }
442추가: }
443추가: fn send(&mut self, command: Command) -> Option<u64> {
444추가: let run = self.running.as_mut()?;
445추가: if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
446추가: return None;
447추가: }
448추가: let seq = run.outgoing;
449추가: let Some(next) = seq.checked_add(1) else {
450추가: self.error = Some("요청 순서 한도 초과".into());
451추가: return None;
452추가: };
453추가: match run.connection.send(Request {
454추가: job_id: run.id,
455추가: sequence: seq,
456추가: command,
457추가: }) {
458추가: Ok(()) => {
459추가: run.outgoing = next;
460추가: Some(seq)
461추가: }
462추가: Err(e) => {
463추가: self.error = Some(e);
464추가: None
465추가: }
466추가: }
467추가: }
468추가: pub fn cancel(&mut self) {
469추가: if self
470추가: .running
471추가: .as_ref()
472추가: .is_some_and(|r| r.cancel_sequence.is_none())
473추가: {
474추가: if let Some(seq) = self.send(Command::Cancel) {
475추가: self.running.as_mut().unwrap().cancel_sequence = Some(seq);
476추가: self.challenge = None;
477추가: }
478추가: }
479추가: }
480추가: pub fn request_close(&mut self) {
481추가: if self.close == Close::Open {
482추가: self.close = if self.busy() {
483추가: Close::Confirm
484추가: } else {
485추가: Close::Review
486추가: };
487추가: }
488추가: }
489추가: pub fn confirm_close(&mut self) {
490추가: if self.close == Close::Confirm {
491추가: self.cancel();
492추가: self.close = if self.busy() {
493추가: Close::Waiting
494추가: } else {
495추가: Close::Review
496추가: };
497추가: }
498추가: }
499추가: pub fn keep_open(&mut self) {
500추가: if self.close != Close::Allowed {
501추가: self.close = Close::Open;
502추가: }
503추가: }
504추가: pub fn acknowledge_close(&mut self) {
505추가: if !self.busy() && self.close == Close::Review {
506추가: self.close = Close::Allowed;
507추가: }
508추가: }
509추가: pub fn poll(&mut self) {
510추가: for _ in 0..128 {
511추가: let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
512추가: break;
513추가: };
514추가: self.receive(event);
515추가: }
516추가: let complete = self.running.as_ref().is_some_and(|r| {
517추가: r.exit.is_some()
518추가: && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
519추가: });
520추가: if complete {
521추가: let run = self.running.take().unwrap();
522추가: self.confirmed =
523추가: self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
524추가: if !self.confirmed {
525추가: self.error.get_or_insert(
526추가: "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
527추가: );
528추가: }
529추가: if self.confirmed
530추가: && self
531추가: .terminal
532추가: .as_ref()
533추가: .is_some_and(|t| t.outcome == Outcome::Completed)
534추가: {
535추가: if matches!(run.start, Start::List { .. }) {
536추가: if let Some((count, id)) = run
537추가: .list_end
538추가: .filter(|(n, _)| *n as usize == run.entries.len())
539추가: {
540추가: let _ = count;
541추가: self.entries = run.entries;
542추가: self.list_id = Some(id);
543추가: } else {
544추가: self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
545추가: self.confirmed = false;
546추가: }
547추가: }
548추가: }
549추가: if self
550추가: .terminal
551추가: .as_ref()
552추가: .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
553추가: {
554추가: self.list_id = None;
555추가: self.selected.clear();
556추가: }
557추가: self.challenge = None;
558추가: if matches!(self.close, Close::Waiting | Close::Confirm) {
559추가: self.close = Close::Review;
560추가: }
561추가: }
562추가: }
563추가: fn receive(&mut self, host: HostEvent) {
564추가: let run = self.running.as_mut().unwrap();
565추가: match host {
566추가: HostEvent::Fault(message) => self.error = Some(message),
567추가: HostEvent::CleanupComplete => run.transport_closed = true,
568추가: HostEvent::StdoutEof => run.stdout_eof = true,
569추가: HostEvent::StderrEof => run.stderr_eof = true,
570추가: HostEvent::Exited { success } => run.exit = Some(success),
571추가: HostEvent::Frame {
572추가: job_id,
573추가: sequence,
574추가: event,
575추가: } => {
576추가: if job_id != run.id
577추가: || sequence != run.incoming
578추가: || self.terminal.is_some()
579추가: || run.stdout_eof
580추가: || sequence >= 1_000_000
581추가: {
582추가: self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
583추가: return;
584추가: }
585추가: run.incoming += 1;
586추가: if !run.accepted && !matches!(event, Event::Accepted { .. }) {
587추가: self.error = Some("작업 승인 응답이 없습니다".into());
588추가: return;
589추가: }
590추가: match event {
591추가: Event::Accepted { encryption } => {
592추가: if run.accepted {
593추가: self.error = Some("작업 승인 중복".into());
594추가: }
595추가: run.accepted = true;
596추가: self.encryption = encryption;
597추가: }
598추가: Event::Entry(entry) => {
599추가: if !matches!(run.start, Start::List { .. })
600추가: || run.list_end.is_some()
601추가: || entry.id as usize != run.entries.len()
602추가: || entry.name.len() > 4096
603추가: || run.entries.len() >= 100_000
604추가: {
605추가: self.error = Some("목록 응답이 유효하지 않습니다".into());
606추가: } else {
607추가: run.entries.push(entry);
608추가: }
609추가: }
610추가: Event::ListEnd {
611추가: entry_count,
612추가: list_id,
613추가: } => {
614추가: if !matches!(run.start, Start::List { .. })
615추가: || run.list_end.is_some()
616추가: || list_id.catalog_version != 1
617추가: {
618추가: self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
619추가: } else {
620추가: run.list_end = Some((entry_count, list_id));
621추가: }
622추가: }
623추가: Event::PasswordRequired {
624추가: challenge_id,
625추가: attempt,
626추가: encrypt,
627추가: } => {
628추가: if self.challenge.is_some() || challenge_id == 0 {
629추가: self.error = Some("암호 요청이 유효하지 않습니다".into());
630추가: } else {
631추가: self.challenge = Some((challenge_id, attempt, encrypt));
632추가: }
633추가: }
634추가: Event::Progress {
635추가: stage,
636추가: processed,
637추가: total,
638추가: completed_entries,
639추가: } => self.progress = Some((stage, processed, total, completed_entries)),
640추가: Event::Output {
641추가: relative_name,
642추가: disposition,
643추가: ..
644추가: } => {
645추가: if self.outputs.len() < 100_000 && relative_name.len() <= 4096 {
646추가: self.outputs.push((relative_name, disposition));
647추가: } else {
648추가: self.error = Some("출력 보고 한도 초과".into());
649추가: }
650추가: }
651추가: Event::CancelAck {
652추가: request_sequence,
653추가: status,
654추가: } => {
655추가: if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
656추가: self.cancel = Some(status);
657추가: } else {
658추가: self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
659추가: }
660추가: }
661추가: Event::Terminal(t) => {
662추가: self.challenge = None;
663추가: self.terminal = Some(t);
664추가: }
665추가: }
666추가: }
667추가: }
668추가: }
669추가: pub fn status(&self) -> String {
670추가: if let Some(error) = &self.error {
671추가: return error.clone();
672추가: }
673추가: if self.busy() {
674추가: if self.terminal.is_some() {
675추가: return "작업 결과 수신 / 프로세스 종료 확인 중".into();
676추가: }
677추가: if self.challenge.is_some() {
678추가: return "암호를 입력하세요".into();
679추가: }
680추가: if let Some(c) = self.cancel {
681추가: return match c {
682추가: CancelStatus::Requested | CancelStatus::AlreadyRequested => {
683추가: "취소 요청 접수 / 최종 결과 대기"
684추가: }
685추가: CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
686추가: CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
687추가: }
688추가: .into();
689추가: }
690추가: if self
691추가: .running
692추가: .as_ref()
693추가: .is_some_and(|r| r.cancel_sequence.is_some())
694추가: {
695추가: return "취소 요청 전송 / 최종 결과 대기".into();
696추가: }
697추가: return "작업 중".into();
698추가: }
699추가: match self
700추가: .terminal
701추가: .as_ref()
702추가: .filter(|_| self.confirmed)
703추가: .map(|t| t.outcome)
704추가: {
705추가: Some(Outcome::Completed) => "작업 완료",
706추가: Some(Outcome::Cancelled) => "작업 취소됨",
707추가: Some(Outcome::Failed) => "작업 실패",
708추가: None => "압축파일을 열거나 ZIP 파일을 만드세요",
709추가: }
710추가: .into()
711추가: }
712추가: }
713추가: pub fn valid_leaf(name: &str) -> bool {
714추가: valid_relative(name) && !name.contains('/') && !name.contains('\\')
715추가: }
716추가: pub fn valid_relative(name: &str) -> bool {
717추가: !name.is_empty()
718추가: && !name.contains('\0')
719추가: && !name.contains(':')
720추가: && !name.starts_with('/')
721추가: && !name.starts_with('\\')
722추가: && name
723추가: .split(['/', '\\'])
724추가: .all(|p| !p.is_empty() && p != "." && p != "..")
725추가: }
726추가:
727추가: // 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
728추가: pub fn launch_args(
729추가: args: Vec<std::ffi::OsString>,
730추가: cwd: PathBuf,
731추가: ) -> Result<(bool, Option<PathBuf>), &'static str> {
732추가: let fixture = args.iter().any(|arg| arg == "--ui-fixture");
733추가: let paths = args
734추가: .into_iter()
735추가: .filter(|arg| arg != "--ui-fixture")
736추가: .collect::<Vec<_>>();
737추가: if paths.len() > 1 {
738추가: return Err("압축파일 하나를 지정하세요");
739추가: }
740추가: let path = paths
741추가: .into_iter()
742추가: .next()
743추가: .map(PathBuf::from)
744추가: .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
745추가: Ok((fixture, path))
746추가: }
747추가:
748추가: pub fn stage_label(stage: Stage) -> &'static str {
749추가: match stage {
750추가: Stage::Scan => "목록 읽는 중",
751추가: Stage::Read => "파일 읽는 중",
752추가: Stage::Decode => "압축 푸는 중",
753추가: Stage::Write => "파일 쓰는 중",
754추가: Stage::Verify => "검증 중",
755추가: Stage::Commit => "저장 마무리 중",
756추가: }
757추가: }
758추가: pub fn disposition_label(disposition: Disposition) -> &'static str {
759추가: match disposition {
760추가: Disposition::Created => "생성됨",
761추가: Disposition::PartialRetained => "일부 파일 남음",
762추가: Disposition::Removed => "작업 임시 파일 정리됨",
763추가: Disposition::CommitUncertain => "저장 여부 불확실",
764추가: }
765추가: }
766추가: pub fn terminal_lines(t: &Terminal) -> Vec<String> {
767추가: let publication = match t.publication {
768추가: Publication::None => "게시된 파일 없음",
769추가: Publication::Partial => "일부 파일 게시됨",
770추가: Publication::Complete => "파일 게시 완료",
771추가: Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
772추가: };
773추가: let durability = match t.durability {
774추가: Durability::NotApplicable => "동기화 해당 없음",
775추가: Durability::Synced => "디스크 동기화 완료",
776추가: Durability::Unconfirmed => "디스크 동기화 미확인",
777추가: Durability::Failed => "디스크 동기화 실패",
778추가: };
779추가: let cleanup = match t.cleanup {
780추가: Cleanup::Complete => "작업 임시 파일 정리 완료",
781추가: Cleanup::Failed => "작업 임시 파일 정리 실패",
782추가: Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
783추가: };
784추가: let mut lines = vec![
785추가: publication.into(),
786추가: format!(
787추가: "생성 {}개 / 남은 임시 파일 {}개",
788추가: t.created_count, t.retained_partial_count
789추가: ),
790추가: format!("{durability} / {cleanup}"),
791추가: ];
792추가: if let Some(error) = t.error {
793추가: lines.push(
794추가: match error {
795추가: ErrorCode::Integrity => "압축파일이 손상됐습니다",
796추가: ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
797추가: ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
798추가: ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
799추가: ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
800추가: ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
801추가: ErrorCode::Limit => "처리 한도를 초과했습니다",
802추가: ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다",
803추가: ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
804추가: ErrorCode::Internal => "작업자 처리 오류입니다",
805추가: ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
806추가: ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
807추가: }
808추가: .into(),
809추가: );
810추가: }
811추가: lines
812추가: }
추가experiments/rust-ui-memory-app/src/desktop.rs+71-0
@@ -0,0 +1,71 @@
1추가: #[cfg(feature = "ui-fixture")]
2추가: #[path = "../../../tests/rust-app-ui/fake.rs"]
3추가: mod fake;
4추가: #[path = "system_font.rs"]
5추가: mod system_font;
6추가: use eframe::egui::{self, Color32, FontData, FontDefinitions, FontFamily, FontId, TextStyle};
7추가: fn main() -> eframe::Result {
8추가: let font = system_font::load().map_err(|e| eframe::Error::AppCreation(Box::new(e)))?;
9추가: eframe::run_native(
10추가: "Zipelo",
11추가: eframe::NativeOptions {
12추가: renderer: eframe::Renderer::Glow,
13추가: viewport: egui::ViewportBuilder::default()
14추가: .with_inner_size([1060.0, 720.0])
15추가: .with_min_inner_size([760.0, 540.0]),
16추가: ..Default::default()
17추가: },
18추가: Box::new(move |cc| {
19추가: let mut fonts = FontDefinitions::empty();
20추가: let mut data = FontData::from_owned(font.bytes);
21추가: data.index = font.face_index;
22추가: fonts.font_data.insert("noto-kr".into(), data.into());
23추가: fonts
24추가: .families
25추가: .insert(FontFamily::Proportional, vec!["noto-kr".into()]);
26추가: cc.egui_ctx.set_fonts(fonts);
27추가: cc.egui_ctx.set_visuals(egui::Visuals::light());
28추가: cc.egui_ctx.style_mut_of(egui::Theme::Light, |style| {
29추가: style
30추가: .text_styles
31추가: .insert(TextStyle::Body, FontId::proportional(18.0));
32추가: style
33추가: .text_styles
34추가: .insert(TextStyle::Button, FontId::proportional(18.0));
35추가: style
36추가: .text_styles
37추가: .insert(TextStyle::Heading, FontId::proportional(26.0));
38추가: style.visuals.panel_fill = Color32::WHITE;
39추가: style.visuals.override_text_color = Some(Color32::from_rgb(24, 39, 57));
40추가: style.visuals.selection.bg_fill = Color32::from_rgb(211, 230, 246);
41추가: style.spacing.item_spacing = egui::vec2(12.0, 10.0);
42추가: style.spacing.button_padding = egui::vec2(14.0, 10.0);
43추가: });
44추가: let (fixture, startup) = zipelo_ui_memory_app::archive_ui::launch_args(
45추가: std::env::args_os().skip(1).collect(),
46추가: std::env::current_dir()?,
47추가: )
48추가: .map_err(std::io::Error::other)?;
49추가: let factory: Box<dyn zipelo_ui_memory_app::archive_ui::Factory> = if fixture {
50추가: #[cfg(feature = "ui-fixture")]
51추가: {
52추가: Box::new(fake::FakeFactory::default())
53추가: }
54추가: #[cfg(not(feature = "ui-fixture"))]
55추가: {
56추가: return Err(Box::new(std::io::Error::other(
57추가: "ui-fixture feature가 필요합니다",
58추가: )));
59추가: }
60추가: } else {
61추가: Box::new(
62추가: zipelo_ui_memory_app::archive_process::ProcessFactory::sibling()
63추가: .map_err(std::io::Error::other)?,
64추가: )
65추가: };
66추가: Ok(Box::new(
67추가: zipelo_ui_memory_app::archive_screen::ArchiveApp::new(factory, startup, fixture),
68추가: ))
69추가: }),
70추가: )
71추가: }
수정experiments/rust-ui-memory-app/src/lib.rs+7-0
@@ -4,3 +4,10 @@ pub use core_memory as core;
44pub mod controller;
55pub mod runtime;
66pub mod transport;
7추가:
8추가: pub mod archive_ui;
9추가:
10추가: #[cfg(feature = "ui")]
11추가: pub mod archive_screen;
12추가:
13추가: pub mod archive_process;
추가tests/rust-app-real-worker/.gitignore+1-0
@@ -0,0 +1 @@
1추가: runs/
추가tests/rust-app-real-worker/Cargo.lock+107-0
@@ -0,0 +1,107 @@
1추가: # This file is automatically @generated by Cargo.
2추가: # It is not intended for manual editing.
3추가: version = 4
4추가:
5추가: [[package]]
6추가: name = "block-buffer"
7추가: version = "0.10.4"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
10추가: dependencies = [
11추가: "generic-array",
12추가: ]
13추가:
14추가: [[package]]
15추가: name = "cfg-if"
16추가: version = "1.0.5"
17추가: source = "registry+https://github.com/rust-lang/crates.io-index"
18추가: checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
19추가:
20추가: [[package]]
21추가: name = "cpufeatures"
22추가: version = "0.2.17"
23추가: source = "registry+https://github.com/rust-lang/crates.io-index"
24추가: checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
25추가: dependencies = [
26추가: "libc",
27추가: ]
28추가:
29추가: [[package]]
30추가: name = "crypto-common"
31추가: version = "0.1.7"
32추가: source = "registry+https://github.com/rust-lang/crates.io-index"
33추가: checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
34추가: dependencies = [
35추가: "generic-array",
36추가: "typenum",
37추가: ]
38추가:
39추가: [[package]]
40추가: name = "digest"
41추가: version = "0.10.7"
42추가: source = "registry+https://github.com/rust-lang/crates.io-index"
43추가: checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
44추가: dependencies = [
45추가: "block-buffer",
46추가: "crypto-common",
47추가: ]
48추가:
49추가: [[package]]
50추가: name = "generic-array"
51추가: version = "0.14.7"
52추가: source = "registry+https://github.com/rust-lang/crates.io-index"
53추가: checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
54추가: dependencies = [
55추가: "typenum",
56추가: "version_check",
57추가: ]
58추가:
59추가: [[package]]
60추가: name = "libc"
61추가: version = "0.2.191"
62추가: source = "registry+https://github.com/rust-lang/crates.io-index"
63추가: checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
64추가:
65추가: [[package]]
66추가: name = "sha2"
67추가: version = "0.10.9"
68추가: source = "registry+https://github.com/rust-lang/crates.io-index"
69추가: checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
70추가: dependencies = [
71추가: "cfg-if",
72추가: "cpufeatures",
73추가: "digest",
74추가: ]
75추가:
76추가: [[package]]
77추가: name = "typenum"
78추가: version = "1.20.1"
79추가: source = "registry+https://github.com/rust-lang/crates.io-index"
80추가: checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
81추가:
82추가: [[package]]
83추가: name = "version_check"
84추가: version = "0.9.5"
85추가: source = "registry+https://github.com/rust-lang/crates.io-index"
86추가: checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
87추가:
88추가: [[package]]
89추가: name = "zipelo-archive-worker"
90추가: version = "0.1.0"
91추가: dependencies = [
92추가: "sha2",
93추가: "zlib-rs",
94추가: ]
95추가:
96추가: [[package]]
97추가: name = "zipelo-real-worker-probe"
98추가: version = "0.1.0"
99추가: dependencies = [
100추가: "zipelo-archive-worker",
101추가: ]
102추가:
103추가: [[package]]
104추가: name = "zlib-rs"
105추가: version = "0.6.8"
106추가: source = "registry+https://github.com/rust-lang/crates.io-index"
107추가: checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
추가tests/rust-app-real-worker/Cargo.toml+19-0
@@ -0,0 +1,19 @@
1추가: [package]
2추가: name = "zipelo-real-worker-probe"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: rust-version = "1.99"
6추가: license = "MIT"
7추가: publish = false
8추가: autotests = false
9추가:
10추가: [workspace]
11추가:
12추가: [dependencies]
13추가: worker_protocol = { package = "zipelo-archive-worker", path = "../../experiments/rust-archive-worker" }
14추가:
15추가: [[bin]]
16추가: name = "zipelo-real-worker-probe"
17추가: path = "probe.rs"
18추가: test = false
19추가: bench = false
추가tests/rust-app-real-worker/README.md+50-0
@@ -0,0 +1,50 @@
1추가: # 실제 작업자와 화면 연결 시험
2추가:
3추가: 기본 앱은 실행 파일과 같은 폴더의 zipelo-archive-worker(Windows는 .exe)를 실행함.
4추가: PATH나 현재 작업 폴더에서 임의 작업자를 검색하지 않음. ui-fixture와 --ui-fixture가
5추가: 모두 지정된 경우에만 기존 가짜 작업자를 사용함.
6추가:
7추가: 클라이언트는 작업자 crate의 protocol과 wire codec을 재사용하며 압축 처리와 파일 접근은
8추가: 별도 작업자 프로세스에서 수행함. UI에서 파이프 쓰기를 기다리지 않도록 8프레임 요청 큐와
9추가: 64이벤트 응답 큐를 사용함. 파이프 입출력과 child wait는 백그라운드에서 처리함.
10추가: 정상 종료에는 Terminal, 양쪽 EOF와 child wait를 모두 확인함. 통신 오류는 성공으로
11추가: 표시하지 않으며, 오류 경로에서는 child 회수와 모든 파이프 스레드/핸들 정리가 끝났다는
12추가: 명시적 완료 신호까지 확인함. 연결이 예외적으로 폐기돼도 소유한 자식을 종료하고 회수함.
13추가: 310초 제한 시간을 넘긴 작업자도 종료와 회수를 시도하며 완료 여부가 불명확하면 닫기를 허용하지 않음.
14추가:
15추가: ## 실행
16추가:
17추가: 저장소 루트에서 로컬 실행기를 사용하면 실제 작업자와 probe 빌드가 화면 시험보다 먼저 수행됨.
18추가:
19추가: ```sh
20추가: python3 tests/ci/run_rust.py local
21추가: ```
22추가:
23추가: 단독 시험에서는 같은 target 디렉터리에 먼저 두 실행 파일을 빌드할 것.
24추가:
25추가: ```sh
26추가: export CARGO_TARGET_DIR="$PWD/tests/ci/target"
27추가: cargo +1.99.1 build --locked --manifest-path experiments/rust-archive-worker/Cargo.toml
28추가: cargo +1.99.1 build --locked --manifest-path tests/rust-app-real-worker/Cargo.toml
29추가: cargo +1.99.1 test --locked --all-features --manifest-path experiments/rust-ui-memory-app/Cargo.toml --test real_worker
30추가: ```
31추가:
32추가: 기본 앱의 직접 실행도 같은 target 디렉터리를 사용할 것.
33추가:
34추가: ```sh
35추가: cargo +1.99.1 run --locked --manifest-path experiments/rust-ui-memory-app/Cargo.toml --features ui -- /absolute/sample.zip
36추가: ```
37추가:
38추가: ## 확인 범위
39추가:
40추가: - 합성 ZIP과 TAR.GZ를 실제 파일 열기 위젯으로 열고 목록을 확인한 뒤 풀기 버튼으로 해제함.
41추가: - ZIP 만들기 위젯으로 합성 파일을 압축하고, 결과를 다시 열고 풀어 바이트가 같은지 확인함.
42추가: - 위 세 흐름은 실제 작업자 EXE와 OS 파이프를 사용하며 Terminal, 양쪽 EOF, child wait와 연결 정리 순서를 관측함.
43추가: - 누락된 작업자, 잘린 프레임, 잘못된 action 승인, Terminal 없는 조기 종료를 오류로 처리함.
44추가: - 첫 Start 직렬화 실패도 실제 작업자 회수까지 대기함. Linux에서는 실행 중인 probe 연결을 폐기한 후 /proc에서 소유 자식이 사라진 것도 확인함.
45추가: - flows.rs의 창은 egui Context에서 실제 위젯에 포인터와 키보드 이벤트를 전달함. 네이티브 OS 창/입력 자동화나 Windows 실행 검증은 아님.
46추가:
47추가: fixtures/는 generate.py의 Python 표준 라이브러리로 생성한 작은 합성 입력임.
48추가: 정상 흐름은 제품 작업자를 사용하고, probe.rs는 통신 실패와 생명주기 시험 전용임.
49추가: 사용자 자료를 읽거나 출력하지 않으며 모든 시험 출력은 이 폴더의 runs/ 안에만 생성함.
50추가: 암호 ZIP, 대용량 성능, OS sandbox, 악성 파일 전체 검증과 Windows 실기는 이 시험의 범위 밖임.
추가tests/rust-app-real-worker/fixtures/sample.tar.gz

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-app-real-worker/fixtures/sample.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-app-real-worker/flows.rs+471-0
@@ -0,0 +1,471 @@
1추가: use std::{
2추가: cell::RefCell,
3추가: fs,
4추가: path::{Path, PathBuf},
5추가: rc::Rc,
6추가: sync::atomic::{AtomicU64, Ordering},
7추가: time::{Duration, Instant},
8추가: };
9추가: use zipelo_ui_memory_app::{archive_process::ProcessFactory, archive_ui::*};
10추가: static NEXT: AtomicU64 = AtomicU64::new(0);
11추가: struct Scratch(PathBuf);
12추가: impl Scratch {
13추가: fn new() -> Self {
14추가: let root =
15추가: Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-app-real-worker/runs");
16추가: fs::create_dir_all(&root).unwrap();
17추가: let path = root.join(format!(
18추가: "{}-{}",
19추가: std::process::id(),
20추가: NEXT.fetch_add(1, Ordering::Relaxed)
21추가: ));
22추가: Self(make_directory(&path))
23추가: }
24추가: fn path(&self, name: &str) -> PathBuf {
25추가: self.0.join(name)
26추가: }
27추가: }
28추가: impl Drop for Scratch {
29추가: fn drop(&mut self) {
30추가: fs::remove_dir_all(&self.0).unwrap();
31추가: }
32추가: }
33추가: fn make_directory(path: &Path) -> PathBuf {
34추가: let mut builder = fs::DirBuilder::new();
35추가: #[cfg(unix)]
36추가: {
37추가: use std::os::unix::fs::DirBuilderExt;
38추가: builder.mode(0o700);
39추가: }
40추가: builder.create(path).unwrap();
41추가: path.canonicalize().unwrap()
42추가: }
43추가: fn binary(name: &str) -> PathBuf {
44추가: let current = std::env::current_exe().unwrap();
45추가: let path = current
46추가: .parent()
47추가: .unwrap()
48추가: .parent()
49추가: .unwrap()
50추가: .join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
51추가: assert!(
52추가: path.is_file(),
53추가: "실제 작업자와 시험 probe를 먼저 빌드해야 함: {}",
54추가: path.display()
55추가: );
56추가: path
57추가: }
58추가: #[derive(Default)]
59추가: struct Observation {
60추가: jobs: Vec<Vec<&'static str>>,
61추가: }
62추가: struct ObservedFactory {
63추가: process: ProcessFactory,
64추가: observed: Rc<RefCell<Observation>>,
65추가: }
66추가: struct ObservedConnection {
67추가: connection: Box<dyn Connection>,
68추가: index: usize,
69추가: observed: Rc<RefCell<Observation>>,
70추가: }
71추가: impl Factory for ObservedFactory {
72추가: fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
73추가: let connection = self.process.connect(job)?;
74추가: let index = self.observed.borrow().jobs.len();
75추가: self.observed.borrow_mut().jobs.push(Vec::new());
76추가: Ok(Box::new(ObservedConnection {
77추가: connection,
78추가: index,
79추가: observed: self.observed.clone(),
80추가: }))
81추가: }
82추가: }
83추가: impl Connection for ObservedConnection {
84추가: fn send(&mut self, request: Request) -> Result<(), String> {
85추가: self.connection.send(request)
86추가: }
87추가: fn poll(&mut self) -> Option<HostEvent> {
88추가: let event = self.connection.poll()?;
89추가: let label = match &event {
90추가: HostEvent::StdoutEof => "stdout",
91추가: HostEvent::StderrEof => "stderr",
92추가: HostEvent::Exited { .. } => "wait",
93추가: HostEvent::CleanupComplete => "cleanup",
94추가: HostEvent::Fault(_) => "fault",
95추가: HostEvent::Frame {
96추가: event: Event::Terminal(_),
97추가: ..
98추가: } => "terminal",
99추가: _ => "frame",
100추가: };
101추가: self.observed.borrow_mut().jobs[self.index].push(label);
102추가: Some(event)
103추가: }
104추가: }
105추가: impl Drop for ObservedConnection {
106추가: fn drop(&mut self) {
107추가: self.observed.borrow_mut().jobs[self.index].push("drop");
108추가: }
109추가: }
110추가: fn observed_factory() -> (ObservedFactory, Rc<RefCell<Observation>>) {
111추가: let observed = Rc::new(RefCell::new(Observation::default()));
112추가: (
113추가: ObservedFactory {
114추가: process: ProcessFactory::new(binary("zipelo-archive-worker")),
115추가: observed: observed.clone(),
116추가: },
117추가: observed,
118추가: )
119추가: }
120추가: fn assert_reaped(observed: &Rc<RefCell<Observation>>) {
121추가: for events in &observed.borrow().jobs {
122추가: for label in ["terminal", "stdout", "stderr", "cleanup", "wait", "drop"] {
123추가: assert_eq!(
124추가: events.iter().filter(|value| **value == label).count(),
125추가: 1,
126추가: "{events:?}"
127추가: );
128추가: }
129추가: assert!(!events.contains(&"fault"));
130추가: assert_eq!(&events[events.len() - 2..], &["wait", "drop"]);
131추가: }
132추가: }
133추가: fn wait(model: &mut Model) {
134추가: let deadline = Instant::now() + Duration::from_secs(10);
135추가: while model.busy() {
136추가: model.poll();
137추가: assert!(
138추가: Instant::now() < deadline,
139추가: "작업자 종료 시간 초과: {}",
140추가: model.status()
141추가: );
142추가: std::thread::sleep(Duration::from_millis(2));
143추가: }
144추가: }
145추가: fn completed(model: &Model) {
146추가: assert!(model.confirmed, "{}", model.status());
147추가: assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
148추가: }
149추가: #[cfg(feature = "ui")]
150추가: mod screen {
151추가: use super::*;
152추가: use eframe::egui::{self, epaint::Shape};
153추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
154추가: struct Screen {
155추가: context: egui::Context,
156추가: app: ArchiveApp,
157추가: }
158추가: impl Screen {
159추가: fn new(factory: ObservedFactory) -> Self {
160추가: Self {
161추가: context: egui::Context::default(),
162추가: app: ArchiveApp::new(Box::new(factory), None, false),
163추가: }
164추가: }
165추가: fn render(&mut self, events: Vec<egui::Event>) -> Vec<(String, egui::Pos2)> {
166추가: fn text(shape: &Shape, output: &mut Vec<(String, egui::Pos2)>) {
167추가: match shape {
168추가: Shape::Text(value) => output.push((
169추가: value.galley.job.text.clone(),
170추가: value.pos + value.galley.rect.size() / 2.0,
171추가: )),
172추가: Shape::Vec(values) => {
173추가: for value in values {
174추가: text(value, output);
175추가: }
176추가: }
177추가: _ => {}
178추가: }
179추가: }
180추가: let mut frame = self.context.run_ui(
181추가: egui::RawInput {
182추가: screen_rect: Some(egui::Rect::from_min_size(
183추가: egui::Pos2::ZERO,
184추가: egui::vec2(1060.0, 720.0),
185추가: )),
186추가: events,
187추가: ..Default::default()
188추가: },
189추가: |ui| self.app.show(ui),
190추가: );
191추가: frame.textures_delta.clear();
192추가: let mut output = Vec::new();
193추가: for shape in frame.shapes {
194추가: text(&shape.shape, &mut output);
195추가: }
196추가: output
197추가: }
198추가: fn locate(&mut self, label: &str) -> egui::Pos2 {
199추가: self.render(vec![]);
200추가: self.render(vec![])
201추가: .into_iter()
202추가: .filter(|(text, _)| text == label)
203추가: .max_by(|a, b| a.1.y.total_cmp(&b.1.y))
204추가: .unwrap_or_else(|| panic!("화면 항목 누락: {label}"))
205추가: .1
206추가: }
207추가: fn click_at(&mut self, point: egui::Pos2) {
208추가: self.render(vec![
209추가: egui::Event::PointerMoved(point),
210추가: egui::Event::PointerButton {
211추가: pos: point,
212추가: button: egui::PointerButton::Primary,
213추가: pressed: true,
214추가: modifiers: Default::default(),
215추가: },
216추가: ]);
217추가: self.render(vec![egui::Event::PointerButton {
218추가: pos: point,
219추가: button: egui::PointerButton::Primary,
220추가: pressed: false,
221추가: modifiers: Default::default(),
222추가: }]);
223추가: }
224추가: fn click(&mut self, label: &str) {
225추가: let point = self.locate(label);
226추가: self.click_at(point);
227추가: }
228추가: fn fill(&mut self, label: &str, offset: egui::Vec2, value: &Path) {
229추가: let point = self.locate(label) + offset;
230추가: self.click_at(point);
231추가: self.render(vec![
232추가: egui::Event::Key {
233추가: key: egui::Key::A,
234추가: physical_key: None,
235추가: pressed: true,
236추가: repeat: false,
237추가: modifiers: egui::Modifiers::COMMAND,
238추가: },
239추가: egui::Event::Text(value.to_str().unwrap().to_string()),
240추가: ]);
241추가: }
242추가: fn settle(&mut self) {
243추가: let deadline = Instant::now() + Duration::from_secs(10);
244추가: while self.app.model.busy() {
245추가: self.render(vec![]);
246추가: assert!(Instant::now() < deadline, "{}", self.app.model.status());
247추가: std::thread::sleep(Duration::from_millis(2));
248추가: }
249추가: completed(&self.app.model);
250추가: }
251추가: fn open(&mut self, archive: &Path) {
252추가: self.click("파일 열기");
253추가: self.fill("압축파일 절대 경로", egui::vec2(0.0, 22.0), archive);
254추가: self.click("열기");
255추가: assert!(self.app.model.busy());
256추가: self.settle();
257추가: }
258추가: fn extract(&mut self, destination: &Path) {
259추가: self.fill("출력 폴더", egui::vec2(100.0, 0.0), destination);
260추가: self.click("풀기");
261추가: assert!(self.app.model.busy());
262추가: self.settle();
263추가: assert_eq!(
264추가: self.app.model.terminal.as_ref().unwrap().publication,
265추가: Publication::Complete
266추가: );
267추가: }
268추가: }
269추가: fn archive_flow(name: &str, format: Format) {
270추가: let scratch = Scratch::new();
271추가: let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
272추가: .join("../../tests/rust-app-real-worker/fixtures")
273추가: .join(name);
274추가: let archive = scratch.path(name);
275추가: fs::copy(fixture, &archive).unwrap();
276추가: let original = fs::read(&archive).unwrap();
277추가: let output = make_directory(&scratch.path("output"));
278추가: let (factory, observed) = observed_factory();
279추가: let mut screen = Screen::new(factory);
280추가: screen.open(&archive);
281추가: assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, format);
282추가: assert_eq!(screen.app.model.entries[0].name, "content.txt");
283추가: screen.extract(&output);
284추가: assert_eq!(
285추가: fs::read(output.join("content.txt")).unwrap(),
286추가: b"Zipelo real worker flow\n"
287추가: );
288추가: assert_eq!(fs::read(archive).unwrap(), original);
289추가: assert_eq!(observed.borrow().jobs.len(), 2);
290추가: assert_reaped(&observed);
291추가: }
292추가: #[test]
293추가: fn zip_open_and_extract_via_actual_widgets_and_worker() {
294추가: archive_flow("sample.zip", Format::Zip);
295추가: }
296추가: #[test]
297추가: fn targz_open_and_extract_via_actual_widgets_and_worker() {
298추가: archive_flow("sample.tar.gz", Format::TarGzip);
299추가: }
300추가: #[test]
301추가: fn create_zip_reopen_and_extract_via_actual_widgets_and_worker() {
302추가: let scratch = Scratch::new();
303추가: let source = scratch.path("one.txt");
304추가: fs::write(&source, b"ZIP creation through real worker\n").unwrap();
305추가: let archive = scratch.path("new.zip");
306추가: let output = make_directory(&scratch.path("output"));
307추가: let (factory, observed) = observed_factory();
308추가: let mut screen = Screen::new(factory);
309추가: screen.click("ZIP 만들기");
310추가: screen.fill(
311추가: "원본 파일 절대 경로 / 한 줄에 하나",
312추가: egui::vec2(0.0, 25.0),
313추가: &source,
314추가: );
315추가: screen.fill("저장할 ZIP 절대 경로", egui::vec2(0.0, 22.0), &archive);
316추가: screen.click("ZIP 만들기");
317추가: assert!(screen.app.model.busy());
318추가: screen.settle();
319추가: assert!(archive.is_file());
320추가: screen.open(&archive);
321추가: assert_eq!(screen.app.model.entries[0].name, "one.txt");
322추가: screen.extract(&output);
323추가: assert_eq!(
324추가: fs::read(output.join("one.txt")).unwrap(),
325추가: fs::read(source).unwrap()
326추가: );
327추가: assert_eq!(observed.borrow().jobs.len(), 3);
328추가: assert_reaped(&observed);
329추가: }
330추가: }
331추가: #[test]
332추가: fn missing_worker_is_an_error_without_a_fake_result() {
333추가: let scratch = Scratch::new();
334추가: let mut factory = ProcessFactory::new(scratch.path("not-installed"));
335추가: let mut model = Model::default();
336추가: assert!(!model.begin(
337추가: Start::List {
338추가: archive: scratch.path("sample.zip")
339추가: },
340추가: &mut factory
341추가: ));
342추가: assert!(!model.busy());
343추가: assert!(model.error.is_some());
344추가: assert!(!model.confirmed);
345추가: }
346추가: #[test]
347추가: fn broken_or_incomplete_worker_output_is_not_success() {
348추가: for name in ["truncated", "wrong-action", "early-exit"] {
349추가: let scratch = Scratch::new();
350추가: let probe = scratch.path(&format!("{name}{}", std::env::consts::EXE_SUFFIX));
351추가: fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
352추가: let mut factory = ProcessFactory::new(probe);
353추가: let mut model = Model::default();
354추가: assert!(model.begin(
355추가: Start::List {
356추가: archive: scratch.path("sample.zip")
357추가: },
358추가: &mut factory
359추가: ));
360추가: model.request_close();
361추가: model.confirm_close();
362추가: assert_eq!(model.close, Close::Waiting);
363추가: wait(&mut model);
364추가: assert!(!model.confirmed);
365추가: assert!(model.error.is_some());
366추가: assert_eq!(model.close, Close::Review);
367추가: model.acknowledge_close();
368추가: assert_eq!(model.close, Close::Allowed);
369추가: }
370추가: }
371추가: #[cfg(target_os = "linux")]
372추가: #[test]
373추가: fn dropping_live_connection_kills_and_reaps_owned_child() {
374추가: let scratch = Scratch::new();
375추가: let probe = scratch.path("hang");
376추가: fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
377추가: let mut factory = ProcessFactory::new(probe);
378추가: let mut model = Model::default();
379추가: assert!(model.begin(
380추가: Start::List {
381추가: archive: scratch.path("sample.zip")
382추가: },
383추가: &mut factory
384추가: ));
385추가: let deadline = Instant::now() + Duration::from_secs(5);
386추가: while !scratch.path("probe.pid").exists() {
387추가: assert!(Instant::now() < deadline);
388추가: std::thread::sleep(Duration::from_millis(2));
389추가: }
390추가: let pid = fs::read_to_string(scratch.path("probe.pid")).unwrap();
391추가: drop(model);
392추가: assert!(!Path::new("/proc").join(pid).exists());
393추가: }
394추가:
395추가: #[test]
396추가: fn failed_start_serialization_reaps_the_real_worker_without_terminal() {
397추가: let scratch = Scratch::new();
398추가: let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
399추가: let mut model = Model::default();
400추가: let archive = scratch.path(&"a".repeat(40000));
401추가: assert!(!model.begin(Start::List { archive }, &mut factory));
402추가: assert!(model.busy());
403추가: model.request_close();
404추가: model.confirm_close();
405추가: assert_eq!(model.close, Close::Waiting);
406추가: wait(&mut model);
407추가: assert!(!model.confirmed);
408추가: assert!(model.terminal.is_none());
409추가: assert!(model.error.is_some());
410추가: assert_eq!(model.close, Close::Review);
411추가: }
412추가:
413추가: #[test]
414추가: fn late_cancel_after_child_reap_keeps_the_original_terminal_result() {
415추가: let scratch = Scratch::new();
416추가: let archive = scratch.path("sample.zip");
417추가: fs::copy(
418추가: Path::new(env!("CARGO_MANIFEST_DIR"))
419추가: .join("../../tests/rust-app-real-worker/fixtures/sample.zip"),
420추가: &archive,
421추가: )
422추가: .unwrap();
423추가: let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
424추가: let mut connection = factory.connect(1).unwrap();
425추가: connection
426추가: .send(Request {
427추가: job_id: 1,
428추가: sequence: 0,
429추가: command: Command::Start(Start::List { archive }),
430추가: })
431추가: .unwrap();
432추가: let deadline = Instant::now() + Duration::from_secs(10);
433추가: let mut terminal = false;
434추가: loop {
435추가: assert!(Instant::now() < deadline);
436추가: match connection.poll() {
437추가: Some(HostEvent::CleanupComplete) => break,
438추가: Some(HostEvent::Frame {
439추가: event: Event::Terminal(value),
440추가: ..
441추가: }) => {
442추가: assert_eq!(value.outcome, Outcome::Completed);
443추가: terminal = true;
444추가: }
445추가: Some(HostEvent::Fault(message)) => panic!("{message}"),
446추가: _ => std::thread::sleep(Duration::from_millis(1)),
447추가: }
448추가: }
449추가: assert!(terminal);
450추가: assert!(
451추가: connection
452추가: .send(Request {
453추가: job_id: 1,
454추가: sequence: 1,
455추가: command: Command::Cancel
456추가: })
457추가: .is_ok()
458추가: );
459추가: loop {
460추가: assert!(Instant::now() < deadline);
461추가: match connection.poll() {
462추가: Some(HostEvent::Exited { success }) => {
463추가: assert!(success);
464추가: break;
465추가: }
466추가: Some(HostEvent::Fault(message)) => panic!("{message}"),
467추가: _ => std::thread::sleep(Duration::from_millis(1)),
468추가: }
469추가: }
470추가: assert!(connection.poll().is_none());
471추가: }
추가tests/rust-app-real-worker/generate.py+24-0
@@ -0,0 +1,24 @@
1추가: import gzip
2추가: from io import BytesIO
3추가: from pathlib import Path
4추가: import tarfile
5추가: import zipfile
6추가:
7추가: ROOT = Path(__file__).resolve().parent / "fixtures"
8추가: PAYLOAD = b"Zipelo real worker flow\n"
9추가: ROOT.mkdir(exist_ok=True)
10추가: stream = BytesIO()
11추가: with zipfile.ZipFile(stream, "w") as archive:
12추가: info = zipfile.ZipInfo("content.txt", (1980, 1, 1, 0, 0, 0))
13추가: info.compress_type = zipfile.ZIP_DEFLATED
14추가: archive.writestr(info, PAYLOAD)
15추가: (ROOT / "sample.zip").write_bytes(stream.getvalue())
16추가: stream = BytesIO()
17추가: with tarfile.open(fileobj=stream, mode="w", format=tarfile.USTAR_FORMAT) as archive:
18추가: info = tarfile.TarInfo("content.txt")
19추가: info.size = len(PAYLOAD)
20추가: info.mode = 0o600
21추가: archive.addfile(info, BytesIO(PAYLOAD))
22추가: compressed = bytearray(gzip.compress(stream.getvalue(), mtime=0))
23추가: compressed[9] = 255
24추가: (ROOT / "sample.tar.gz").write_bytes(compressed)
추가tests/rust-app-real-worker/probe.rs+29-0
@@ -0,0 +1,29 @@
1추가: use std::{io::Write, path::PathBuf, time::Duration};
2추가: use worker_protocol::{
3추가: protocol::*,
4추가: wire::{Reader, Writer},
5추가: };
6추가:
7추가: fn main() {
8추가: let executable = PathBuf::from(std::env::args_os().next().unwrap());
9추가: let mode = executable.file_stem().unwrap().to_string_lossy();
10추가: if mode.starts_with("hang") {
11추가: let parent = executable.parent().unwrap();
12추가: std::fs::write(parent.join("probe.pid.tmp"), std::process::id().to_string()).unwrap();
13추가: std::fs::rename(parent.join("probe.pid.tmp"), parent.join("probe.pid")).unwrap();
14추가: std::thread::sleep(Duration::from_secs(30));
15추가: return;
16추가: }
17추가: let mut reader = Reader::new(std::io::stdin());
18추가: let (job, _, _) = reader.read().unwrap().unwrap();
19추가: if mode.starts_with("wrong-action") {
20추가: Writer::new(std::io::stdout(), job)
21추가: .send(&Message::Accepted {
22추가: action: ActionKind::Extract,
23추가: encryption: false,
24추가: })
25추가: .unwrap();
26추가: } else if !mode.starts_with("early-exit") {
27추가: std::io::stdout().write_all(b"ZAW1").unwrap();
28추가: }
29추가: }
추가tests/rust-app-ui/.gitignore+3-0
@@ -0,0 +1,3 @@
1추가: screens/
2추가: screens-*/
3추가: __pycache__/
추가tests/rust-app-ui/README.md+19-0
@@ -0,0 +1,19 @@
1추가: # 앱 화면 흐름 시험
2추가:
3추가: 가짜 작업자는 계약 revision 2의 의미를 따르는 프론트엔드 어댑터임. 바이너리 codec, 실제 프로세스 실행, 파일 읽기와 쓰기, 암호 해독은 수행하지 않음. 실제 codec은 backend 소유이며 이 PR에서 중복 구현하지 않음.
4추가:
5추가: `python3 tests/ci/run_rust.py local`은 기존 시험과 새 `archive_ui` 시험을 all-features로 실행함. Windows 결과는 교차 빌드이며 Windows 실제 실행은 별도 확인해야 함.
6추가:
7추가: 화면 직접 확인:
8추가:
9추가: ```sh
10추가: cargo +1.99.1 run --locked --manifest-path experiments/rust-ui-memory-app/Cargo.toml --features ui-fixture -- --ui-fixture /absolute/example.zip
11추가: ```
12추가:
13추가: `locked.zip` 이름은 가짜 암호 요청을 만듦. 아무 비어 있지 않은 합성 암호를 받으며 암호를 기록하거나 저장하지 않음. 실제 암호나 사용자 자료를 입력할 필요가 없음. 시험 모드는 화면에 명시되고 실제 파일을 만들지 않음. `ui-fixture` 없이 실행하면 앱과 같은 폴더의 실제 zipelo-archive-worker를 실행함. Windows에서는 .exe 확장자를 사용함. 작업자가 누락되면 오류를 표시하며 가짜 성공으로 대체하지 않음. 실제 작업자 연결 시험은 ../rust-app-real-worker/README.md를 참고할 것.
14추가:
15추가: 범위는 목록 확인, 선택 해제, GZ 출력명, ZIP 생성, 암호 요청, 진행률, 취소와 닫기 철회, Terminal/EOF/child wait 분리, 오래된 ID/sequence 거부, SourceChanged 재열람, 부분 출력과 불확실 게시 보존임. 구성한 이벤트 시험은 실제 OS 종료나 파일 보안 검증의 증거가 아님.
16추가:
17추가: 디자인은 흰 바탕 #FFFFFF, 글자 #182739, 선택 #D3E6F6, 강조 #174C7C를 사용함. 기존 한글 시스템 폰트와 본문/버튼 18px, 제목 26px를 유지함. 상단 작업 버튼, 가운데 파일 목록, 하단 진행/결과의 왼쪽 정렬 구조이며 작은 부가 설명, 장식 카드와 새 아이콘을 추가하지 않음.
18추가:
19추가: 풀기 버튼은 raw GZ에만 출력명을 보내며 ZIP/TAR/TAR.GZ에는 None을 보냄. 모델과 가짜 작업자도 이 계약을 검증함. Start 전송 실패 시에는 연결을 보존하고 추가 요청을 막으며, 양쪽 EOF와 child wait가 모두 올 때까지 교체와 닫기를 허용하지 않음. 이때 Terminal이 없어도 종료 후 오류 확인 화면으로 이동하며 성공으로 표시하지 않음.
추가tests/rust-app-ui/fake.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-ui/native_smoke.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-ui/regressions.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-ui/validation.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기