team-ljyzipelo

공개
308줄11 KB
1use super::*;
2use std::collections::VecDeque;
3struct FirstLimit {
4 first: bool,
5 process: ProcessFactory,
6}
7struct Failed {
8 job: u64,
9 events: VecDeque<HostEvent>,
10}
11impl Connection for Failed {
12 fn send(&mut self, request: Request) -> Result<(), String> {
13 assert!(matches!(request.command, Command::Start(_)));
14 self.events.extend([
15 HostEvent::Frame {
16 job_id: self.job,
17 sequence: 0,
18 event: Event::Accepted { encryption: true },
19 },
20 HostEvent::Frame {
21 job_id: self.job,
22 sequence: 1,
23 event: Event::Terminal(Terminal {
24 outcome: Outcome::Failed,
25 error: Some(ErrorCode::Limit),
26 publication: Publication::None,
27 created_count: 0,
28 retained_partial_count: 0,
29 durability: Durability::NotApplicable,
30 cleanup: Cleanup::Complete,
31 }),
32 },
33 HostEvent::StdoutEof,
34 HostEvent::StderrEof,
35 HostEvent::Exited { success: true },
36 ]);
37 Ok(())
38 }
39 fn poll(&mut self) -> Option<HostEvent> {
40 self.events.pop_front()
41 }
42}
43impl Factory for FirstLimit {
44 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
45 if self.first {
46 self.first = false;
47 Ok(Box::new(Failed {
48 job,
49 events: VecDeque::new(),
50 }))
51 } else {
52 self.process.connect(job)
53 }
54 }
55}
56#[test]
57fn model_retry_uses_real_guarded_codec_and_requires_a_new_job_approval() {
58 for mode in 0..3 {
59 let scratch = Scratch::new();
60 let archive = scratch.path("sample.zip");
61 fs::write(&archive, include_bytes!("fixtures/sample.zip")).unwrap();
62 let mut factory = FirstLimit {
63 first: true,
64 process: ProcessFactory::new(binary("zipelo-archive-worker")),
65 };
66 let mut model = Model::default();
67 assert!(model.begin(Start::List { archive }, &mut factory));
68 let first_job = model.job_id().unwrap();
69 wait(&mut model);
70 assert!(model.can_retry_expanded());
71 assert!(model.retry_expanded(&mut factory));
72 let job = model.job_id().unwrap();
73 assert_ne!(first_job, job);
74 let deadline = Instant::now() + Duration::from_secs(10);
75 while model.resource.is_none() {
76 model.poll();
77 assert!(model.error.is_none(), "{:?}", model.error);
78 assert!(Instant::now() < deadline);
79 std::thread::sleep(Duration::from_millis(1));
80 }
81 let q = model.resource.clone().unwrap();
82 assert_eq!(
83 q.scope,
84 ResourceScope {
85 output: true,
86 entries: true,
87 ratio: false
88 }
89 );
90 assert_eq!(q.usage.actual_bytes, None);
91 assert!(q.usage.available_bytes.is_some());
92 assert!(model.entries.is_empty());
93 assert!(!model.resource_reply(first_job, q.id, true));
94 if mode == 2 {
95 model.cancel();
96 } else {
97 assert!(model.resource_reply(job, q.id, mode == 0));
98 }
99 wait(&mut model);
100 assert!(model.confirmed, "{:?}", model.error);
101 assert_eq!(
102 model.terminal.as_ref().unwrap().outcome,
103 if mode == 0 {
104 Outcome::Completed
105 } else {
106 Outcome::Cancelled
107 }
108 );
109 assert_eq!(model.list_id.is_some(), mode == 0);
110 assert!(model.resource.is_none());
111 }
112}
113
114#[test]
115fn approved_extraction_reports_implicit_parents_separately_from_entries() {
116 let scratch = Scratch::new();
117 let archive = scratch.path("implicit.zip");
118 let generated = std::process::Command::new("python3")
119 .arg("-c")
120 .arg("import sys, zipfile; z = zipfile.ZipFile(sys.argv[1], 'w'); [z.writestr(p, b'') for p in ['a/b/one', 'a/b/two', 'c/d/three']]; z.close()")
121 .arg(&archive)
122 .output()
123 .unwrap();
124 assert!(generated.status.success());
125 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
126 let mut model = Model::default();
127 assert!(model.begin(Start::List { archive }, &mut factory));
128 wait(&mut model);
129 assert!(model.confirmed, "{:?}", model.error);
130 assert_eq!(model.entries.len(), 3);
131 model.entries[0].bytes = Some(Limits::default().output + 1);
132 let destination = make_directory(&scratch.path("output"));
133 assert!(model.extract(destination.clone(), false, None, &mut factory));
134 let deadline = Instant::now() + Duration::from_secs(10);
135 while model.resource.is_none() {
136 model.poll();
137 assert!(model.error.is_none(), "{:?}", model.error);
138 assert!(Instant::now() < deadline);
139 std::thread::sleep(Duration::from_millis(1));
140 }
141 let question = model.resource.clone().unwrap();
142 assert!(question.scope.output && question.scope.entries);
143 assert!(model.outputs.is_empty());
144 assert!(model.resource_reply(model.job_id().unwrap(), question.id, true));
145 wait(&mut model);
146 assert!(model.confirmed, "{:?}", model.error);
147 assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
148 assert_eq!(model.terminal.as_ref().unwrap().created_count, 7);
149 assert_eq!(model.outputs.len(), 7);
150 for name in ["a", "a/b", "c", "c/d"] {
151 assert!(destination.join(name).is_dir());
152 assert!(
153 model
154 .outputs
155 .iter()
156 .any(|(p, d)| p == name && *d == Disposition::Created)
157 );
158 }
159 for name in ["a/b/one", "a/b/two", "c/d/three"] {
160 assert_eq!(fs::read(destination.join(name)).unwrap(), b"");
161 assert!(
162 model
163 .outputs
164 .iter()
165 .any(|(p, d)| p == name && *d == Disposition::Created)
166 );
167 }
168}
169
170#[cfg(target_os = "linux")]
171#[test]
172fn approved_password_wait_is_not_killed_by_app_deadline() {
173 const MODE: &str = "ZIPELO_SUPERVISOR_CLOCK_CASE";
174 if let Ok(mode) = std::env::var(MODE) {
175 let approved = mode != "unapproved";
176 let scratch = Scratch::new();
177 let output = scratch.path("output.zip");
178 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
179 let mut connection = factory.connect(1).unwrap();
180 let start = Start::CreateZip {
181 sources: vec![(scratch.path("source.txt"), "source.txt".into())],
182 output_file: output.clone(),
183 method: Method::Store,
184 aes256: true,
185 };
186 fs::write(scratch.path("source.txt"), b"source").unwrap();
187 connection
188 .send(Request {
189 job_id: 1,
190 sequence: 0,
191 command: if approved {
192 Command::StartExpanded(start)
193 } else {
194 Command::Start(start)
195 },
196 })
197 .unwrap();
198 let started = Instant::now();
199 let mut sequence = 1;
200 let mut granted = false;
201 let mut password = false;
202 let mut cancelled = false;
203 let mut terminal = None;
204 let mut fault = None;
205 loop {
206 if let Some(event) = connection.poll() {
207 match event {
208 HostEvent::Frame {
209 event: Event::ResourceRequired(q),
210 ..
211 } => {
212 assert!(approved);
213 connection
214 .send(Request {
215 job_id: 1,
216 sequence,
217 command: Command::ResourceReply {
218 challenge_id: q.id,
219 scope: q.scope,
220 allow: true,
221 },
222 })
223 .unwrap();
224 sequence += 1;
225 granted = true;
226 }
227 HostEvent::Frame {
228 event: Event::PasswordRequired { .. },
229 ..
230 } => password = true,
231 HostEvent::Frame {
232 event: Event::Terminal(value),
233 ..
234 } => terminal = Some(value),
235 HostEvent::Fault(message) => fault = Some(message),
236 HostEvent::Exited { success } => {
237 assert!(password);
238 assert_eq!(granted, approved);
239 assert!(!output.exists());
240 if approved {
241 assert!(success);
242 assert!(
243 fault.is_none(),
244 "승인 뒤 암호 대기를 강제 종료함: {fault:?}"
245 );
246 assert_eq!(terminal.unwrap().outcome, Outcome::Cancelled);
247 } else {
248 assert!(!success);
249 assert!(fault.unwrap().contains("제한 시간"));
250 }
251 return;
252 }
253 _ => {}
254 }
255 }
256 if approved && started.elapsed() > Duration::from_secs(4) && !cancelled {
257 connection
258 .send(Request {
259 job_id: 1,
260 sequence,
261 command: Command::Cancel,
262 })
263 .unwrap();
264 cancelled = true;
265 }
266 assert!(started.elapsed() < Duration::from_secs(8));
267 std::thread::sleep(Duration::from_millis(1));
268 }
269 }
270 let scratch = Scratch::new();
271 let clock = scratch.path("supervisor-clock.so");
272 assert!(
273 std::process::Command::new("cc")
274 .args(["-shared", "-fPIC", "-pthread"])
275 .arg(
276 Path::new(env!("CARGO_MANIFEST_DIR"))
277 .join("../../tests/rust-app-real-worker/supervisor_clock.c")
278 )
279 .args(["-o"])
280 .arg(&clock)
281 .arg("-ldl")
282 .status()
283 .unwrap()
284 .success()
285 );
286 for mode in ["control", "approved", "unapproved"] {
287 let mut command = std::process::Command::new(std::env::current_exe().unwrap());
288 command
289 .args([
290 "--exact",
291 "guarded_flows::approved_password_wait_is_not_killed_by_app_deadline",
292 "--nocapture",
293 ])
294 .env(MODE, mode);
295 if mode == "control" {
296 command.env_remove("LD_PRELOAD");
297 } else {
298 command.env("LD_PRELOAD", &clock);
299 }
300 let output = command.output().unwrap();
301 assert!(
302 output.status.success(),
303 "{mode}: {}\n{}",
304 String::from_utf8_lossy(&output.stdout),
305 String::from_utf8_lossy(&output.stderr)
306 );
307 }
308}