Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/tests/lens_shot.rs

8.2 KiB, 1 run

created by r1870400018:69927, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! `fe2o3_net::lens::Shots`, the picture store behind Daimond's Lens screenshot (D-20261006-14).
2
3use oxedyne_fe2o3_core::prelude::*;
4use oxedyne_fe2o3_net::lens::{
5 stamp,
6 Answer,
7 Ask,
8 Filed,
9 ShotGates,
10 ShotRefusal,
11 Shots,
12};
13
14use std::{
15 fs,
16 path::PathBuf,
17 sync::atomic::{
18 AtomicU64,
19 Ordering,
20 },
21 time::{
22 SystemTime,
23 UNIX_EPOCH,
24 },
25};
26
27
28static SERIAL: AtomicU64 = AtomicU64::new(0);
29
30struct Scratch(PathBuf);
31
32impl Scratch {
33 fn new(tag: &str) -> Self {
34 let n = SERIAL.fetch_add(1, Ordering::SeqCst);
35 let dir = std::env::temp_dir().join(fmt!("lens-shot-{}-{}-{}", std::process::id(), tag, n));
36 let _ = fs::remove_dir_all(&dir);
37 Self(dir)
38 }
39 fn shots(&self) -> Shots { Shots::new(self.0.join("shots"), ShotGates::daimond()) }
40}
41
42impl Drop for Scratch {
43 fn drop(&mut self) {
44 let _ = fs::remove_dir_all(&self.0);
45 }
46}
47
48const PNG: &[u8] = b"\x89PNG\r\n\x1a\nrest-of-a-picture";
49
50// The wall clock, since the hand-out and ask files are aged by modification time.
51fn now() -> u64 {
52 match SystemTime::now().duration_since(UNIX_EPOCH) {
53 Ok(d) => d.as_millis() as u64,
54 Err(_) => 0,
55 }
56}
57
58fn names(dir: &std::path::Path) -> Vec<String> {
59 let mut v: Vec<String> = match fs::read_dir(dir) {
60 Ok(rd) => rd.filter_map(|e| e.ok())
61 .filter(|e| e.path().is_file())
62 .map(|e| e.file_name().to_string_lossy().to_string())
63 .collect(),
64 Err(_) => Vec::new(),
65 };
66 v.sort();
67 v
68}
69
70#[test]
71fn nothing_is_wanted_until_asked() -> Outcome<()> {
72 let s = Scratch::new("none");
73 let shots = s.shots();
74 assert_eq!(res!(shots.take("acct", "dev1", now())), Ask::Nothing);
75 Ok(())
76}
77
78#[test]
79fn an_ask_is_handed_out_once_and_answered_with_a_picture() -> Outcome<()> {
80 let s = Scratch::new("pic");
81 let shots = s.shots();
82 let t = now();
83 res!(shots.ask("dev1", "r1"));
84 assert_eq!(res!(shots.take("acct", "dev1", t)), Ask::Take("r1".to_string()));
85 assert_eq!(res!(shots.take("acct", "dev1", t)), Ask::Nothing, "an ask is collected once");
86 let filed = res!(shots.answer("acct", "dev1", "r1", Answer::Picture(PNG), t + 1_000));
87 let want = shots.dir().join(fmt!("{}.acct.dev1.r1.png", stamp(t + 1_000)));
88 assert_eq!(filed, Filed::Stored(want.clone()));
89 assert_eq!(res!(fs::read(&want)), PNG.to_vec());
90 assert_eq!(res!(shots.find("dev1", "r1")), Some(want));
91 // Consumed: the same answer again is unasked.
92 assert_eq!(
93 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(PNG), t + 2_000)),
94 Filed::Refused(ShotRefusal::Unasked),
95 );
96 assert!(names(shots.dir()).iter().all(|n| !n.ends_with(".part")), "no part file is left");
97 Ok(())
98}
99
100#[test]
101fn an_answer_nobody_asked_for_is_refused() -> Outcome<()> {
102 let s = Scratch::new("unasked");
103 let shots = s.shots();
104 let t = now();
105 assert_eq!(
106 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(PNG), t)),
107 Filed::Refused(ShotRefusal::Unasked),
108 );
109 res!(shots.ask("dev1", "r1"));
110 res!(shots.take("acct", "dev1", t));
111 // Another account, another id and a late answer are each unasked.
112 for (acct, id, at) in [("other", "r1", t), ("acct", "r2", t), ("acct", "r1", t + 120_001)] {
113 assert_eq!(
114 res!(shots.answer(acct, "dev1", id, Answer::Picture(PNG), at)),
115 Filed::Refused(ShotRefusal::Unasked),
116 );
117 }
118 assert_eq!(ShotRefusal::Unasked.status(), 409);
119 assert!(names(shots.dir()).is_empty(), "nothing was filed");
120 Ok(())
121}
122
123#[test]
124fn a_picture_must_be_a_png_within_the_cap() -> Outcome<()> {
125 let s = Scratch::new("cap");
126 let shots = Shots::new(s.0.join("shots"), ShotGates { max_bytes: 64, ..ShotGates::daimond() });
127 let t = now();
128 res!(shots.ask("dev1", "r1"));
129 res!(shots.take("acct", "dev1", t));
130 assert_eq!(
131 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(b"GIF89a....."), t)),
132 Filed::Refused(ShotRefusal::NotPicture),
133 );
134 let mut big = PNG.to_vec();
135 big.resize(65, 0);
136 assert_eq!(
137 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(&big), t)),
138 Filed::Refused(ShotRefusal::TooLarge),
139 );
140 assert_eq!(ShotRefusal::TooLarge.status(), 413);
141 // A refused body does not consume the ask.
142 assert!(matches!(
143 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(PNG), t)),
144 Filed::Stored(_),
145 ));
146 Ok(())
147}
148
149#[test]
150fn a_device_may_refuse_and_say_why() -> Outcome<()> {
151 let s = Scratch::new("refuse");
152 let shots = s.shots();
153 let t = now();
154 res!(shots.ask("dev1", "r1"));
155 res!(shots.take("acct", "dev1", t));
156 let filed = res!(shots.answer("acct", "dev1", "r1", Answer::Refused("off\non this device"), t));
157 let path = match filed {
158 Filed::Stored(p) => p,
159 other => return Err(err!("Expected a stored refusal, got {:?}.", other; Test)),
160 };
161 assert!(path.to_string_lossy().ends_with(".acct.dev1.r1.refused"));
162 assert_eq!(res!(fs::read_to_string(&path)), "off on this device", "a line break cannot forge a line");
163 Ok(())
164}
165
166#[test]
167fn a_second_ask_inside_a_minute_is_refused_for_the_device() -> Outcome<()> {
168 let s = Scratch::new("rate");
169 let shots = s.shots();
170 let t = now();
171 res!(shots.ask("dev1", "r1"));
172 res!(shots.take("acct", "dev1", t));
173 res!(shots.answer("acct", "dev1", "r1", Answer::Picture(PNG), t + 1_000));
174 res!(shots.ask("dev1", "r2"));
175 match res!(shots.take("acct", "dev1", t + 30_000)) {
176 Ask::TooSoon(id, wait) => {
177 assert_eq!(id, "r2");
178 assert_eq!(wait, 30_000);
179 }
180 other => return Err(err!("Expected TooSoon, got {:?}.", other; Test)),
181 }
182 let refused = match res!(shots.find("dev1", "r2")) {
183 Some(p) => p,
184 None => return Err(err!("The rate refusal was not filed."; Test)),
185 };
186 assert!(res!(fs::read_to_string(&refused)).starts_with("rate:"));
187 // The refused ask was collected, so the device is not asked again; after the floor it is.
188 assert_eq!(res!(shots.take("acct", "dev1", t + 30_001)), Ask::Nothing);
189 res!(shots.ask("dev1", "r3"));
190 assert_eq!(res!(shots.take("acct", "dev1", t + 60_000)), Ask::Take("r3".to_string()));
191 Ok(())
192}
193
194#[test]
195fn pictures_older_than_seven_days_are_pruned() -> Outcome<()> {
196 let s = Scratch::new("prune");
197 let shots = s.shots();
198 let t = now();
199 let day = 86_400_000;
200 res!(fs::create_dir_all(shots.dir()));
201 let old = shots.dir().join(fmt!("{}.acct.dev1.r0.png", stamp(t - 8 * day)));
202 let young = shots.dir().join(fmt!("{}.acct.dev1.r1.png", stamp(t - 6 * day)));
203 let stranger = shots.dir().join("README.txt");
204 for p in [&old, &young, &stranger] {
205 res!(fs::write(p, PNG));
206 }
207 assert_eq!(res!(shots.prune(t)), 1);
208 assert!(!old.exists(), "eight days old goes");
209 assert!(young.exists(), "six days old stays");
210 assert!(stranger.exists(), "a file not named by the store is left alone");
211 Ok(())
212}
213
214#[test]
215fn the_oldest_pictures_go_when_the_total_is_exceeded() -> Outcome<()> {
216 let s = Scratch::new("total");
217 let gates = ShotGates { max_total: 2 * PNG.len() as u64, ..ShotGates::daimond() };
218 let shots = Shots::new(s.0.join("shots"), gates);
219 let t = now();
220 res!(fs::create_dir_all(shots.dir()));
221 for i in 0..3u64 {
222 res!(fs::write(shots.dir().join(fmt!("{}.a.d.r{}.png", stamp(t - (3 - i) * 1_000), i)), PNG));
223 }
224 assert_eq!(res!(shots.prune(t)), 1);
225 let left = names(shots.dir());
226 assert_eq!(left.len(), 2);
227 assert!(left.iter().all(|n| !n.ends_with(".r0.png")), "the oldest went: {:?}", left);
228 Ok(())
229}
230
231#[test]
232fn segments_cannot_walk_out_of_the_directory() -> Outcome<()> {
233 let s = Scratch::new("walk");
234 let shots = s.shots();
235 let t = now();
236 res!(shots.ask("../../etc", "../r1"));
237 assert_eq!(res!(shots.take("a/../b", "../../etc", t)), Ask::Take("___r1".to_string()));
238 let filed = res!(shots.answer("a/../b", "../../etc", "../r1", Answer::Picture(PNG), t));
239 match filed {
240 Filed::Stored(p) => assert_eq!(p.parent(), Some(shots.dir())),
241 other => return Err(err!("Expected stored, got {:?}.", other; Test)),
242 }
243 Ok(())
244}