team-ljyzipelo

공개
930줄32 KB
1use super::*;
2use sha2::{Digest, Sha256};
3use std::{
4 io::Read,
5 process::{Child, ChildStdin},
6 sync::mpsc,
7 time::{Duration, Instant},
8};
9
10struct Running(Child);
11impl Drop for Running {
12 fn drop(&mut self) {
13 let _ = self.0.kill();
14 let _ = self.0.wait();
15 }
16}
17fn directory(s: &Scratch, name: &str) {
18 let path = s.0.join(name);
19 fs::create_dir_all(&path).unwrap();
20 #[cfg(unix)]
21 {
22 use std::os::unix::fs::PermissionsExt;
23 let mut current = path.as_path();
24 while current != s.0 {
25 fs::set_permissions(current, fs::Permissions::from_mode(0o700)).unwrap();
26 current = current.parent().unwrap();
27 }
28 }
29}
30fn request(s: &Scratch) -> Start {
31 Start {
32 action: Action::Extract {
33 archive: s.path("input"),
34 destination: s.path("output"),
35 selection: Selection::All,
36 list_id: None,
37 gzip_output_name: None,
38 },
39 limits: Limits::default(),
40 }
41}
42fn fixture(s: &Scratch, names: &[&str]) {
43 let members = names
44 .iter()
45 .enumerate()
46 .map(|(id, name)| archive::Member {
47 entry: Entry {
48 entry_id: id as u32,
49 name: (*name).into(),
50 kind: EntryKind::File,
51 size: PAYLOAD.len() as u64,
52 compressed_size: PAYLOAD.len() as u64,
53 encrypted: false,
54 },
55 data: PAYLOAD.to_vec(),
56 })
57 .collect::<Vec<_>>();
58 let zip =
59 archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())).unwrap();
60 fs::write(s.0.join("input"), zip).unwrap();
61 directory(s, "output");
62 #[cfg(unix)]
63 {
64 use std::os::unix::fs::PermissionsExt;
65 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
66 }
67 for name in names {
68 let path = s.0.join("output").join(name);
69 directory(
70 s,
71 path.parent()
72 .unwrap()
73 .strip_prefix(&s.0)
74 .unwrap()
75 .to_str()
76 .unwrap(),
77 );
78 fs::write(path, b"original").unwrap();
79 }
80}
81fn reply(id: u64, choice: ConflictChoice, apply: bool) -> Message {
82 Message::ConflictReply {
83 challenge_id: id,
84 choice,
85 apply_to_remaining: apply,
86 }
87}
88fn run(
89 s: &Scratch,
90 start: Start,
91 fault: Option<&str>,
92 initial: Vec<Message>,
93 mut respond: impl FnMut(&Message) -> Option<Vec<Message>>,
94) -> Vec<Message> {
95 let mut command = s.worker();
96 command
97 .stdin(Stdio::piped())
98 .stdout(Stdio::piped())
99 .stderr(Stdio::piped());
100 #[cfg(target_os = "linux")]
101 if let Some(fault) = fault {
102 let shim = s.0.join("io_fault.so");
103 assert!(
104 Command::new("cc")
105 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
106 .arg(
107 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
108 .join("../../tests/rust-archive-worker/io_fault.c")
109 )
110 .arg("-ldl")
111 .arg("-o")
112 .arg(&shim)
113 .status()
114 .unwrap()
115 .success()
116 );
117 command
118 .env("LD_PRELOAD", shim)
119 .env("ZIPELO_TEST_FAULT", fault)
120 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
121 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
122 }
123 #[cfg(not(target_os = "linux"))]
124 assert!(fault.is_none());
125 let mut child = Running(command.spawn().unwrap());
126 let mut writer: Option<Writer<ChildStdin>> =
127 Some(Writer::new(child.0.stdin.take().unwrap(), 17));
128 writer
129 .as_mut()
130 .unwrap()
131 .send(&Message::StartInteractive(start))
132 .unwrap();
133 for message in initial {
134 writer.as_mut().unwrap().send(&message).unwrap();
135 }
136 let stdout = child.0.stdout.take().unwrap();
137 let mut stderr = child.0.stderr.take().unwrap();
138 let errors = std::thread::spawn(move || {
139 let mut bytes = Vec::new();
140 stderr.read_to_end(&mut bytes).unwrap();
141 bytes
142 });
143 let (send, receive) = mpsc::channel();
144 let reader = std::thread::spawn(move || {
145 let mut reader = Reader::new(stdout);
146 loop {
147 let frame = reader.read();
148 let done = !matches!(frame, Ok(Some(_)));
149 if send.send(frame).is_err() || done {
150 break;
151 }
152 }
153 });
154 let mut events = Vec::new();
155 loop {
156 let Some((job, _, event)) = receive
157 .recv_timeout(Duration::from_secs(15))
158 .expect("worker response timeout")
159 .unwrap()
160 else {
161 break;
162 };
163 assert_eq!(job, 17);
164 if let Some(commands) = respond(&event) {
165 if commands.is_empty() {
166 writer = None;
167 } else {
168 for command in commands {
169 writer.as_mut().unwrap().send(&command).unwrap();
170 }
171 }
172 }
173 let done = matches!(event, Message::Terminal(_));
174 events.push(event);
175 if done {
176 writer = None;
177 }
178 }
179 assert!(child.0.wait().unwrap().success(), "{events:?}");
180 reader.join().unwrap();
181 assert!(errors.join().unwrap().is_empty());
182 assert!(matches!(events.last(), Some(Message::Terminal(_))));
183 events
184}
185fn choose(s: &Scratch, choice: ConflictChoice, apply: bool) -> Vec<Message> {
186 run(s, request(s), None, vec![], |event| match event {
187 Message::ConflictRequired { challenge_id, .. } => {
188 Some(vec![reply(*challenge_id, choice, apply)])
189 }
190 _ => None,
191 })
192}
193fn count(events: &[Message], predicate: impl Fn(&Message) -> bool) -> usize {
194 events.iter().filter(|event| predicate(event)).count()
195}
196fn questions(events: &[Message]) -> usize {
197 count(events, |e| matches!(e, Message::ConflictRequired { .. }))
198}
199fn created(events: &[Message]) -> usize {
200 count(events, |e| {
201 matches!(
202 e,
203 Message::Output {
204 disposition: Disposition::Created,
205 ..
206 }
207 )
208 })
209}
210fn hash(path: &std::path::Path) -> Vec<u8> {
211 Sha256::digest(fs::read(path).unwrap()).to_vec()
212}
213
214#[test]
215fn three_choices_and_apply_remaining_report_every_entry() {
216 for choice in [
217 ConflictChoice::Overwrite,
218 ConflictChoice::Skip,
219 ConflictChoice::Rename,
220 ] {
221 for apply in [false, true] {
222 let s = Scratch::new();
223 fixture(&s, &["a.txt", "b.txt"]);
224 let before = hash(&s.0.join("output/a.txt"));
225 let events = choose(&s, choice, apply);
226 let t = terminal(&events);
227 assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
228 assert_eq!(questions(&events), if apply { 1 } else { 2 });
229 assert_eq!(
230 count(&events, |e| matches!(e, Message::ConflictResolved { .. })),
231 2
232 );
233 for name in ["a", "b"] {
234 let original = s.0.join(format!("output/{name}.txt"));
235 if choice == ConflictChoice::Overwrite {
236 assert_eq!(fs::read(original).unwrap(), PAYLOAD);
237 } else {
238 assert_eq!(hash(&original), before);
239 }
240 if choice == ConflictChoice::Rename {
241 assert_eq!(
242 fs::read(s.0.join(format!("output/{name} (1).txt"))).unwrap(),
243 PAYLOAD
244 );
245 }
246 }
247 let skipped = choice == ConflictChoice::Skip;
248 assert_eq!(t.created_count, if skipped { 0 } else { 2 });
249 assert_eq!(created(&events), t.created_count as usize);
250 assert_eq!(
251 t.publication,
252 if skipped {
253 Publication::None
254 } else {
255 Publication::Complete
256 }
257 );
258 assert_eq!(t.cleanup, Cleanup::Complete);
259 if skipped {
260 assert_eq!(t.durability, Durability::NotApplicable);
261 }
262 assert_eq!(
263 fs::read_dir(s.0.join("output")).unwrap().count(),
264 if choice == ConflictChoice::Rename {
265 4
266 } else {
267 2
268 }
269 );
270 }
271 }
272}
273#[test]
274fn rename_avoids_existing_names_and_later_archive_paths() {
275 let s = Scratch::new();
276 fixture(&s, &["폴더/자료.txt", "폴더/자료 (1).txt"]);
277 fs::write(s.0.join("output/폴더/자료 (2).txt"), b"keep").unwrap();
278 let events = choose(&s, ConflictChoice::Rename, true);
279 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
280 assert_eq!(
281 fs::read(s.0.join("output/폴더/자료 (3).txt")).unwrap(),
282 PAYLOAD
283 );
284 assert_eq!(
285 fs::read(s.0.join("output/폴더/자료 (1) (1).txt")).unwrap(),
286 PAYLOAD
287 );
288 assert_eq!(
289 fs::read(s.0.join("output/폴더/자료 (2).txt")).unwrap(),
290 b"keep"
291 );
292}
293#[test]
294fn mixed_choices_and_non_conflicting_files() {
295 let s = Scratch::new();
296 fixture(&s, &["a", "b", "c", "new"]);
297 fs::remove_file(s.0.join("output/new")).unwrap();
298 let mut index = 0;
299 let events = run(&s, request(&s), None, vec![], |event| match event {
300 Message::ConflictRequired {
301 challenge_id,
302 incoming_size,
303 existing_size,
304 ..
305 } => {
306 assert_eq!(*incoming_size, PAYLOAD.len() as u64);
307 assert_eq!(*existing_size, 8);
308 let choice = [
309 ConflictChoice::Overwrite,
310 ConflictChoice::Skip,
311 ConflictChoice::Rename,
312 ][index];
313 index += 1;
314 Some(vec![reply(*challenge_id, choice, false)])
315 }
316 _ => None,
317 });
318 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
319 assert_eq!(terminal(&events).created_count, 3);
320 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD);
321 assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original");
322 assert_eq!(fs::read(s.0.join("output/c (1)")).unwrap(), PAYLOAD);
323 assert_eq!(fs::read(s.0.join("output/new")).unwrap(), PAYLOAD);
324}
325#[test]
326fn cancel_waiting_for_choice_preserves_originals() {
327 let s = Scratch::new();
328 fixture(&s, &["a"]);
329 let before = hash(&s.0.join("output/a"));
330 let events = run(&s, request(&s), None, vec![], |e| {
331 matches!(e, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel])
332 });
333 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
334 assert_eq!(terminal(&events).publication, Publication::None);
335 assert_eq!(created(&events), 0);
336 assert_eq!(hash(&s.0.join("output/a")), before);
337 assert!(events.iter().any(|e| matches!(
338 e,
339 Message::CancelAck {
340 status: CancelStatus::Requested,
341 ..
342 }
343 )));
344}
345#[test]
346fn cancellation_keeps_earlier_replacement() {
347 let s = Scratch::new();
348 fixture(&s, &["a", "b"]);
349 let events = run(&s, request(&s), None, vec![], |e| match e {
350 Message::ConflictRequired {
351 challenge_id,
352 entry_id: 0,
353 ..
354 } => Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)]),
355 Message::ConflictRequired { .. } => Some(vec![Message::Cancel]),
356 _ => None,
357 });
358 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
359 assert_eq!(terminal(&events).publication, Publication::Partial);
360 assert_eq!(terminal(&events).created_count, 1);
361 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD);
362 assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original");
363}
364#[test]
365fn eof_stale_duplicate_and_wrong_kind_replies_fail_protocol() {
366 for mode in 0..4 {
367 let s = Scratch::new();
368 fixture(&s, &["a", "b"]);
369 let events = run(&s, request(&s), None, vec![], |e| match e {
370 Message::ConflictRequired { challenge_id, .. } => Some(match mode {
371 0 => vec![],
372 1 => vec![reply(challenge_id + 1, ConflictChoice::Skip, false)],
373 2 => vec![
374 reply(*challenge_id, ConflictChoice::Skip, false),
375 reply(*challenge_id, ConflictChoice::Skip, false),
376 ],
377 _ => vec![Message::Password {
378 challenge_id: *challenge_id,
379 secret: Secret(vec![]),
380 }],
381 }),
382 _ => None,
383 });
384 assert_eq!(
385 terminal(&events).error,
386 ErrorCode::Protocol,
387 "{mode}: {events:?}"
388 );
389 assert_eq!(created(&events), 0);
390 }
391}
392#[test]
393fn premature_reply_is_rejected() {
394 let s = Scratch::new();
395 fixture(&s, &["a"]);
396 let events = run(
397 &s,
398 request(&s),
399 None,
400 vec![reply(999, ConflictChoice::Skip, true)],
401 |_| None,
402 );
403 assert_eq!(terminal(&events).error, ErrorCode::Protocol, "{events:?}");
404 assert_eq!(created(&events), 0);
405}
406#[test]
407fn password_and_conflict_share_distinct_challenges() {
408 let s = Scratch::new();
409 fs::write(s.0.join("input"), AES_ZIP).unwrap();
410 directory(&s, "output");
411 fs::write(s.0.join("output/payload.bin"), b"original").unwrap();
412 let mut password_id = None;
413 let events = run(&s, request(&s), None, vec![], |e| match e {
414 Message::PasswordRequired { challenge_id, .. } => {
415 password_id = Some(*challenge_id);
416 Some(password_reply(*challenge_id, TEST_PASSWORD))
417 }
418 Message::ConflictRequired { challenge_id, .. } => {
419 assert_ne!(Some(*challenge_id), password_id);
420 Some(vec![reply(*challenge_id, ConflictChoice::Skip, false)])
421 }
422 _ => None,
423 });
424 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
425 assert_eq!(questions(&events), 1);
426 assert_eq!(created(&events), 0);
427}
428#[test]
429fn legacy_start_still_aborts_and_policy_does_not_cross_jobs() {
430 let s = Scratch::new();
431 fixture(&s, &["a", "b"]);
432 assert_eq!(terminal(&execute(request(&s))).error, ErrorCode::Conflict);
433 assert_eq!(questions(&choose(&s, ConflictChoice::Skip, true)), 1);
434 assert_eq!(questions(&choose(&s, ConflictChoice::Skip, false)), 2);
435}
436#[test]
437fn corruption_is_rejected_before_any_question_or_output() {
438 let s = Scratch::new();
439 fixture(&s, &["a"]);
440 let mut bytes = fs::read(s.0.join("input")).unwrap();
441 let at = bytes
442 .windows(PAYLOAD.len())
443 .position(|b| b == PAYLOAD)
444 .unwrap();
445 bytes[at] ^= 1;
446 fs::write(s.0.join("input"), bytes).unwrap();
447 let events = run(&s, request(&s), None, vec![], |_| None);
448 assert_eq!(terminal(&events).error, ErrorCode::Integrity, "{events:?}");
449 assert_eq!(questions(&events), 0);
450 assert_eq!(created(&events), 0);
451}
452#[test]
453fn raw_gzip_conflicts_use_explicit_name() {
454 let s = Scratch::new();
455 fixture(&s, &["chosen.txt"]);
456 fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap();
457 let mut start = request(&s);
458 if let Action::Extract {
459 gzip_output_name, ..
460 } = &mut start.action
461 {
462 *gzip_output_name = Some("chosen.txt".into());
463 }
464 let events = run(&s, start, None, vec![], |e| match e {
465 Message::ConflictRequired {
466 challenge_id,
467 relative_name,
468 ..
469 } => {
470 assert_eq!(relative_name, "chosen.txt");
471 Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)])
472 }
473 _ => None,
474 });
475 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
476 assert_eq!(fs::read(s.0.join("output/chosen.txt")).unwrap(), PAYLOAD);
477}
478#[test]
479fn file_directory_collisions_are_rejected_before_questions() {
480 for path in ["a", "parent"] {
481 let s = Scratch::new();
482 fixture(&s, &[if path == "a" { "a" } else { "parent/a" }]);
483 let target = s.0.join("output").join(path);
484 if path == "a" {
485 fs::remove_file(&target).unwrap();
486 fs::create_dir(&target).unwrap();
487 } else {
488 fs::remove_dir_all(&target).unwrap();
489 fs::write(&target, b"keep").unwrap();
490 }
491 let events = run(&s, request(&s), None, vec![], |_| None);
492 assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
493 assert_eq!(questions(&events), 0);
494 assert_eq!(created(&events), 0);
495 }
496}
497#[test]
498fn newly_created_empty_directory_is_counted_when_files_are_skipped() {
499 let s = Scratch::new();
500 directory(&s, "empty");
501 fs::write(s.0.join("source"), PAYLOAD).unwrap();
502 let events = execute(Start {
503 action: Action::CreateZip {
504 sources: vec![
505 Source {
506 path: s.path("source"),
507 archive_name: "a".into(),
508 },
509 Source {
510 path: s.path("empty"),
511 archive_name: "empty".into(),
512 },
513 ],
514 output_file: s.path("input"),
515 method: Method::Store,
516 encryption: Encryption::None,
517 },
518 limits: Limits::default(),
519 });
520 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
521 directory(&s, "output");
522 fs::write(s.0.join("output/a"), b"original").unwrap();
523 let events = choose(&s, ConflictChoice::Skip, true);
524 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
525 assert_eq!(terminal(&events).publication, Publication::Complete);
526 assert_eq!(terminal(&events).created_count, 1);
527 assert_eq!(created(&events), 1);
528 assert!(s.0.join("output/empty").is_dir());
529}
530
531#[cfg(target_os = "linux")]
532#[test]
533fn links_and_special_entries_are_not_interactive() {
534 use std::os::unix::{fs::symlink, net::UnixListener};
535 for mode in 0..3 {
536 let s = Scratch::new();
537 fixture(&s, &["a"]);
538 fs::remove_file(s.0.join("output/a")).unwrap();
539 fs::write(s.0.join("outside"), b"keep").unwrap();
540 let listener;
541 match mode {
542 0 => symlink(s.0.join("outside"), s.0.join("output/a")).unwrap(),
543 1 => symlink(s.0.join("missing"), s.0.join("output/a")).unwrap(),
544 _ => {
545 listener = UnixListener::bind(s.0.join("output/a")).unwrap();
546 let _ = &listener;
547 }
548 }
549 let events = run(&s, request(&s), None, vec![], |_| None);
550 assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
551 assert_eq!(questions(&events), 0);
552 assert_eq!(fs::read(s.0.join("outside")).unwrap(), b"keep");
553 }
554}
555#[cfg(target_os = "linux")]
556#[test]
557fn pre_replacement_failures_preserve_original_hash_and_remove_temps() {
558 for mode in [
559 "create-full",
560 "full",
561 "sync-full",
562 "write-io",
563 "replace-fail",
564 ] {
565 let s = Scratch::new();
566 fixture(&s, &["a"]);
567 let before = hash(&s.0.join("output/a"));
568 let events = run(&s, request(&s), Some(mode), vec![], |e| match e {
569 Message::ConflictRequired { challenge_id, .. } => {
570 Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)])
571 }
572 _ => None,
573 });
574 assert_eq!(
575 terminal(&events).outcome,
576 Outcome::Failed,
577 "{mode}: {events:?}"
578 );
579 assert_eq!(created(&events), 0);
580 assert_eq!(hash(&s.0.join("output/a")), before);
581 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
582 assert_eq!(terminal(&events).retained_partial_count, 0);
583 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
584 }
585}
586#[cfg(target_os = "linux")]
587#[test]
588fn changed_target_is_not_replaced() {
589 let s = Scratch::new();
590 fixture(&s, &["a"]);
591 let events = run(&s, request(&s), None, vec![], |e| match e {
592 Message::ConflictRequired { challenge_id, .. } => {
593 fs::write(s.0.join("output/a"), b"changed by user").unwrap();
594 Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)])
595 }
596 _ => None,
597 });
598 assert_eq!(terminal(&events).error, ErrorCode::Conflict, "{events:?}");
599 assert_eq!(created(&events), 0);
600 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"changed by user");
601}
602#[cfg(target_os = "linux")]
603#[test]
604fn cancel_during_temporary_write_preserves_original_hash() {
605 let s = Scratch::new();
606 fixture(&s, &["a"]);
607 let before = hash(&s.0.join("output/a"));
608 let mut cancelled = false;
609 let events = run(&s, request(&s), Some("pause"), vec![], |e| match e {
610 Message::ConflictRequired { challenge_id, .. } => {
611 Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)])
612 }
613 Message::Progress {
614 stage: Stage::Write,
615 ..
616 } if !cancelled => {
617 let deadline = Instant::now() + Duration::from_secs(5);
618 while !s.0.join("paused").exists() {
619 assert!(Instant::now() < deadline);
620 std::thread::sleep(Duration::from_millis(5));
621 }
622 cancelled = true;
623 Some(vec![Message::Cancel])
624 }
625 Message::CancelAck {
626 status: CancelStatus::Requested,
627 ..
628 } => {
629 fs::write(s.0.join("release"), []).unwrap();
630 None
631 }
632 _ => None,
633 });
634 assert!(cancelled);
635 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
636 assert_eq!(hash(&s.0.join("output/a")), before);
637 assert_eq!(created(&events), 0);
638 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
639}
640#[cfg(target_os = "linux")]
641#[test]
642fn post_replacement_sync_error_reports_actual_publication() {
643 let s = Scratch::new();
644 fixture(&s, &["a"]);
645 let events = run(
646 &s,
647 request(&s),
648 Some("dir-sync-full"),
649 vec![],
650 |e| match e {
651 Message::ConflictRequired { challenge_id, .. } => {
652 Some(vec![reply(*challenge_id, ConflictChoice::Overwrite, false)])
653 }
654 _ => None,
655 },
656 );
657 assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
658 assert_eq!(terminal(&events).publication, Publication::Partial);
659 assert_eq!(terminal(&events).created_count, 1);
660 assert_eq!(terminal(&events).durability, Durability::Failed);
661 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
662 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD);
663 assert_eq!(created(&events), 1);
664}
665
666#[test]
667fn rename_handles_maximum_utf8_filename_length() {
668 let s = Scratch::new();
669 let name = format!("{}ab.txt", "가".repeat(83));
670 fixture(&s, &[&name]);
671 let events = choose(&s, ConflictChoice::Rename, false);
672 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
673 let renamed = events
674 .iter()
675 .find_map(|event| match event {
676 Message::ConflictResolved {
677 relative_name,
678 choice: ConflictChoice::Rename,
679 ..
680 } => Some(relative_name),
681 _ => None,
682 })
683 .unwrap();
684 assert!(renamed.len() <= 255);
685 assert!(renamed.ends_with(" (1).txt"));
686 assert_eq!(fs::read(s.0.join("output").join(renamed)).unwrap(), PAYLOAD);
687 assert_eq!(
688 fs::read(s.0.join("output").join(name)).unwrap(),
689 b"original"
690 );
691}
692#[cfg(target_os = "linux")]
693#[test]
694fn overwrite_does_not_modify_other_hard_links() {
695 let s = Scratch::new();
696 fixture(&s, &["a"]);
697 fs::hard_link(s.0.join("output/a"), s.0.join("outside")).unwrap();
698 let events = choose(&s, ConflictChoice::Overwrite, false);
699 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
700 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), PAYLOAD);
701 assert_eq!(fs::read(s.0.join("outside")).unwrap(), b"original");
702}
703
704#[cfg(target_os = "linux")]
705#[test]
706fn skip_all_ignores_destination_space_for_zip_tar_and_gzip() {
707 for format in ["zip", "tar", "gzip"] {
708 for apply in [false, true] {
709 let s = Scratch::new();
710 let names = match format {
711 "zip" => vec!["a", "b"],
712 "tar" => vec!["folder/hello.txt"],
713 _ => vec!["chosen.txt"],
714 };
715 fixture(&s, &names);
716 let mut start = request(&s);
717 if format == "tar" {
718 fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap();
719 } else if format == "gzip" {
720 fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap();
721 if let Action::Extract {
722 gzip_output_name, ..
723 } = &mut start.action
724 {
725 *gzip_output_name = Some("chosen.txt".into());
726 }
727 }
728 let before = names
729 .iter()
730 .map(|name| hash(&s.0.join("output").join(name)))
731 .collect::<Vec<_>>();
732 let events = run(
733 &s,
734 start,
735 Some("space-destination"),
736 vec![],
737 |event| match event {
738 Message::ConflictRequired { challenge_id, .. } => {
739 Some(vec![reply(*challenge_id, ConflictChoice::Skip, apply)])
740 }
741 _ => None,
742 },
743 );
744 assert_eq!(
745 terminal(&events).outcome,
746 Outcome::Completed,
747 "{format}/{apply}: {events:?}"
748 );
749 assert_eq!(terminal(&events).error, ErrorCode::None);
750 assert_eq!(terminal(&events).publication, Publication::None);
751 assert_eq!(terminal(&events).created_count, 0);
752 assert_eq!(terminal(&events).durability, Durability::NotApplicable);
753 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
754 assert_eq!(created(&events), 0);
755 let conflicts = if format == "zip" { 2 } else { 1 };
756 assert_eq!(questions(&events), if apply { 1 } else { conflicts });
757 assert_eq!(
758 count(&events, |event| matches!(
759 event,
760 Message::ConflictResolved {
761 choice: ConflictChoice::Skip,
762 ..
763 }
764 )),
765 conflicts
766 );
767 for (name, before) in names.iter().zip(before) {
768 assert_eq!(hash(&s.0.join("output").join(name)), before);
769 }
770 if format == "gzip" {
771 assert_eq!(
772 fs::read(s.0.join("output/chosen.txt")).unwrap(),
773 b"original"
774 );
775 }
776 assert!(
777 !s.0.join("paused").exists(),
778 "skipped files must not charge destination space"
779 );
780 }
781 }
782}
783#[cfg(target_os = "linux")]
784#[test]
785fn destination_space_is_checked_after_overwrite_or_rename_choice() {
786 for choice in [ConflictChoice::Overwrite, ConflictChoice::Rename] {
787 let s = Scratch::new();
788 fixture(&s, &["a", "b"]);
789 let before = hash(&s.0.join("output/a"));
790 let events = run(
791 &s,
792 request(&s),
793 Some("space-destination"),
794 vec![],
795 |event| match event {
796 Message::ConflictRequired { challenge_id, .. } => {
797 Some(vec![reply(*challenge_id, choice, true)])
798 }
799 _ => None,
800 },
801 );
802 assert_eq!(questions(&events), 1, "{events:?}");
803 assert_eq!(
804 count(&events, |event| matches!(
805 event,
806 Message::ConflictResolved { .. }
807 )),
808 1
809 );
810 assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
811 assert_eq!(terminal(&events).publication, Publication::None);
812 assert_eq!(terminal(&events).created_count, 0);
813 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
814 assert_eq!(hash(&s.0.join("output/a")), before);
815 assert_eq!(hash(&s.0.join("output/b")), before);
816 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 2);
817 assert!(s.0.join("paused").exists());
818 }
819}
820#[cfg(target_os = "linux")]
821#[test]
822fn skipped_files_do_not_charge_space_for_remaining_publication() {
823 for choice in [
824 Some(ConflictChoice::Overwrite),
825 Some(ConflictChoice::Rename),
826 None,
827 ] {
828 let s = Scratch::new();
829 fixture(&s, &["a", "b", "c"]);
830 assert!(PAYLOAD.len() <= 64 && PAYLOAD.len() * 3 > 64);
831 if choice.is_none() {
832 fs::remove_file(s.0.join("output/c")).unwrap();
833 }
834 let events = run(
835 &s,
836 request(&s),
837 Some("space-one-output"),
838 vec![],
839 |event| match event {
840 Message::ConflictRequired {
841 challenge_id,
842 entry_id,
843 ..
844 } => {
845 let choice = if *entry_id < 2 {
846 ConflictChoice::Skip
847 } else {
848 choice.unwrap()
849 };
850 Some(vec![reply(*challenge_id, choice, false)])
851 }
852 _ => None,
853 },
854 );
855 assert_eq!(
856 terminal(&events).outcome,
857 Outcome::Completed,
858 "{choice:?}: {events:?}"
859 );
860 assert_eq!(terminal(&events).publication, Publication::Complete);
861 assert_eq!(terminal(&events).created_count, 1);
862 assert_eq!(created(&events), 1);
863 assert_eq!(questions(&events), if choice.is_some() { 3 } else { 2 });
864 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
865 assert_eq!(fs::read(s.0.join("output/b")).unwrap(), b"original");
866 let output = if choice == Some(ConflictChoice::Rename) {
867 "c (1)"
868 } else {
869 "c"
870 };
871 assert_eq!(fs::read(s.0.join("output").join(output)).unwrap(), PAYLOAD);
872 if choice == Some(ConflictChoice::Rename) {
873 assert_eq!(fs::read(s.0.join("output/c")).unwrap(), b"original");
874 }
875 assert!(s.0.join("paused").exists());
876 }
877}
878#[cfg(target_os = "linux")]
879#[test]
880fn insufficient_destination_space_does_not_prevent_cancellation() {
881 let s = Scratch::new();
882 fixture(&s, &["a"]);
883 let events = run(
884 &s,
885 request(&s),
886 Some("space-destination"),
887 vec![],
888 |event| matches!(event, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]),
889 );
890 assert_eq!(questions(&events), 1, "{events:?}");
891 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
892 assert_eq!(terminal(&events).publication, Publication::None);
893 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
894}
895#[cfg(target_os = "linux")]
896#[test]
897fn interactive_staging_space_and_integrity_checks_remain_before_questions() {
898 for corrupt in [false, true] {
899 let s = Scratch::new();
900 fixture(&s, &["a"]);
901 if corrupt {
902 let mut bytes = fs::read(s.0.join("input")).unwrap();
903 let at = bytes
904 .windows(PAYLOAD.len())
905 .position(|bytes| bytes == PAYLOAD)
906 .unwrap();
907 bytes[at] ^= 1;
908 fs::write(s.0.join("input"), bytes).unwrap();
909 }
910 let fault = if corrupt {
911 "space-destination"
912 } else {
913 "space-stage"
914 };
915 let events = run(&s, request(&s), Some(fault), vec![], |_| None);
916 assert_eq!(
917 terminal(&events).error,
918 if corrupt {
919 ErrorCode::Integrity
920 } else {
921 ErrorCode::DiskFull
922 },
923 "{events:?}"
924 );
925 assert_eq!(questions(&events), 0);
926 assert_eq!(created(&events), 0);
927 assert_eq!(terminal(&events).publication, Publication::None);
928 assert_eq!(fs::read(s.0.join("output/a")).unwrap(), b"original");
929 }
930}