team-ljyzipelo

공개

재해시 후 대상 변경을 확인하고 임시 조각을 격리함

작성자
시로사키 하나
작성 시각
커밋
58912982c66749b44723a6ef6019d63cb8bbda64
부모
12294c3
이 시점의 파일 보기

변경된 파일 3개

+274-11
수정experiments/rust-archive-worker/src/filesystem.rs+3-1
@@ -780,6 +780,8 @@ pub(crate) fn publish_reader_steps(
780780 &mut PublicationMonitor(check),
781781 );
782782 let mut finish = written.and(closed).and_then(|_| {
783추가: check(PublishStep::Commit)?;
784추가: // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
783785 if let Some(expected) = replace {
784786 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
785787 != Some(expected)
@@ -787,7 +789,7 @@ pub(crate) fn publish_reader_steps(
787789 return Err(ErrorCode::Conflict);
788790 }
789791 }
790삭제: check(PublishStep::Commit)
792추가: Ok(())
791793 });
792794 let mut temp_consumed = false;
793795 if finish.is_ok() {
수정tests/rust-archive-worker/split_capture.rs+89-10
@@ -4,15 +4,27 @@ static NEXT: AtomicU64 = AtomicU64::new(0);
44struct Scratch(PathBuf);
55impl Scratch {
66 fn new() -> Self {
7삭제: let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8삭제: .join("../../tests/rust-archive-worker/split-runs")
9삭제: .join(format!(
10삭제: "{}-{}",
11삭제: std::process::id(),
12삭제: NEXT.fetch_add(1, Ordering::Relaxed)
13삭제: ));
14삭제: std::fs::create_dir_all(&path).unwrap();
15삭제: Self(path.canonicalize().unwrap())
7추가: let root = std::env::var_os("TMPDIR")
8추가: .map(PathBuf::from)
9추가: .unwrap_or_else(|| {
10추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
11추가: });
12추가: std::fs::create_dir_all(&root).unwrap();
13추가: let path = root.canonicalize().unwrap().join(format!(
14추가: "zipelo-split-capture-{}-{}",
15추가: std::process::id(),
16추가: NEXT.fetch_add(1, Ordering::Relaxed)
17추가: ));
18추가: let builder = std::fs::DirBuilder::new();
19추가: #[cfg(unix)]
20추가: let mut builder = builder;
21추가: #[cfg(unix)]
22추가: {
23추가: use std::os::unix::fs::DirBuilderExt;
24추가: builder.mode(0o700);
25추가: }
26추가: builder.create(&path).unwrap();
27추가: Self(path)
1628 }
1729 fn split(&self, count: usize) -> Vec<u8> {
1830 let bytes = include_bytes!("fixtures/7z/copy.7z");
@@ -42,7 +54,7 @@ impl Scratch {
4254}
4355impl Drop for Scratch {
4456 fn drop(&mut self) {
45삭제: let _ = std::fs::remove_dir_all(&self.0);
57추가: std::fs::remove_dir_all(&self.0).expect("분할 조각 임시 폴더 정리에 실패함");
4658 }
4759}
4860fn code<T>(result: Result<T>) -> ErrorCode {
@@ -404,3 +416,70 @@ fn disappearing_known_tail_is_a_source_change_before_reopen() {
404416 ErrorCode::SourceChanged
405417 );
406418}
419추가:
420추가: #[test]
421추가: fn scratch_uses_tmpdir_and_cleans_all_split_parts() {
422추가: let root = std::env::var_os("TMPDIR")
423추가: .map(PathBuf::from)
424추가: .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp"));
425추가: let path = {
426추가: let s = Scratch::new();
427추가: let root = root.canonicalize().unwrap();
428추가: assert_eq!(s.0.parent(), Some(root.as_path()));
429추가: s.split(11);
430추가: assert_eq!(std::fs::read_dir(&s.0).unwrap().count(), 11);
431추가: s.0.clone()
432추가: };
433추가: assert!(!path.exists());
434추가: }
435추가:
436추가: #[test]
437추가: fn scratch_exit_child() {
438추가: if std::env::var_os("ZIPELO_SPLIT_SCRATCH_EXIT_TEST").is_none() {
439추가: return;
440추가: }
441추가: let s = Scratch::new();
442추가: s.split(3);
443추가: // Drop이 실행되지 않는 종료를 재현함.
444추가: std::process::exit(73);
445추가: }
446추가:
447추가: #[test]
448추가: fn scratch_abrupt_exit_leaves_parts_only_under_tmpdir() {
449추가: let path = {
450추가: let s = Scratch::new();
451추가: let status = std::process::Command::new(std::env::current_exe().unwrap())
452추가: .args([
453추가: "--exact",
454추가: "split_seven_zip::tests::scratch_exit_child",
455추가: "--test-threads=1",
456추가: ])
457추가: .env("TMPDIR", &s.0)
458추가: .env("ZIPELO_SPLIT_SCRATCH_EXIT_TEST", "1")
459추가: .output()
460추가: .unwrap();
461추가: assert_eq!(status.status.code(), Some(73), "{status:?}");
462추가: let entries = std::fs::read_dir(&s.0)
463추가: .unwrap()
464추가: .collect::<std::io::Result<Vec<_>>>()
465추가: .unwrap();
466추가: assert_eq!(entries.len(), 1);
467추가: let leftover = entries[0].path();
468추가: assert_eq!(leftover.parent(), Some(s.0.as_path()));
469추가: assert!(
470추가: leftover
471추가: .file_name()
472추가: .unwrap()
473추가: .to_str()
474추가: .unwrap()
475추가: .starts_with("zipelo-split-capture-")
476추가: );
477추가: assert_eq!(std::fs::read_dir(&leftover).unwrap().count(), 3);
478추가: assert_eq!(
479추가: std::fs::read(leftover.join("sample.7z.001")).unwrap().len(),
480추가: include_bytes!("fixtures/7z/copy.7z").len() / 3
481추가: );
482추가: s.0.clone()
483추가: };
484추가: assert!(!path.exists());
485추가: }
수정tests/rust-archive-worker/split_runtime.rs+182-0
@@ -807,3 +807,185 @@ fn split_publication_changed_source_stops_before_creating_the_first_directory()
807807 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
808808 assert_ne!(hashes(&paths), before);
809809}
810추가:
811추가: #[test]
812추가: fn 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추가: }