team-ljyzipelo

공개

목록과 미리보기 임시 파일을 여유 있는 위치에 저장함

작성자
시로사키 하나
작성 시각
커밋
c942f313e43826b3cb1732393f1c3066cbfb36e7
부모
ccb80fd
이 시점의 파일 보기

변경된 파일 7개

+754-21
수정experiments/rust-archive-worker/src/runtime.rs+3-0
@@ -595,6 +595,9 @@ impl<W: Write> Job<W> {
595595 .and_then(|path| Dir::root(&path).ok())
596596 .map(|root| crate::spool::place_in(&root))
597597 .transpose()?,
598추가: Action::List { archive } | Action::Preview { archive, .. } => {
599추가: Some(crate::spool::fallback_for(&archive.to_path()?))
600추가: }
598601 _ => None,
599602 };
600603 if let Some(budget) = &self.budget {
수정experiments/rust-archive-worker/src/spool.rs+160-21
@@ -8,27 +8,107 @@ use std::{
88
99type Result<T> = std::result::Result<T, ErrorCode>;
1010
11추가: enum Placement {
12추가: Fixed(filesystem::Dir),
13추가: Fallback {
14추가: source_parent: std::path::PathBuf,
15추가: next: usize,
16추가: other_error: Option<ErrorCode>,
17추가: },
18추가: }
19추가:
1120thread_local! {
12삭제: // 작업 스레드가 지정한 임시 파일 위치. 없으면 시스템 임시 폴더를 사용함.
13삭제: static LOCATION: std::cell::RefCell<Option<filesystem::Dir>> =
21추가: // 작업 스레드의 임시 파일 정책만 보관함.
22추가: static LOCATION: std::cell::RefCell<Option<Placement>> =
1423 const { std::cell::RefCell::new(None) };
1524 // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함.
1625 static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1726}
1827
19삭제: /// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨.
20삭제: /// 작업은 한 스레드에서 실행되므로 다른 작업이나 시험에 섞이지 않음.
21삭제: pub(crate) struct Location(());
28추가: pub(crate) struct Location(Option<Placement>);
2229impl Drop for Location {
2330 fn drop(&mut self) {
24삭제: LOCATION.with(|location| *location.borrow_mut() = None);
31추가: LOCATION.with(|location| *location.borrow_mut() = self.0.take());
2532 }
2633}
2734pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
28삭제: let dir = dir.duplicate()?;
29삭제: LOCATION.with(|location| *location.borrow_mut() = Some(dir));
35추가: let placement = Placement::Fixed(dir.duplicate()?);
36추가: LEFTOVER.with(|leftover| leftover.set(false));
37추가: Ok(LOCATION.with(|location| Location(location.replace(Some(placement)))))
38추가: }
39추가: pub(crate) fn fallback_for(path: &Path) -> Location {
3040 LEFTOVER.with(|leftover| leftover.set(false));
31삭제: Ok(Location(()))
41추가: let placement = Placement::Fallback {
42추가: source_parent: path.parent().unwrap_or(Path::new("")).to_path_buf(),
43추가: next: 0,
44추가: other_error: None,
45추가: };
46추가: LOCATION.with(|location| Location(location.replace(Some(placement))))
47추가: }
48추가:
49추가: #[cfg(target_os = "linux")]
50추가: fn private_directory(path: &Path) -> Result<filesystem::Dir> {
51추가: if !path.is_absolute() {
52추가: return Err(ErrorCode::Io);
53추가: }
54추가: match filesystem::Dir::root(path) {
55추가: Ok(dir) => Ok(dir),
56추가: Err(error) => {
57추가: if !matches!(std::fs::symlink_metadata(path), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound)
58추가: {
59추가: return Err(error);
60추가: }
61추가: let parent = private_directory(path.parent().ok_or(ErrorCode::Io)?)?;
62추가: let name = path
63추가: .file_name()
64추가: .and_then(|n| n.to_str())
65추가: .ok_or(ErrorCode::Io)?;
66추가: parent.child(name, true)?.ok_or(ErrorCode::Io)
67추가: }
68추가: }
69추가: }
70추가: fn cache_directory() -> Result<filesystem::Dir> {
71추가: #[cfg(target_os = "linux")]
72추가: {
73추가: let base = match std::env::var_os("XDG_CACHE_HOME").filter(|p| !p.is_empty()) {
74추가: Some(path) => std::path::PathBuf::from(path),
75추가: None => std::path::PathBuf::from(std::env::var_os("HOME").ok_or(ErrorCode::Io)?)
76추가: .join(".cache"),
77추가: };
78추가: private_directory(&base)?
79추가: .child("zipelo", true)?
80추가: .ok_or(ErrorCode::Io)
81추가: }
82추가: #[cfg(windows)]
83추가: {
84추가: let base = std::path::PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or(ErrorCode::Io)?);
85추가: if !base.is_absolute() {
86추가: return Err(ErrorCode::Io);
87추가: }
88추가: filesystem::Dir::root(&base)?
89추가: .child("Zipelo", true)?
90추가: .ok_or(ErrorCode::Io)?
91추가: .child("Temp", true)?
92추가: .ok_or(ErrorCode::Io)
93추가: }
94추가: }
95추가: fn next_after_full() -> Result<bool> {
96추가: LOCATION.with(|location| {
97추가: let mut location = location.borrow_mut();
98추가: match location.as_mut() {
99추가: Some(Placement::Fallback {
100추가: next, other_error, ..
101추가: }) => {
102추가: *next += 1;
103추가: if *next >= 3 {
104추가: Err(other_error.unwrap_or(ErrorCode::DiskFull))
105추가: } else {
106추가: Ok(true)
107추가: }
108추가: }
109추가: _ => Ok(false),
110추가: }
111추가: })
32112}
33113
34114/// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로
@@ -43,25 +123,64 @@ pub(crate) fn take_leftover() -> bool {
43123 LEFTOVER.with(|leftover| leftover.replace(false))
44124}
45125
126추가: /// 실패한 단계의 임시 파일이 닫힌 뒤 다음 위치에서 다시 시도함.
127추가: pub(crate) fn retry_full<T>(mut operation: impl FnMut() -> Result<T>) -> Result<T> {
128추가: loop {
129추가: match operation() {
130추가: Err(ErrorCode::DiskFull) if next_after_full()? => continue,
131추가: result => return result,
132추가: }
133추가: }
134추가: }
135추가:
46136pub(crate) fn random_name() -> Result<String> {
47137 let mut random = [0; 16];
48138 crate::crypto::random(&mut random)?;
49139 Ok(random.iter().map(|b| format!("{b:02x}")).collect())
50140}
51141
52삭제: /// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠.
53삭제: /// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음.
54삭제: /// 출력 폴더에 만들지 못하면(읽기 전용, 공간 부족 등) 이 작업의 남은 임시 파일은 모두
55삭제: /// 기존 시스템 임시 폴더에 둠. 그러면 동작과 오류 우선순위가 이전과 같아지며, 출력 폴더
56삭제: /// 문제는 원래의 출력 확인 지점에서 보고됨.
142추가: /// 지정한 정책에 따라 이름 없는 임시 파일을 만듦.
57143pub(crate) fn temporary() -> Result<File> {
58삭제: let placed =
59삭제: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary));
60삭제: match placed {
61삭제: Some(Ok(file)) => return Ok(file),
62삭제: Some(Err(_)) => LOCATION.with(|location| *location.borrow_mut() = None),
63삭제: None => {}
64삭제: }
144추가: let placed = LOCATION.with(|location| {
145추가: let mut location = location.borrow_mut();
146추가: match location.as_mut() {
147추가: Some(Placement::Fixed(dir)) => match dir.temporary() {
148추가: Ok(file) => Some(Ok(file)),
149추가: Err(_) => {
150추가: *location = None;
151추가: None
152추가: }
153추가: },
154추가: Some(Placement::Fallback {
155추가: source_parent,
156추가: next,
157추가: other_error,
158추가: }) => {
159추가: while *next < 3 {
160추가: let file = match *next {
161추가: 0 => cache_directory().and_then(|dir| dir.temporary()),
162추가: 1 => filesystem::Dir::root(source_parent).and_then(|dir| dir.temporary()),
163추가: _ => system_temporary(),
164추가: };
165추가: match file {
166추가: Ok(file) => return Some(Ok(file)),
167추가: Err(error) => {
168추가: if error != ErrorCode::DiskFull {
169추가: *other_error = Some(ErrorCode::Io);
170추가: }
171추가: *next += 1;
172추가: }
173추가: }
174추가: }
175추가: Some(Err(other_error.unwrap_or(ErrorCode::DiskFull)))
176추가: }
177추가: None => None,
178추가: }
179추가: });
180추가: placed.unwrap_or_else(system_temporary)
181추가: }
182추가:
183추가: fn system_temporary() -> Result<File> {
65184 #[cfg(target_os = "linux")]
66185 {
67186 use std::os::unix::fs::OpenOptionsExt;
@@ -193,6 +312,26 @@ impl Snapshot {
193312 source: &mut File,
194313 limit: u64,
195314 step: &mut impl FnMut(Step) -> Result<()>,
315추가: ) -> Result<Self> {
316추가: let original = source.metadata().map_err(|_| ErrorCode::Io)?;
317추가: loop {
318추가: step(Step::Check)?;
319추가: let current = source.metadata().map_err(|_| ErrorCode::Io)?;
320추가: if current.len() != original.len()
321추가: || current.modified().ok() != original.modified().ok()
322추가: {
323추가: return Err(ErrorCode::SourceChanged);
324추가: }
325추가: match Self::capture_once(source, limit, step) {
326추가: Err(ErrorCode::DiskFull) if next_after_full()? => continue,
327추가: result => return result,
328추가: }
329추가: }
330추가: }
331추가: fn capture_once(
332추가: source: &mut File,
333추가: limit: u64,
334추가: step: &mut impl FnMut(Step) -> Result<()>,
196335 ) -> Result<Self> {
197336 let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
198337 if !before.is_file() {
수정experiments/rust-archive-worker/src/streaming.rs+13-0
@@ -74,6 +74,19 @@ impl Catalog {
7474 password: Option<&[u8]>,
7575 selected: Option<u32>,
7676 check: &mut impl crate::resources::Monitor,
77추가: ) -> Result<Self> {
78추가: spool::retry_full(|| {
79추가: Self::open_selected_once(source, len, limits, decode, password, selected, check)
80추가: })
81추가: }
82추가: fn open_selected_once(
83추가: source: &mut File,
84추가: len: u64,
85추가: limits: Limits,
86추가: decode: bool,
87추가: password: Option<&[u8]>,
88추가: selected: Option<u32>,
89추가: check: &mut impl crate::resources::Monitor,
7790 ) -> Result<Self> {
7891 let mut magic = [0; 6];
7992 let n = len.min(6) as usize;
수정tests/rust-archive-worker/main.rs+3-0
@@ -1637,3 +1637,6 @@ mod partial_output;
16371637
16381638#[cfg(target_os = "linux")]
16391639mod spool_location;
1640추가:
1641추가: #[cfg(target_os = "linux")]
1642추가: mod spool_fallback;
추가tests/rust-archive-worker/spool_fallback.rs+421-0
@@ -0,0 +1,421 @@
1추가: use super::*;
2추가: use std::{
3추가: io::Read,
4추가: os::unix::fs::{DirBuilderExt, PermissionsExt},
5추가: process::Child,
6추가: sync::mpsc,
7추가: time::Duration,
8추가: };
9추가:
10추가: struct Running(Child);
11추가: impl Drop for Running {
12추가: fn drop(&mut self) {
13추가: let _ = self.0.kill();
14추가: let _ = self.0.wait();
15추가: }
16추가: }
17추가:
18추가: const PAYLOAD: &[u8] = b"spool fallback preview\n";
19추가: struct Case {
20추가: scratch: Scratch,
21추가: }
22추가: impl Case {
23추가: fn new() -> Self {
24추가: let scratch = Scratch::new();
25추가: for name in ["cache", "archive", "system"] {
26추가: fs::DirBuilder::new()
27추가: .mode(0o700)
28추가: .create(scratch.0.join(name))
29추가: .unwrap();
30추가: }
31추가: assert!(
32추가: Command::new("python3")
33추가: .arg("-B")
34추가: .arg(
35추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
36추가: .join("../../tests/rust-archive-worker/spool_fallback_cases.py")
37추가: )
38추가: .arg(&scratch.0)
39추가: .status()
40추가: .unwrap()
41추가: .success()
42추가: );
43추가: Self { scratch }
44추가: }
45추가: fn run(&self, action: Action, phase: &str, mask: u8, named: bool) -> Vec<Message> {
46추가: let s = &self.scratch;
47추가: let mut command = s.worker();
48추가: command
49추가: .env("XDG_CACHE_HOME", s.0.join("cache"))
50추가: .env(
51추가: "TMPDIR",
52추가: if phase == "real" {
53추가: PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap())
54추가: } else {
55추가: s.0.join("system")
56추가: },
57추가: )
58추가: .env("HOME", &s.0);
59추가: if phase == "home" {
60추가: command.env_remove("XDG_CACHE_HOME");
61추가: }
62추가: if phase == "changed" {
63추가: command.env(
64추가: "ZIPELO_SPOOL_SOURCE",
65추가: self.archive("zip").to_path().unwrap(),
66추가: );
67추가: }
68추가: if phase != "real" {
69추가: let library = s.0.join("location.so");
70추가: if !library.exists() {
71추가: assert!(
72추가: Command::new("cc")
73추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
74추가: .arg(
75추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
76추가: .join("../../tests/rust-archive-worker/spool_location_fault.c")
77추가: )
78추가: .args(["-ldl", "-o"])
79추가: .arg(&library)
80추가: .status()
81추가: .unwrap()
82추가: .success()
83추가: );
84추가: }
85추가: command
86추가: .env("LD_PRELOAD", library)
87추가: .env("ZIPELO_SPOOL_PHASE", phase)
88추가: .env("ZIPELO_SPOOL_MASK", mask.to_string())
89추가: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
90추가: if named {
91추가: command.env("ZIPELO_SPOOL_NAMED", "1");
92추가: }
93추가: }
94추가: let mut child = Running(
95추가: command
96추가: .stdin(Stdio::piped())
97추가: .stdout(Stdio::piped())
98추가: .stderr(Stdio::piped())
99추가: .spawn()
100추가: .unwrap(),
101추가: );
102추가: let preview = matches!(action, Action::Preview { .. });
103추가: let start = Start {
104추가: action,
105추가: limits: Limits::default(),
106추가: };
107추가: let message = if preview {
108추가: Message::StartGuarded(GuardedStart {
109추가: start,
110추가: ceiling: Limits::default(),
111추가: interactive: true,
112추가: })
113추가: } else {
114추가: Message::Start(start)
115추가: };
116추가: let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17));
117추가: writer.as_mut().unwrap().send(&message).unwrap();
118추가: let stdout = child.0.stdout.take().unwrap();
119추가: let mut stderr = child.0.stderr.take().unwrap();
120추가: let (send, receive) = mpsc::sync_channel(128);
121추가: let reader = std::thread::spawn(move || {
122추가: let mut reader = Reader::new(stdout);
123추가: loop {
124추가: let frame = reader.read();
125추가: let done = !matches!(frame, Ok(Some(_)));
126추가: if send.send(frame).is_err() || done {
127추가: break;
128추가: }
129추가: }
130추가: });
131추가: let mut events = Vec::new();
132추가: loop {
133추가: let Some((job, _, event)) = receive
134추가: .recv_timeout(Duration::from_secs(30))
135추가: .expect("worker timeout")
136추가: .unwrap()
137추가: else {
138추가: break;
139추가: };
140추가: assert_eq!(job, 17);
141추가: assert!(
142추가: !matches!(
143추가: event,
144추가: Message::ResourceRequired { .. } | Message::PasswordRequired { .. }
145추가: ),
146추가: "{event:?}"
147추가: );
148추가: if matches!(event, Message::Terminal(_)) {
149추가: drop(writer.take());
150추가: }
151추가: events.push(event);
152추가: }
153추가: assert!(child.0.wait().unwrap().success(), "{events:?}");
154추가: let mut errors = Vec::new();
155추가: stderr.read_to_end(&mut errors).unwrap();
156추가: assert!(errors.is_empty(), "{errors:?}");
157추가: reader.join().unwrap();
158추가: assert_eq!(
159추가: events
160추가: .iter()
161추가: .filter(|e| matches!(e, Message::Terminal(_)))
162추가: .count(),
163추가: 1
164추가: );
165추가: self.clean();
166추가: events
167추가: }
168추가: fn archive(&self, format: &str) -> NativePath {
169추가: self.scratch.path(&format!("archive/input.{format}"))
170추가: }
171추가: fn list(&self, format: &str, phase: &str, mask: u8, named: bool) -> Vec<Message> {
172추가: self.run(
173추가: Action::List {
174추가: archive: self.archive(format),
175추가: },
176추가: phase,
177추가: mask,
178추가: named,
179추가: )
180추가: }
181추가: fn clean(&self) {
182추가: let root = &self.scratch.0;
183추가: for directory in ["cache/zipelo", ".cache/zipelo", "system"] {
184추가: let path = root.join(directory);
185추가: if path.is_dir() {
186추가: assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "{path:?}");
187추가: }
188추가: }
189추가: assert_eq!(fs::read_dir(root.join("archive")).unwrap().count(), 2);
190추가: }
191추가: fn preview(&self, format: &str, phase: &str, mask: u8, named: bool) -> Vec<Message> {
192추가: let events = self.list(format, phase, mask, named);
193추가: assert_eq!(
194추가: terminal(&events).outcome,
195추가: Outcome::Completed,
196추가: "{format}/{phase}/{mask}: {events:?}"
197추가: );
198추가: let list_id = events
199추가: .iter()
200추가: .find_map(|e| match e {
201추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
202추가: _ => None,
203추가: })
204추가: .unwrap();
205추가: let entry_id = events
206추가: .iter()
207추가: .find_map(|e| match e {
208추가: Message::Entry(entry) if entry.name == "preview.txt" => Some(entry.entry_id),
209추가: _ => None,
210추가: })
211추가: .unwrap();
212추가: self.run(
213추가: Action::Preview {
214추가: archive: self.archive(format),
215추가: list_id,
216추가: entry_id,
217추가: },
218추가: phase,
219추가: mask,
220추가: named,
221추가: )
222추가: }
223추가: fn assert_preview(&self, format: &str, phase: &str, mask: u8, named: bool) {
224추가: let path = self.scratch.0.join(format!("archive/input.{format}"));
225추가: let original = fs::read(&path).unwrap();
226추가: assert!(original.len() > 16 * 1024 * 1024);
227추가: let events = self.preview(format, phase, mask, named);
228추가: assert_eq!(
229추가: terminal(&events).outcome,
230추가: Outcome::Completed,
231추가: "{format}/{phase}/{mask}: {events:?}"
232추가: );
233추가: let mut preview = Vec::new();
234추가: for event in &events {
235추가: if let Message::PreviewChunk { data, .. } = event {
236추가: preview.extend_from_slice(data);
237추가: }
238추가: }
239추가: assert_eq!(preview, PAYLOAD);
240추가: assert!(
241추가: events
242추가: .iter()
243추가: .any(|e| matches!(e, Message::PreviewEnd { .. }))
244추가: );
245추가: assert_eq!(fs::read(path).unwrap(), original);
246추가: }
247추가: }
248추가: #[test]
249추가: fn cache_source_and_system_locations_retry_creation_space_and_partial_quota_writes() {
250추가: for named in [false, true] {
251추가: for phase in ["create", "space", "write"] {
252추가: for mask in [0, 1, 3] {
253추가: let c = Case::new();
254추가: for format in ["zip", "7z"] {
255추가: c.assert_preview(format, phase, mask, named);
256추가: }
257추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
258추가: let expected = match mask {
259추가: 0 => '0',
260추가: 1 => '1',
261추가: _ => '2',
262추가: };
263추가: assert!(trace.contains(expected), "{phase}/{mask}: {trace}");
264추가: if mask == 0 {
265추가: assert!(!trace.contains('1') && !trace.contains('2'), "{trace}");
266추가: }
267추가: if mask == 1 {
268추가: assert!(!trace.contains('2'), "{trace}");
269추가: }
270추가: }
271추가: }
272추가: }
273추가: }
274추가: #[test]
275추가: fn disk_full_requires_exhausting_all_three_locations_and_io_errors_stay_io() {
276추가: for phase in ["create", "space", "write"] {
277추가: let c = Case::new();
278추가: for format in ["zip", "7z"] {
279추가: let events = c.list(format, phase, 7, false);
280추가: assert_eq!(
281추가: terminal(&events).error,
282추가: ErrorCode::DiskFull,
283추가: "{phase}: {events:?}"
284추가: );
285추가: assert_eq!(terminal(&events).outcome, Outcome::Failed);
286추가: assert!(!events.iter().any(|e| matches!(e, Message::ListEnd { .. })));
287추가: }
288추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
289추가: for at in ['0', '1', '2'] {
290추가: assert!(trace.contains(at), "{phase}: {trace}");
291추가: }
292추가: }
293추가: let c = Case::new();
294추가: for phase in ["io", "denied"] {
295추가: let events = c.list("zip", phase, 7, false);
296추가: assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
297추가: }
298추가: }
299추가: #[test]
300추가: fn unsafe_cache_is_skipped_without_following_its_link() {
301추가: use std::os::unix::fs::symlink;
302추가: let c = Case::new();
303추가: fs::DirBuilder::new()
304추가: .mode(0o700)
305추가: .create(c.scratch.0.join("outside"))
306추가: .unwrap();
307추가: symlink(
308추가: c.scratch.0.join("outside"),
309추가: c.scratch.0.join("cache/zipelo"),
310추가: )
311추가: .unwrap();
312추가: let events = c.list("zip", "create", 0, false);
313추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
314추가: assert_eq!(
315추가: fs::read_dir(c.scratch.0.join("outside")).unwrap().count(),
316추가: 0
317추가: );
318추가: fs::remove_file(c.scratch.0.join("cache/zipelo")).unwrap();
319추가: c.clean();
320추가: }
321추가: #[test]
322추가: fn preview_decode_retries_when_snapshot_fits_but_decoded_staging_does_not() {
323추가: for named in [false, true] {
324추가: for phase in ["stage-space", "stage-write"] {
325추가: for mask in [1, 3] {
326추가: let c = Case::new();
327추가: for format in ["zip", "7z"] {
328추가: c.assert_preview(format, phase, mask, named);
329추가: }
330추가: }
331추가: let c = Case::new();
332추가: for format in ["zip", "7z"] {
333추가: let events = c.preview(format, phase, 7, named);
334추가: assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
335추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull, "{events:?}");
336추가: assert!(
337추가: !events
338추가: .iter()
339추가: .any(|event| matches!(event, Message::PreviewEnd { .. }))
340추가: );
341추가: }
342추가: }
343추가: }
344추가: }
345추가:
346추가: #[test]
347추가: fn default_home_cache_is_created_privately() {
348추가: let c = Case::new();
349추가: c.assert_preview("zip", "home", 0, false);
350추가: for name in [".cache", ".cache/zipelo"] {
351추가: assert_eq!(
352추가: fs::metadata(c.scratch.0.join(name))
353추가: .unwrap()
354추가: .permissions()
355추가: .mode()
356추가: & 0o777,
357추가: 0o700
358추가: );
359추가: }
360추가: }
361추가:
362추가: #[test]
363추가: fn source_change_during_failed_copy_prevents_retry_success() {
364추가: let c = Case::new();
365추가: let events = c.list("zip", "changed", 1, false);
366추가: assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
367추가: assert_eq!(
368추가: terminal(&events).error,
369추가: ErrorCode::SourceChanged,
370추가: "{events:?}"
371추가: );
372추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
373추가: assert!(
374추가: trace.contains('0') && !trace.contains('1') && !trace.contains('2'),
375추가: "{trace}"
376추가: );
377추가: }
378추가:
379추가: #[test]
380추가: #[ignore = "별도 VM의 작은 tmpfs 경로를 ZIPELO_SPOOL_REAL_TMP로 지정해야 함"]
381추가: fn actual_tmpfs_quota_lists_and_previews_large_zip_and_seven_zip() {
382추가: let path = PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap());
383추가: let filesystem = Command::new("stat")
384추가: .args(["-f", "-c", "%T"])
385추가: .arg(&path)
386추가: .output()
387추가: .unwrap();
388추가: assert_eq!(
389추가: String::from_utf8(filesystem.stdout).unwrap().trim(),
390추가: "tmpfs"
391추가: );
392추가: let capacity = Command::new("stat")
393추가: .args(["-f", "-c", "%S %b"])
394추가: .arg(&path)
395추가: .output()
396추가: .unwrap();
397추가: let fields: Vec<u64> = String::from_utf8(capacity.stdout)
398추가: .unwrap()
399추가: .split_whitespace()
400추가: .map(|value| value.parse().unwrap())
401추가: .collect();
402추가: let bytes = fields[0] * fields[1];
403추가: assert!(bytes > 0 && bytes < 16 * 1024 * 1024, "{bytes}");
404추가: let probe = path.join("capacity-probe");
405추가: let error = fs::write(&probe, vec![0; bytes as usize + 4096]).unwrap_err();
406추가: assert_eq!(error.kind(), std::io::ErrorKind::StorageFull);
407추가: fs::remove_file(probe).unwrap();
408추가: let c = Case::new();
409추가: for format in ["zip", "7z"] {
410추가: c.assert_preview(format, "real", 0, false);
411추가: }
412추가: assert_eq!(fs::read_dir(path).unwrap().count(), 0);
413추가: assert_eq!(
414추가: fs::metadata(c.scratch.0.join("cache/zipelo"))
415추가: .unwrap()
416추가: .permissions()
417추가: .mode()
418추가: & 0o777,
419추가: 0o700
420추가: );
421추가: }
추가tests/rust-archive-worker/spool_fallback_cases.py+18-0
@@ -0,0 +1,18 @@
1추가: """시스템 임시 폴더보다 큰 독립 ZIP과 7z 입력을 만듦."""
2추가: from pathlib import Path
3추가: import sys
4추가: import zipfile
5추가:
6추가: from seven_zip_fixtures import archive
7추가:
8추가: root = Path(sys.argv[1])
9추가: payload = b"spool fallback preview\n"
10추가: filler = bytes(range(256)) * (16 * 1024 * 1024 // 256)
11추가: with zipfile.ZipFile(
12추가: root / "archive" / "input.zip", "w", compression=zipfile.ZIP_STORED
13추가: ) as target:
14추가: target.writestr("preview.txt", payload)
15추가: target.writestr("filler.bin", filler)
16추가: (root / "archive" / "input.7z").write_bytes(
17추가: archive([("preview.txt", payload, 0x20), ("filler.bin", filler, 0x20)], method="copy")
18추가: )
추가tests/rust-archive-worker/spool_location_fault.c+136-0
@@ -0,0 +1,136 @@
1추가: #define _GNU_SOURCE
2추가: #include <dlfcn.h>
3추가: #include <errno.h>
4추가: #include <fcntl.h>
5추가: #include <stdarg.h>
6추가: #include <stdio.h>
7추가: #include <stdlib.h>
8추가: #include <string.h>
9추가: #include <sys/statvfs.h>
10추가: #include <unistd.h>
11추가:
12추가: static int (*original_openat)(int, const char *, int, ...);
13추가: static int (*original_open64)(const char *, int, ...);
14추가: static ssize_t (*original_write)(int, const void *, size_t);
15추가: static int written[3];
16추가: static int snapshot_fd = -1;
17추가:
18추가: __attribute__((constructor)) static void initialize(void) {
19추가: original_openat = dlsym(RTLD_NEXT, "openat");
20추가: original_open64 = dlsym(RTLD_NEXT, "open64");
21추가: original_write = dlsym(RTLD_NEXT, "write");
22추가: }
23추가: static int location(const char *path) {
24추가: if (strstr(path, "/cache/")) return 0;
25추가: if (strstr(path, "/archive/")) return 1;
26추가: if (strstr(path, "/system/")) return 2;
27추가: return -1;
28추가: }
29추가: static int descriptor(int fd, char *path, size_t size) {
30추가: char link[64];
31추가: path[0] = 0;
32추가: snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
33추가: ssize_t length = readlink(link, path, size - 1);
34추가: if (length < 0) return -1;
35추가: path[length] = 0;
36추가: return location(path);
37추가: }
38추가: static int affected(int at) {
39추가: const char *mask = getenv("ZIPELO_SPOOL_MASK");
40추가: return at >= 0 && mask && (atoi(mask) & (1 << at));
41추가: }
42추가: static void trace(int at) {
43추가: const char *path = getenv("ZIPELO_SPOOL_TRACE");
44추가: if (!path || at < 0) return;
45추가: int fd = original_openat(AT_FDCWD, path, O_CREAT | O_WRONLY | O_APPEND, 0600);
46추가: if (fd >= 0) {
47추가: char value = '0' + at;
48추가: original_write(fd, &value, 1);
49추가: close(fd);
50추가: }
51추가: }
52추가: static int reject(int at, int flags) {
53추가: if ((flags & O_TMPFILE) != O_TMPFILE && !(flags & O_CREAT)) return 0;
54추가: trace(at);
55추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
56추가: if (affected(at) && phase && (!strcmp(phase, "create") || !strcmp(phase, "denied"))) {
57추가: errno = !strcmp(phase, "denied") ? EACCES : EDQUOT;
58추가: return 1;
59추가: }
60추가: if (getenv("ZIPELO_SPOOL_NAMED") && (flags & O_TMPFILE) == O_TMPFILE) {
61추가: errno = EOPNOTSUPP;
62추가: return 1;
63추가: }
64추가: return 0;
65추가: }
66추가: int openat(int fd, const char *path, int flags, ...) {
67추가: mode_t mode = 0;
68추가: if ((flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE) {
69추가: va_list args;
70추가: va_start(args, flags);
71추가: mode = va_arg(args, unsigned int);
72추가: va_end(args);
73추가: }
74추가: char parent[4096], full[8192];
75추가: descriptor(fd, parent, sizeof(parent));
76추가: snprintf(full, sizeof(full), "%s/%s", parent, path);
77추가: if (reject(location(full), flags)) return -1;
78추가: int result = original_openat(fd, path, flags, mode);
79추가: if (result >= 0 && snapshot_fd < 0 && location(full) >= 0
80추가: && ((flags & O_TMPFILE) == O_TMPFILE || (flags & O_CREAT))) {
81추가: snapshot_fd = result;
82추가: }
83추가: return result;
84추가: }
85추가: int open64(const char *path, int flags, ...) {
86추가: mode_t mode = 0;
87추가: if ((flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE) {
88추가: va_list args;
89추가: va_start(args, flags);
90추가: mode = va_arg(args, unsigned int);
91추가: va_end(args);
92추가: }
93추가: char full[8192];
94추가: snprintf(full, sizeof(full), "%s/", path);
95추가: if (reject(location(full), flags)) return -1;
96추가: int result = original_open64(path, flags, mode);
97추가: if (result >= 0 && snapshot_fd < 0 && location(full) >= 0
98추가: && ((flags & O_TMPFILE) == O_TMPFILE || (flags & O_CREAT))) {
99추가: snapshot_fd = result;
100추가: }
101추가: return result;
102추가: }
103추가: ssize_t write(int fd, const void *bytes, size_t count) {
104추가: char path[4096];
105추가: int at = descriptor(fd, path, sizeof(path));
106추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
107추가: int stage = phase && !strcmp(phase, "stage-write") && fd != snapshot_fd;
108추가: if (affected(at) && phase && (stage || !strcmp(phase, "write")
109추가: || !strcmp(phase, "changed") || !strcmp(phase, "io"))) {
110추가: if (!strcmp(phase, "io")) { errno = EIO; return -1; }
111추가: if (!written[at]++) return original_write(fd, bytes, count < 7 ? count : 7);
112추가: if (!strcmp(phase, "changed")) {
113추가: int source = original_openat(AT_FDCWD, getenv("ZIPELO_SPOOL_SOURCE"), O_WRONLY | O_APPEND);
114추가: if (source >= 0) {
115추가: original_write(source, "x", 1);
116추가: close(source);
117추가: }
118추가: }
119추가: errno = EDQUOT;
120추가: return -1;
121추가: }
122추가: return original_write(fd, bytes, count);
123추가: }
124추가: int fstatvfs(int fd, struct statvfs *value) {
125추가: int (*original)(int, struct statvfs *) = dlsym(RTLD_NEXT, "fstatvfs");
126추가: int result = original(fd, value);
127추가: char path[4096];
128추가: int at = descriptor(fd, path, sizeof(path));
129추가: const char *phase = getenv("ZIPELO_SPOOL_PHASE");
130추가: int stage = phase && !strcmp(phase, "stage-space") && fd != snapshot_fd;
131추가: if (!result && affected(at) && phase && (stage || !strcmp(phase, "space"))) {
132추가: value->f_frsize = 1;
133추가: value->f_bavail = stage ? 0 : 1024;
134추가: }
135추가: return result;
136추가: }