team-ljyzipelo

공개
1,031줄35 KB
1use super::*;
2use sha2::{Digest, Sha256};
3
4fn directory(s: &Scratch, name: &str) {
5 let path = s.0.join(name);
6 fs::create_dir_all(&path).unwrap();
7 #[cfg(unix)]
8 {
9 use std::os::unix::fs::PermissionsExt;
10 let mut current = path.as_path();
11 while current != s.0 {
12 fs::set_permissions(current, fs::Permissions::from_mode(0o700)).unwrap();
13 current = current.parent().unwrap();
14 }
15 }
16}
17fn pieces(s: &Scratch, bytes: &[u8], ends: &[usize]) -> Vec<PathBuf> {
18 let mut begin = 0;
19 let mut paths = Vec::new();
20 for (index, end) in ends.iter().copied().chain(Some(bytes.len())).enumerate() {
21 assert!(begin <= end && end <= bytes.len());
22 let path = s.0.join(format!("sample.7z.{:03}", index + 1));
23 fs::write(&path, &bytes[begin..end]).unwrap();
24 paths.push(path);
25 begin = end;
26 }
27 paths
28}
29fn setup(s: &Scratch, count: usize, fixture: &str) -> (Vec<u8>, Vec<PathBuf>) {
30 let bytes = seven_fixture(fixture);
31 let ends = (1..count)
32 .map(|i| i * bytes.len() / count)
33 .collect::<Vec<_>>();
34 let paths = pieces(s, &bytes, &ends);
35 (bytes, paths)
36}
37fn list(s: &Scratch) -> Vec<Message> {
38 execute(Start {
39 action: Action::List {
40 archive: s.path("sample.7z.001"),
41 },
42 limits: Limits::default(),
43 })
44}
45fn id(events: &[Message]) -> ListId {
46 assert_eq!(terminal(events).outcome, Outcome::Completed, "{events:?}");
47 events
48 .iter()
49 .find_map(|event| match event {
50 Message::ListEnd { list_id, .. } => Some(list_id.clone()),
51 _ => None,
52 })
53 .unwrap()
54}
55fn request(s: &Scratch, list_id: Option<ListId>, selection: Selection) -> Start {
56 Start {
57 action: Action::Extract {
58 archive: s.path("sample.7z.001"),
59 destination: s.path("output"),
60 selection,
61 list_id,
62 gzip_output_name: None,
63 },
64 limits: Limits::default(),
65 }
66}
67fn failure(events: &[Message], error: ErrorCode) {
68 assert_eq!(terminal(events).outcome, Outcome::Failed, "{events:?}");
69 assert_eq!(terminal(events).error, error, "{events:?}");
70 assert_eq!(terminal(events).created_count, 0, "{events:?}");
71 assert_eq!(
72 terminal(events).publication,
73 Publication::None,
74 "{events:?}"
75 );
76 assert!(
77 !events
78 .iter()
79 .any(|event| matches!(event, Message::Output { .. } | Message::ListEnd { .. })),
80 "{events:?}"
81 );
82}
83fn hashes(paths: &[PathBuf]) -> Vec<[u8; 32]> {
84 paths
85 .iter()
86 .map(|p| Sha256::digest(fs::read(p).unwrap()).into())
87 .collect()
88}
89fn problem(events: &[Message], reason: VolumeProblemReason, leaf: &str) {
90 let problems = events
91 .iter()
92 .filter_map(|event| match event {
93 Message::VolumeProblem { reason, volume } => Some((reason, volume)),
94 _ => None,
95 })
96 .collect::<Vec<_>>();
97 assert_eq!(problems.len(), 1, "{events:?}");
98 assert_eq!(
99 problems[0],
100 (&reason, &NativePath::from_path(std::path::Path::new(leaf)))
101 );
102 let accepted = events
103 .iter()
104 .position(|event| matches!(event, Message::Accepted { .. }))
105 .unwrap();
106 let reported = events
107 .iter()
108 .position(|event| matches!(event, Message::VolumeProblem { .. }))
109 .unwrap();
110 assert!(accepted < reported && reported < events.len() - 1);
111}
112
113#[test]
114fn headers_and_data_cross_variable_part_boundaries_for_reference_archives() {
115 for fixture in [
116 "copy.7z",
117 "lzma.7z",
118 "lzma2.7z",
119 "libarchive-lzma1.7z",
120 "libarchive-lzma2.7z",
121 ] {
122 let s = Scratch::new();
123 let bytes = seven_fixture(fixture);
124 let paths = pieces(&s, &bytes, &[1, 6, 13, 31, 32, 40]);
125 let before = hashes(&paths);
126 let listed = list(&s);
127 let token = id(&listed);
128 assert_eq!(token.catalog_version, 2);
129 assert_eq!(token.format, Format::SevenZip);
130 assert!(matches!(
131 token.source_object,
132 SourceObject::SplitSevenZip { .. }
133 ));
134 assert_eq!(token.archive_bytes, bytes.len() as u64);
135 assert_eq!(
136 token.archive_sha256,
137 <[u8; 32]>::from(Sha256::digest(&bytes))
138 );
139 directory(&s, "output");
140 let result = execute(request(&s, Some(token), Selection::EntryIds(vec![0])));
141 assert_eq!(
142 terminal(&result).outcome,
143 Outcome::Completed,
144 "{fixture}: {result:?}"
145 );
146 assert_eq!(
147 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
148 SEVEN_PAYLOAD.repeat(100)
149 );
150 assert_eq!(hashes(&paths), before);
151 }
152}
153
154#[test]
155fn numeric_order_crosses_009_010_and_accepts_exactly_999_parts() {
156 for count in [11, 999] {
157 let s = Scratch::new();
158 let (bytes, paths) = setup(&s, count, "copy.7z");
159 let before = hashes(&paths);
160 let token = id(&list(&s));
161 assert_eq!(token.archive_bytes, bytes.len() as u64);
162 directory(&s, "output");
163 let result = execute(request(&s, Some(token), Selection::All));
164 assert_eq!(
165 terminal(&result).outcome,
166 Outcome::Completed,
167 "{count}: {result:?}"
168 );
169 assert_eq!(
170 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
171 SEVEN_PAYLOAD.repeat(100)
172 );
173 assert_eq!(hashes(&paths), before);
174 fs::write(s.0.join("sample.7z.1000"), [0]).unwrap();
175 failure(&list(&s), ErrorCode::Limit);
176 }
177}
178
179#[test]
180fn nonfirst_selection_and_definite_middle_gaps_name_the_exact_required_part() {
181 let s = Scratch::new();
182 let (_, paths) = setup(&s, 11, "copy.7z");
183 let result = execute(Start {
184 action: Action::List {
185 archive: s.path("sample.7z.002"),
186 },
187 limits: Limits::default(),
188 });
189 failure(&result, ErrorCode::InvalidRequest);
190 problem(
191 &result,
192 VolumeProblemReason::FirstVolumeRequired,
193 "sample.7z.001",
194 );
195 fs::remove_file(&paths[8]).unwrap();
196 let result = list(&s);
197 failure(&result, ErrorCode::MissingVolume);
198 problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.009");
199}
200
201#[test]
202fn missing_tail_truncated_empty_and_extra_bytes_never_guess_a_missing_name() {
203 for mode in 0..4 {
204 let s = Scratch::new();
205 let (_, paths) = setup(&s, 3, "copy.7z");
206 match mode {
207 0 => fs::remove_file(&paths[2]).unwrap(),
208 1 => {
209 let mut bytes = fs::read(&paths[2]).unwrap();
210 bytes.pop();
211 fs::write(&paths[2], bytes).unwrap();
212 }
213 2 => fs::write(&paths[1], []).unwrap(),
214 _ => {
215 let mut bytes = fs::read(&paths[2]).unwrap();
216 bytes.push(0);
217 fs::write(&paths[2], bytes).unwrap();
218 }
219 }
220 let result = list(&s);
221 failure(&result, ErrorCode::Integrity);
222 problem(&result, VolumeProblemReason::IncompleteSet, "sample.7z.001");
223 }
224}
225
226#[test]
227fn detectable_mixed_reordered_and_corrupt_payloads_never_publish() {
228 for mode in 0..3 {
229 let s = Scratch::new();
230 let (_, paths) = setup(&s, 11, "copy.7z");
231 if mode == 0 {
232 let a = fs::read(&paths[4]).unwrap();
233 let b = fs::read(&paths[5]).unwrap();
234 fs::write(&paths[4], b).unwrap();
235 fs::write(&paths[5], a).unwrap();
236 } else {
237 let mut bytes = fs::read(&paths[4]).unwrap();
238 if mode == 1 {
239 bytes.fill(0x5a);
240 } else {
241 bytes[0] ^= 1;
242 }
243 fs::write(&paths[4], bytes).unwrap();
244 }
245 directory(&s, "output");
246 let result = execute(request(&s, None, Selection::All));
247 failure(&result, ErrorCode::Integrity);
248 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
249 }
250}
251
252#[test]
253fn changing_middle_tail_length_object_or_count_after_listing_invalidates_the_token() {
254 for mode in 0..8 {
255 let s = Scratch::new();
256 let (_, paths) = setup(&s, 3, "copy.7z");
257 let token = id(&list(&s));
258 let selected = if mode == 0 { &paths[1] } else { &paths[2] };
259 match mode {
260 0 | 1 => {
261 let mut data = fs::read(selected).unwrap();
262 data[0] ^= 1;
263 fs::write(selected, data).unwrap();
264 }
265 2 => {
266 let data = fs::read(selected).unwrap();
267 fs::rename(selected, s.0.join("old-part")).unwrap();
268 fs::write(selected, data).unwrap();
269 }
270 3 => {
271 let mut data = fs::read(selected).unwrap();
272 data.pop();
273 fs::write(selected, data).unwrap();
274 }
275 4 => fs::remove_file(selected).unwrap(),
276 5 => fs::write(s.0.join("sample.7z.004"), [0]).unwrap(),
277 6 => fs::remove_file(&paths[1]).unwrap(),
278 _ => {
279 for path in &paths {
280 fs::remove_file(path).unwrap();
281 }
282 }
283 }
284 directory(&s, "output");
285 let result = execute(request(&s, Some(token), Selection::All));
286 failure(
287 &result,
288 if mode == 6 {
289 ErrorCode::MissingVolume
290 } else {
291 ErrorCode::SourceChanged
292 },
293 );
294 if mode == 6 {
295 problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.002");
296 } else {
297 assert!(
298 !result
299 .iter()
300 .any(|event| matches!(event, Message::VolumeProblem { .. }))
301 );
302 }
303 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
304 }
305}
306
307#[test]
308fn replacement_or_gap_during_conflict_wait_is_rechecked_before_first_file_commit() {
309 for mode in 0..3 {
310 let s = Scratch::new();
311 let (_, paths) = setup(&s, 3, "copy.7z");
312 let token = id(&list(&s));
313 directory(&s, "output/folder");
314 fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
315 let mut changed = false;
316 let result = guarded::run(
317 &s,
318 GuardedStart {
319 start: request(&s, Some(token), Selection::All),
320 ceiling: Limits::default(),
321 interactive: true,
322 },
323 |event| {
324 if let Message::ConflictRequired { challenge_id, .. } = event {
325 changed = true;
326 if mode == 2 {
327 fs::remove_file(&paths[1]).unwrap();
328 } else {
329 let target = &paths[if mode == 0 { 1 } else { 2 }];
330 let mut bytes = fs::read(target).unwrap();
331 bytes[0] ^= 1;
332 fs::write(target, bytes).unwrap();
333 }
334 return Some(vec![Message::ConflictReply {
335 challenge_id: *challenge_id,
336 choice: ConflictChoice::Overwrite,
337 apply_to_remaining: false,
338 }]);
339 }
340 None
341 },
342 );
343 assert!(changed, "{result:?}");
344 failure(
345 &result,
346 if mode == 2 {
347 ErrorCode::MissingVolume
348 } else {
349 ErrorCode::SourceChanged
350 },
351 );
352 assert_eq!(
353 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
354 b"keep"
355 );
356 assert_eq!(terminal(&result).cleanup, Cleanup::Complete);
357 assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 1);
358 }
359}
360
361#[test]
362fn split_capture_uses_aggregate_input_budget_and_existing_output_permission() {
363 for allow in [false, true] {
364 let s = Scratch::new();
365 let (bytes, paths) = setup(&s, 11, "copy.7z");
366 let before = hashes(&paths);
367 directory(&s, "output");
368 let mut start = request(&s, None, Selection::All);
369 start.limits.input = bytes.len() as u64;
370 start.limits.output = 1;
371 let ceiling = Limits {
372 input: bytes.len() as u64,
373 output: 8192,
374 ..Limits::default()
375 };
376 let mut questions = 0;
377 let result = guarded::run(
378 &s,
379 GuardedStart {
380 start,
381 ceiling,
382 interactive: true,
383 },
384 |event| {
385 if let Message::ResourceRequired {
386 challenge_id,
387 scope,
388 ..
389 } = event
390 {
391 questions += 1;
392 return Some(vec![Message::ResourceReply {
393 challenge_id: *challenge_id,
394 scope: *scope,
395 allow,
396 }]);
397 }
398 None
399 },
400 );
401 assert_eq!(questions, 1);
402 assert_eq!(
403 terminal(&result).outcome,
404 if allow {
405 Outcome::Completed
406 } else {
407 Outcome::Cancelled
408 },
409 "{result:?}"
410 );
411 if allow {
412 assert_eq!(
413 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
414 SEVEN_PAYLOAD.repeat(100)
415 );
416 } else {
417 assert_eq!(terminal(&result).created_count, 0);
418 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
419 }
420 assert_eq!(hashes(&paths), before);
421 }
422 let s = Scratch::new();
423 let (bytes, _) = setup(&s, 11, "copy.7z");
424 directory(&s, "output");
425 let mut start = request(&s, None, Selection::All);
426 start.limits.input = bytes.len() as u64 - 1;
427 failure(&execute(start), ErrorCode::Limit);
428}
429
430#[test]
431fn cancellation_at_conflict_keeps_source_and_existing_output() {
432 let s = Scratch::new();
433 let (_, paths) = setup(&s, 3, "copy.7z");
434 let before = hashes(&paths);
435 directory(&s, "output/folder");
436 fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
437 let result = guarded::run(
438 &s,
439 GuardedStart {
440 start: request(&s, None, Selection::All),
441 ceiling: Limits::default(),
442 interactive: true,
443 },
444 |event| matches!(event, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]),
445 );
446 assert_eq!(terminal(&result).outcome, Outcome::Cancelled);
447 assert_eq!(terminal(&result).created_count, 0);
448 assert_eq!(
449 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
450 b"keep"
451 );
452 assert_eq!(hashes(&paths), before);
453}
454
455#[test]
456fn split_preview_and_excluded_zip_volume_names_are_not_retried_as_single_inputs() {
457 let s = Scratch::new();
458 let (_, paths) = setup(&s, 3, "copy.7z");
459 let token = id(&list(&s));
460 let preview = Start {
461 action: Action::Preview {
462 archive: s.path("sample.7z.001"),
463 entry_id: 0,
464 list_id: token,
465 },
466 limits: Limits::default(),
467 };
468 let result = guarded::run(
469 &s,
470 GuardedStart {
471 start: preview,
472 ceiling: Limits::default(),
473 interactive: true,
474 },
475 |_| None,
476 );
477 failure(&result, ErrorCode::UnsupportedFeature);
478 assert!(
479 !result
480 .iter()
481 .any(|event| matches!(event, Message::PreviewBegin(_)))
482 );
483 for name in ["sample.zip.001", "sample.z01"] {
484 fs::write(s.0.join(name), include_bytes!("fixtures/store.zip")).unwrap();
485 let result = execute(Start {
486 action: Action::List {
487 archive: s.path(name),
488 },
489 limits: Limits::default(),
490 });
491 failure(&result, ErrorCode::UnsupportedFeature);
492 }
493 assert_eq!(paths.len(), 3);
494}
495
496fn reference_fixture(s: &Scratch, name: &str) -> Vec<PathBuf> {
497 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
498 .join("../../tests/rust-archive-worker/fixtures/split7z");
499 let mut paths = Vec::new();
500 for index in 1..=999 {
501 let source = root.join(format!("{name}.7z.{index:03}"));
502 match fs::read(source) {
503 Ok(data) => {
504 let destination = s.0.join(format!("sample.7z.{index:03}"));
505 fs::write(&destination, data).unwrap();
506 paths.push(destination);
507 }
508 Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
509 Err(error) => panic!("{error:?}"),
510 }
511 }
512 assert!(paths.len() > 1);
513 paths
514}
515
516#[test]
517fn seven_zip_created_volumes_list_and_extract_with_matching_reference_hashes() {
518 let s = Scratch::new();
519 let paths = reference_fixture(&s, "reference");
520 let before = hashes(&paths);
521 let token = id(&list(&s));
522 directory(&s, "output");
523 let result = execute(request(&s, Some(token), Selection::All));
524 assert_eq!(terminal(&result).outcome, Outcome::Completed, "{result:?}");
525 let expected = SEVEN_PAYLOAD.repeat(100);
526 let actual = fs::read(s.0.join("output/folder/hello.txt")).unwrap();
527 assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
528 assert_eq!(actual, expected);
529 let expected = (0..4096usize)
530 .map(|index| ((index * 37 + (index >> 3)) % 256) as u8)
531 .collect::<Vec<_>>();
532 let actual = fs::read(s.0.join("output/second.bin")).unwrap();
533 assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
534 assert_eq!(actual, expected);
535 assert_eq!(hashes(&paths), before);
536}
537
538#[test]
539fn encrypted_seven_zip_volumes_list_and_extract_with_password() {
540 for (name, header) in [("encrypted-header", true), ("encrypted-body", false)] {
541 let s = Scratch::new();
542 let paths = reference_fixture(&s, name);
543 let before = hashes(&paths);
544 let mut prompts = Vec::new();
545 let listing = interactive(
546 Start {
547 action: Action::List {
548 archive: s.path("sample.7z.001"),
549 },
550 limits: Limits::default(),
551 },
552 |id, attempt, _| {
553 prompts.push(attempt);
554 password_reply(id, b"zipelo-split-test")
555 },
556 );
557 let token = id(&listing);
558 // 헤더가 암호화된 경우에만 목록을 읽기 전에 암호를 물음.
559 assert_eq!(prompts, if header { vec![1] } else { vec![] });
560 assert!(listing.iter().any(|event| matches!(
561 event,
562 Message::Entry(Entry {
563 encrypted: true,
564 ..
565 })
566 )));
567 directory(&s, "output");
568 // 틀린 암호 세 번은 출력 없이 끝나고 조각을 바꾸지 않음.
569 let wrong = interactive(
570 request(&s, Some(token.clone()), Selection::All),
571 |id, _, _| password_reply(id, b"wrong-password"),
572 );
573 failure(&wrong, ErrorCode::WrongPassword);
574 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
575 let mut prompts = Vec::new();
576 let events = interactive(
577 request(&s, Some(token), Selection::All),
578 |id, attempt, _| {
579 prompts.push(attempt);
580 password_reply(id, b"zipelo-split-test")
581 },
582 );
583 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
584 assert_eq!(prompts, [1]);
585 assert_eq!(
586 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
587 SEVEN_PAYLOAD.repeat(100)
588 );
589 let expected = (0..4096usize)
590 .map(|index| ((index * 37 + (index >> 3)) % 256) as u8)
591 .collect::<Vec<_>>();
592 assert_eq!(fs::read(s.0.join("output/second.bin")).unwrap(), expected);
593 assert_eq!(hashes(&paths), before);
594 }
595}
596
597fn publication_fixture(s: &Scratch, existing: bool, with_file: bool) -> Vec<PathBuf> {
598 assert!(
599 Command::new("python3")
600 .env("PYTHONDONTWRITEBYTECODE", "1")
601 .arg(
602 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
603 .join("../../tests/rust-archive-worker/split_publication_cases.py")
604 )
605 .arg(&s.0)
606 .arg(if with_file { "file" } else { "directories" })
607 .status()
608 .unwrap()
609 .success()
610 );
611 directory(s, "output");
612 if existing {
613 for index in 0..16 {
614 directory(s, &format!("output/d{index:03}"));
615 }
616 }
617 (1..=5)
618 .map(|index| s.0.join(format!("sample.7z.{index:03}")))
619 .take_while(|path| path.is_file())
620 .collect()
621}
622fn publication_verifications(events: &[Message]) -> Vec<usize> {
623 events
624 .iter()
625 .enumerate()
626 .filter_map(|(index, event)| {
627 matches!(
628 event,
629 Message::Progress {
630 stage: Stage::Verify,
631 processed_bytes: 0,
632 total_bytes: None,
633 ..
634 }
635 )
636 .then_some(index)
637 })
638 .collect()
639}
640fn publication_request(s: &Scratch) -> GuardedStart {
641 GuardedStart {
642 start: request(s, None, Selection::All),
643 ceiling: Limits::default(),
644 interactive: true,
645 }
646}
647
648#[test]
649fn split_publication_verifies_once_for_fresh_or_many_existing_directories() {
650 for existing in [false, true] {
651 let s = Scratch::new();
652 let paths = publication_fixture(&s, existing, true);
653 let before = hashes(&paths);
654 let events = guarded::run(&s, publication_request(&s), |_| None);
655 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
656 let verifies = publication_verifications(&events);
657 assert_eq!(verifies.len(), 1, "existing={existing}: {events:?}");
658 let first_output = events
659 .iter()
660 .position(|event| matches!(event, Message::Output { .. }))
661 .unwrap();
662 assert!(verifies[0] < first_output);
663 if existing {
664 let write = events
665 .iter()
666 .position(|event| {
667 matches!(
668 event,
669 Message::Progress {
670 stage: Stage::Write,
671 ..
672 }
673 )
674 })
675 .unwrap();
676 assert!(write < verifies[0]);
677 }
678 assert_eq!(
679 terminal(&events).created_count,
680 if existing { 1 } else { 17 }
681 );
682 assert_eq!(
683 fs::read(s.0.join("output/payload.bin")).unwrap(),
684 (0..=255u8).cycle().take(1024 * 1024).collect::<Vec<_>>()
685 );
686 assert_eq!(hashes(&paths), before);
687 }
688}
689
690#[test]
691fn split_publication_existing_directories_do_not_cache_before_conflict_changes() {
692 let s = Scratch::new();
693 let paths = publication_fixture(&s, true, true);
694 fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
695 let mut changed = None;
696 let events = guarded::run(&s, publication_request(&s), |event| {
697 if let Message::ConflictRequired { challenge_id, .. } = event {
698 let mut data = fs::read(&paths[1]).unwrap();
699 data[0] ^= 1;
700 fs::write(&paths[1], data).unwrap();
701 changed = Some(hashes(&paths));
702 return Some(vec![Message::ConflictReply {
703 challenge_id: *challenge_id,
704 choice: ConflictChoice::Overwrite,
705 apply_to_remaining: false,
706 }]);
707 }
708 None
709 });
710 failure(&events, ErrorCode::SourceChanged);
711 let verifies = publication_verifications(&events);
712 assert_eq!(verifies.len(), 1, "{events:?}");
713 let conflict = events
714 .iter()
715 .position(|event| matches!(event, Message::ConflictRequired { .. }))
716 .unwrap();
717 assert!(conflict < verifies[0]);
718 assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
719 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 17);
720 assert_eq!(hashes(&paths), changed.unwrap());
721 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
722}
723
724#[test]
725fn split_publication_no_outputs_verify_once_and_cancel_does_not_rehash() {
726 for mode in 0..3 {
727 let s = Scratch::new();
728 let paths = publication_fixture(&s, true, mode != 0);
729 let before = hashes(&paths);
730 if mode != 0 {
731 fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
732 }
733 let events = guarded::run(&s, publication_request(&s), |event| {
734 if let Message::ConflictRequired { challenge_id, .. } = event {
735 return Some(if mode == 2 {
736 vec![Message::Cancel]
737 } else {
738 vec![Message::ConflictReply {
739 challenge_id: *challenge_id,
740 choice: ConflictChoice::Skip,
741 apply_to_remaining: false,
742 }]
743 });
744 }
745 None
746 });
747 assert_eq!(
748 terminal(&events).outcome,
749 if mode == 2 {
750 Outcome::Cancelled
751 } else {
752 Outcome::Completed
753 },
754 "{events:?}"
755 );
756 assert_eq!(
757 publication_verifications(&events).len(),
758 usize::from(mode != 2),
759 "{events:?}"
760 );
761 assert_eq!(terminal(&events).publication, Publication::None);
762 assert_eq!(terminal(&events).created_count, 0);
763 assert!(
764 !events
765 .iter()
766 .any(|event| matches!(event, Message::Output { .. }))
767 );
768 if mode != 0 {
769 assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
770 }
771 assert_eq!(hashes(&paths), before);
772 }
773}
774
775#[test]
776fn split_publication_changed_source_stops_before_creating_the_first_directory() {
777 use std::sync::{Arc, Mutex};
778 struct ChangingOutput {
779 frame: Vec<u8>,
780 output: Arc<Mutex<Vec<u8>>>,
781 path: PathBuf,
782 changed: bool,
783 }
784 impl Write for ChangingOutput {
785 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
786 self.frame.extend_from_slice(bytes);
787 Ok(bytes.len())
788 }
789 fn flush(&mut self) -> std::io::Result<()> {
790 let event = {
791 let mut output = self.output.lock().unwrap();
792 output.extend_from_slice(&self.frame);
793 let mut reader = Reader::new(output.as_slice());
794 let mut last = None;
795 while let Some((_, _, event)) = reader.read()? {
796 last = Some(event);
797 }
798 last.unwrap()
799 };
800 if !self.changed
801 && matches!(
802 event,
803 Message::Progress {
804 stage: Stage::Verify,
805 processed_bytes: 0,
806 total_bytes: None,
807 ..
808 }
809 )
810 {
811 // 검증 시작 프레임을 보낼 때 바꿔 스케줄링 경합 없이 생성 직전을 재현함.
812 let mut data = fs::read(&self.path)?;
813 data[0] ^= 1;
814 fs::write(&self.path, data)?;
815 self.changed = true;
816 }
817 self.frame.clear();
818 Ok(())
819 }
820 }
821 let s = Scratch::new();
822 let paths = publication_fixture(&s, false, true);
823 let before = hashes(&paths);
824 let mut input = Vec::new();
825 Writer::new(&mut input, 17)
826 .send(&Message::Start(request(&s, None, Selection::All)))
827 .unwrap();
828 let output = Arc::new(Mutex::new(Vec::new()));
829 zipelo_archive_worker::runtime::serve(
830 std::io::Cursor::new(input),
831 ChangingOutput {
832 frame: Vec::new(),
833 output: Arc::clone(&output),
834 path: paths[1].clone(),
835 changed: false,
836 },
837 )
838 .unwrap();
839 let output = output.lock().unwrap();
840 let mut reader = Reader::new(output.as_slice());
841 let mut events = Vec::new();
842 while let Some((_, _, event)) = reader.read().unwrap() {
843 events.push(event);
844 }
845 failure(&events, ErrorCode::SourceChanged);
846 assert_eq!(publication_verifications(&events).len(), 1);
847 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
848 assert_ne!(hashes(&paths), before);
849}
850
851#[test]
852fn split_publication_target_changes_during_verification_are_preserved() {
853 use std::io::{Cursor, Read};
854 use std::sync::{Arc, Mutex, mpsc};
855 const USER_EDIT: &[u8] = b"new user edit after overwrite approval";
856 struct Input {
857 receive: mpsc::Receiver<Vec<u8>>,
858 pending: Cursor<Vec<u8>>,
859 }
860 impl Read for Input {
861 fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
862 if bytes.is_empty() {
863 return Ok(0);
864 }
865 loop {
866 let count = self.pending.read(bytes)?;
867 if count != 0 {
868 return Ok(count);
869 }
870 match self
871 .receive
872 .recv_timeout(std::time::Duration::from_secs(20))
873 {
874 Ok(frame) => self.pending = Cursor::new(frame),
875 Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(0),
876 Err(error) => return Err(std::io::Error::other(error)),
877 }
878 }
879 }
880 }
881 struct Reply {
882 send: mpsc::Sender<Vec<u8>>,
883 pending: Vec<u8>,
884 }
885 impl Write for Reply {
886 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
887 self.pending.extend_from_slice(bytes);
888 Ok(bytes.len())
889 }
890 fn flush(&mut self) -> std::io::Result<()> {
891 self.send
892 .send(std::mem::take(&mut self.pending))
893 .map_err(std::io::Error::other)
894 }
895 }
896 struct ChangingOutput {
897 frame: Vec<u8>,
898 output: Arc<Mutex<Vec<u8>>>,
899 reply: Option<Writer<Reply>>,
900 target: PathBuf,
901 mode: u8,
902 modified: Option<std::time::SystemTime>,
903 changed: bool,
904 }
905 impl Write for ChangingOutput {
906 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
907 self.frame.extend_from_slice(bytes);
908 Ok(bytes.len())
909 }
910 fn flush(&mut self) -> std::io::Result<()> {
911 let event = {
912 let mut output = self.output.lock().unwrap();
913 output.extend_from_slice(&self.frame);
914 let mut reader = Reader::new(output.as_slice());
915 let mut last = None;
916 while let Some((_, _, event)) = reader.read()? {
917 last = Some(event);
918 }
919 last.unwrap()
920 };
921 match event {
922 Message::ConflictRequired { challenge_id, .. } => {
923 self.reply.as_mut().unwrap().send(&Message::ConflictReply {
924 challenge_id,
925 choice: ConflictChoice::Overwrite,
926 apply_to_remaining: false,
927 })?;
928 }
929 Message::Progress {
930 stage: Stage::Verify,
931 processed_bytes: 0,
932 total_bytes: None,
933 ..
934 } if !self.changed => {
935 // 재해시 시작과 동기화해 승인 이후 대상 변경을 재현함.
936 match self.mode {
937 0 => {
938 fs::write(&self.target, USER_EDIT)?;
939 fs::File::options()
940 .write(true)
941 .open(&self.target)?
942 .set_times(fs::FileTimes::new().set_modified(
943 self.modified.unwrap() + std::time::Duration::from_secs(2),
944 ))?;
945 }
946 1 => {
947 let old = self.target.with_file_name("approved-old");
948 fs::rename(&self.target, &old)?;
949 fs::write(&self.target, USER_EDIT)?;
950 fs::File::options()
951 .write(true)
952 .open(&self.target)?
953 .set_times(
954 fs::FileTimes::new().set_modified(self.modified.unwrap()),
955 )?;
956 fs::remove_file(old)?;
957 }
958 2 => fs::remove_file(&self.target)?,
959 3 => fs::write(&self.target, USER_EDIT)?,
960 _ => unreachable!(),
961 }
962 self.changed = true;
963 }
964 Message::Terminal(_) => self.reply = None,
965 _ => {}
966 }
967 self.frame.clear();
968 Ok(())
969 }
970 }
971 for mode in 0..4 {
972 let s = Scratch::new();
973 let paths = publication_fixture(&s, true, true);
974 let before = hashes(&paths);
975 let target = s.0.join("output/payload.bin");
976 let modified = if mode == 3 {
977 None
978 } else {
979 fs::write(&target, vec![b'o'; USER_EDIT.len()]).unwrap();
980 Some(fs::metadata(&target).unwrap().modified().unwrap())
981 };
982 let (send, receive) = mpsc::channel();
983 let mut reply = Writer::new(
984 Reply {
985 send,
986 pending: Vec::new(),
987 },
988 17,
989 );
990 reply
991 .send(&Message::StartGuarded(publication_request(&s)))
992 .unwrap();
993 let output = Arc::new(Mutex::new(Vec::new()));
994 zipelo_archive_worker::runtime::serve(
995 Input {
996 receive,
997 pending: Cursor::new(Vec::new()),
998 },
999 ChangingOutput {
1000 frame: Vec::new(),
1001 output: Arc::clone(&output),
1002 reply: Some(reply),
1003 target: target.clone(),
1004 mode,
1005 modified,
1006 changed: false,
1007 },
1008 )
1009 .unwrap();
1010 let output = output.lock().unwrap();
1011 let mut reader = Reader::new(output.as_slice());
1012 let mut events = Vec::new();
1013 while let Some((_, _, event)) = reader.read().unwrap() {
1014 events.push(event);
1015 }
1016 failure(&events, ErrorCode::Conflict);
1017 assert_eq!(publication_verifications(&events).len(), 1);
1018 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
1019 assert_eq!(terminal(&events).retained_partial_count, 0);
1020 if mode == 2 {
1021 assert!(!target.exists());
1022 } else {
1023 assert_eq!(fs::read(&target).unwrap(), USER_EDIT);
1024 }
1025 assert_eq!(
1026 fs::read_dir(s.0.join("output")).unwrap().count(),
1027 if mode == 2 { 16 } else { 17 }
1028 );
1029 assert_eq!(hashes(&paths), before);
1030 }
1031}