| 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 | } |