team-ljyzipelo

공개
991줄33 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_keep_the_existing_unsupported_policy() {
540 for name in ["encrypted-header", "encrypted-body"] {
541 let s = Scratch::new();
542 let paths = reference_fixture(&s, name);
543 let before = hashes(&paths);
544 directory(&s, "output");
545 let result = execute(request(&s, None, Selection::All));
546 failure(&result, ErrorCode::UnsupportedFeature);
547 assert!(
548 !result
549 .iter()
550 .any(|event| matches!(event, Message::PasswordRequired { .. }))
551 );
552 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
553 assert_eq!(hashes(&paths), before);
554 }
555}
556
557fn publication_fixture(s: &Scratch, existing: bool, with_file: bool) -> Vec<PathBuf> {
558 assert!(
559 Command::new("python3")
560 .env("PYTHONDONTWRITEBYTECODE", "1")
561 .arg(
562 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
563 .join("../../tests/rust-archive-worker/split_publication_cases.py")
564 )
565 .arg(&s.0)
566 .arg(if with_file { "file" } else { "directories" })
567 .status()
568 .unwrap()
569 .success()
570 );
571 directory(s, "output");
572 if existing {
573 for index in 0..16 {
574 directory(s, &format!("output/d{index:03}"));
575 }
576 }
577 (1..=5)
578 .map(|index| s.0.join(format!("sample.7z.{index:03}")))
579 .take_while(|path| path.is_file())
580 .collect()
581}
582fn publication_verifications(events: &[Message]) -> Vec<usize> {
583 events
584 .iter()
585 .enumerate()
586 .filter_map(|(index, event)| {
587 matches!(
588 event,
589 Message::Progress {
590 stage: Stage::Verify,
591 processed_bytes: 0,
592 total_bytes: None,
593 ..
594 }
595 )
596 .then_some(index)
597 })
598 .collect()
599}
600fn publication_request(s: &Scratch) -> GuardedStart {
601 GuardedStart {
602 start: request(s, None, Selection::All),
603 ceiling: Limits::default(),
604 interactive: true,
605 }
606}
607
608#[test]
609fn split_publication_verifies_once_for_fresh_or_many_existing_directories() {
610 for existing in [false, true] {
611 let s = Scratch::new();
612 let paths = publication_fixture(&s, existing, true);
613 let before = hashes(&paths);
614 let events = guarded::run(&s, publication_request(&s), |_| None);
615 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
616 let verifies = publication_verifications(&events);
617 assert_eq!(verifies.len(), 1, "existing={existing}: {events:?}");
618 let first_output = events
619 .iter()
620 .position(|event| matches!(event, Message::Output { .. }))
621 .unwrap();
622 assert!(verifies[0] < first_output);
623 if existing {
624 let write = events
625 .iter()
626 .position(|event| {
627 matches!(
628 event,
629 Message::Progress {
630 stage: Stage::Write,
631 ..
632 }
633 )
634 })
635 .unwrap();
636 assert!(write < verifies[0]);
637 }
638 assert_eq!(
639 terminal(&events).created_count,
640 if existing { 1 } else { 17 }
641 );
642 assert_eq!(
643 fs::read(s.0.join("output/payload.bin")).unwrap(),
644 (0..=255u8).cycle().take(1024 * 1024).collect::<Vec<_>>()
645 );
646 assert_eq!(hashes(&paths), before);
647 }
648}
649
650#[test]
651fn split_publication_existing_directories_do_not_cache_before_conflict_changes() {
652 let s = Scratch::new();
653 let paths = publication_fixture(&s, true, true);
654 fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
655 let mut changed = None;
656 let events = guarded::run(&s, publication_request(&s), |event| {
657 if let Message::ConflictRequired { challenge_id, .. } = event {
658 let mut data = fs::read(&paths[1]).unwrap();
659 data[0] ^= 1;
660 fs::write(&paths[1], data).unwrap();
661 changed = Some(hashes(&paths));
662 return Some(vec![Message::ConflictReply {
663 challenge_id: *challenge_id,
664 choice: ConflictChoice::Overwrite,
665 apply_to_remaining: false,
666 }]);
667 }
668 None
669 });
670 failure(&events, ErrorCode::SourceChanged);
671 let verifies = publication_verifications(&events);
672 assert_eq!(verifies.len(), 1, "{events:?}");
673 let conflict = events
674 .iter()
675 .position(|event| matches!(event, Message::ConflictRequired { .. }))
676 .unwrap();
677 assert!(conflict < verifies[0]);
678 assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
679 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 17);
680 assert_eq!(hashes(&paths), changed.unwrap());
681 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
682}
683
684#[test]
685fn split_publication_no_outputs_verify_once_and_cancel_does_not_rehash() {
686 for mode in 0..3 {
687 let s = Scratch::new();
688 let paths = publication_fixture(&s, true, mode != 0);
689 let before = hashes(&paths);
690 if mode != 0 {
691 fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
692 }
693 let events = guarded::run(&s, publication_request(&s), |event| {
694 if let Message::ConflictRequired { challenge_id, .. } = event {
695 return Some(if mode == 2 {
696 vec![Message::Cancel]
697 } else {
698 vec![Message::ConflictReply {
699 challenge_id: *challenge_id,
700 choice: ConflictChoice::Skip,
701 apply_to_remaining: false,
702 }]
703 });
704 }
705 None
706 });
707 assert_eq!(
708 terminal(&events).outcome,
709 if mode == 2 {
710 Outcome::Cancelled
711 } else {
712 Outcome::Completed
713 },
714 "{events:?}"
715 );
716 assert_eq!(
717 publication_verifications(&events).len(),
718 usize::from(mode != 2),
719 "{events:?}"
720 );
721 assert_eq!(terminal(&events).publication, Publication::None);
722 assert_eq!(terminal(&events).created_count, 0);
723 assert!(
724 !events
725 .iter()
726 .any(|event| matches!(event, Message::Output { .. }))
727 );
728 if mode != 0 {
729 assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
730 }
731 assert_eq!(hashes(&paths), before);
732 }
733}
734
735#[test]
736fn split_publication_changed_source_stops_before_creating_the_first_directory() {
737 use std::sync::{Arc, Mutex};
738 struct ChangingOutput {
739 frame: Vec<u8>,
740 output: Arc<Mutex<Vec<u8>>>,
741 path: PathBuf,
742 changed: bool,
743 }
744 impl Write for ChangingOutput {
745 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
746 self.frame.extend_from_slice(bytes);
747 Ok(bytes.len())
748 }
749 fn flush(&mut self) -> std::io::Result<()> {
750 let event = {
751 let mut output = self.output.lock().unwrap();
752 output.extend_from_slice(&self.frame);
753 let mut reader = Reader::new(output.as_slice());
754 let mut last = None;
755 while let Some((_, _, event)) = reader.read()? {
756 last = Some(event);
757 }
758 last.unwrap()
759 };
760 if !self.changed
761 && matches!(
762 event,
763 Message::Progress {
764 stage: Stage::Verify,
765 processed_bytes: 0,
766 total_bytes: None,
767 ..
768 }
769 )
770 {
771 // 검증 시작 프레임을 보낼 때 바꿔 스케줄링 경합 없이 생성 직전을 재현함.
772 let mut data = fs::read(&self.path)?;
773 data[0] ^= 1;
774 fs::write(&self.path, data)?;
775 self.changed = true;
776 }
777 self.frame.clear();
778 Ok(())
779 }
780 }
781 let s = Scratch::new();
782 let paths = publication_fixture(&s, false, true);
783 let before = hashes(&paths);
784 let mut input = Vec::new();
785 Writer::new(&mut input, 17)
786 .send(&Message::Start(request(&s, None, Selection::All)))
787 .unwrap();
788 let output = Arc::new(Mutex::new(Vec::new()));
789 zipelo_archive_worker::runtime::serve(
790 std::io::Cursor::new(input),
791 ChangingOutput {
792 frame: Vec::new(),
793 output: Arc::clone(&output),
794 path: paths[1].clone(),
795 changed: false,
796 },
797 )
798 .unwrap();
799 let output = output.lock().unwrap();
800 let mut reader = Reader::new(output.as_slice());
801 let mut events = Vec::new();
802 while let Some((_, _, event)) = reader.read().unwrap() {
803 events.push(event);
804 }
805 failure(&events, ErrorCode::SourceChanged);
806 assert_eq!(publication_verifications(&events).len(), 1);
807 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
808 assert_ne!(hashes(&paths), before);
809}
810
811#[test]
812fn split_publication_target_changes_during_verification_are_preserved() {
813 use std::io::{Cursor, Read};
814 use std::sync::{Arc, Mutex, mpsc};
815 const USER_EDIT: &[u8] = b"new user edit after overwrite approval";
816 struct Input {
817 receive: mpsc::Receiver<Vec<u8>>,
818 pending: Cursor<Vec<u8>>,
819 }
820 impl Read for Input {
821 fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
822 if bytes.is_empty() {
823 return Ok(0);
824 }
825 loop {
826 let count = self.pending.read(bytes)?;
827 if count != 0 {
828 return Ok(count);
829 }
830 match self
831 .receive
832 .recv_timeout(std::time::Duration::from_secs(20))
833 {
834 Ok(frame) => self.pending = Cursor::new(frame),
835 Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(0),
836 Err(error) => return Err(std::io::Error::other(error)),
837 }
838 }
839 }
840 }
841 struct Reply {
842 send: mpsc::Sender<Vec<u8>>,
843 pending: Vec<u8>,
844 }
845 impl Write for Reply {
846 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
847 self.pending.extend_from_slice(bytes);
848 Ok(bytes.len())
849 }
850 fn flush(&mut self) -> std::io::Result<()> {
851 self.send
852 .send(std::mem::take(&mut self.pending))
853 .map_err(std::io::Error::other)
854 }
855 }
856 struct ChangingOutput {
857 frame: Vec<u8>,
858 output: Arc<Mutex<Vec<u8>>>,
859 reply: Option<Writer<Reply>>,
860 target: PathBuf,
861 mode: u8,
862 modified: Option<std::time::SystemTime>,
863 changed: bool,
864 }
865 impl Write for ChangingOutput {
866 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
867 self.frame.extend_from_slice(bytes);
868 Ok(bytes.len())
869 }
870 fn flush(&mut self) -> std::io::Result<()> {
871 let event = {
872 let mut output = self.output.lock().unwrap();
873 output.extend_from_slice(&self.frame);
874 let mut reader = Reader::new(output.as_slice());
875 let mut last = None;
876 while let Some((_, _, event)) = reader.read()? {
877 last = Some(event);
878 }
879 last.unwrap()
880 };
881 match event {
882 Message::ConflictRequired { challenge_id, .. } => {
883 self.reply.as_mut().unwrap().send(&Message::ConflictReply {
884 challenge_id,
885 choice: ConflictChoice::Overwrite,
886 apply_to_remaining: false,
887 })?;
888 }
889 Message::Progress {
890 stage: Stage::Verify,
891 processed_bytes: 0,
892 total_bytes: None,
893 ..
894 } if !self.changed => {
895 // 재해시 시작과 동기화해 승인 이후 대상 변경을 재현함.
896 match self.mode {
897 0 => {
898 fs::write(&self.target, USER_EDIT)?;
899 fs::File::options()
900 .write(true)
901 .open(&self.target)?
902 .set_times(fs::FileTimes::new().set_modified(
903 self.modified.unwrap() + std::time::Duration::from_secs(2),
904 ))?;
905 }
906 1 => {
907 let old = self.target.with_file_name("approved-old");
908 fs::rename(&self.target, &old)?;
909 fs::write(&self.target, USER_EDIT)?;
910 fs::File::options()
911 .write(true)
912 .open(&self.target)?
913 .set_times(
914 fs::FileTimes::new().set_modified(self.modified.unwrap()),
915 )?;
916 fs::remove_file(old)?;
917 }
918 2 => fs::remove_file(&self.target)?,
919 3 => fs::write(&self.target, USER_EDIT)?,
920 _ => unreachable!(),
921 }
922 self.changed = true;
923 }
924 Message::Terminal(_) => self.reply = None,
925 _ => {}
926 }
927 self.frame.clear();
928 Ok(())
929 }
930 }
931 for mode in 0..4 {
932 let s = Scratch::new();
933 let paths = publication_fixture(&s, true, true);
934 let before = hashes(&paths);
935 let target = s.0.join("output/payload.bin");
936 let modified = if mode == 3 {
937 None
938 } else {
939 fs::write(&target, vec![b'o'; USER_EDIT.len()]).unwrap();
940 Some(fs::metadata(&target).unwrap().modified().unwrap())
941 };
942 let (send, receive) = mpsc::channel();
943 let mut reply = Writer::new(
944 Reply {
945 send,
946 pending: Vec::new(),
947 },
948 17,
949 );
950 reply
951 .send(&Message::StartGuarded(publication_request(&s)))
952 .unwrap();
953 let output = Arc::new(Mutex::new(Vec::new()));
954 zipelo_archive_worker::runtime::serve(
955 Input {
956 receive,
957 pending: Cursor::new(Vec::new()),
958 },
959 ChangingOutput {
960 frame: Vec::new(),
961 output: Arc::clone(&output),
962 reply: Some(reply),
963 target: target.clone(),
964 mode,
965 modified,
966 changed: false,
967 },
968 )
969 .unwrap();
970 let output = output.lock().unwrap();
971 let mut reader = Reader::new(output.as_slice());
972 let mut events = Vec::new();
973 while let Some((_, _, event)) = reader.read().unwrap() {
974 events.push(event);
975 }
976 failure(&events, ErrorCode::Conflict);
977 assert_eq!(publication_verifications(&events).len(), 1);
978 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
979 assert_eq!(terminal(&events).retained_partial_count, 0);
980 if mode == 2 {
981 assert!(!target.exists());
982 } else {
983 assert_eq!(fs::read(&target).unwrap(), USER_EDIT);
984 }
985 assert_eq!(
986 fs::read_dir(s.0.join("output")).unwrap().count(),
987 if mode == 2 { 16 } else { 17 }
988 );
989 assert_eq!(hashes(&paths), before);
990 }
991}