vpac / src / mirrors_test.v
387 lines · 358 sloc · 11.58 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1@[has_globals]
2module main
3
4import vile.scheme
5import net
6import os
7import sync
8import time
9
10// mirrors_machine is a scheme machine set up the way load_config sets one up,
11// for what a mirrors file needs
12fn mirrors_machine() !&scheme.VM {
13 mut m := scheme.new_with_options(max_steps: 100_000_000)!
14 m.register('defined?', prim_defined)!
15 return m
16}
17
18fn mirrors_read(mut m scheme.VM, var string) ![]string {
19 items := m.lookup(var)!.list_items()!
20 mut urls := []string{}
21 for item in items { urls << item.as_string()! }
22 return urls
23}
24
25fn test_ranked_mirror_files_round_trip() ! {
26 urls := [
27 'https://ok.example/' + r'$repo/os/$arch',
28 'https://quote.example/a"b',
29 'https://backslash.example/a\\b',
30 'https://newline.example/a\nb',
31 'https://tab.example/a\tb',
32 // closes its string and the form, then defines something
33 'https://x.example/")) (define pwned 1) (append mirrors-arch (list "',
34 ]
35 for native in [false, true] {
36 text := ranked_mirrors('arch', urls, '2026-11-08', native)!
37 assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n')
38 mut m := mirrors_machine()!
39 if native { m.eval_alt(text)! } else { m.eval(text)! }
40 assert mirrors_read(mut m, 'mirrors-arch')! == urls
41 if _ := m.eval('pwned') {
42 assert false, 'a url ran as code'
43 }
44 }
45}
46
47fn test_mirrors_scm_appends() ! {
48 // the file adds to a list the config may have started already
49 mut m := mirrors_machine()!
50 m.eval('(define mirrors-arch #("https://first.example/"))')!
51 m.eval(ranked_mirrors('arch', ['https://second.example/'], 'today', false)!)!
52 assert mirrors_read(mut m, 'mirrors-arch')! == ['https://first.example/', 'https://second.example/']
53}
54
55fn test_mirrors_scm_empty() ! {
56 mut m := mirrors_machine()!
57 m.eval(ranked_mirrors('artix', [], 'today', false)!)!
58 assert mirrors_read(mut m, 'mirrors-artix')!.len == 0
59}
60
61fn test_ranked_mirrors_load_from_config() ! {
62 dir := os.join_path(os.vtmp_dir(), 'vpac_ranked_config_${os.getpid()}')
63 os.mkdir_all(dir)!
64 defer {
65 reset_config()
66 os.rmdir_all(dir) or { went_on('remove the test config', err) }
67 }
68 urls := ['https://one.example/\$repo/os/\$arch', 'https://two.example/\$repo/os/\$arch']
69 os.write_file(os.join_path(dir, 'mirrors.scm'), ranked_mirrors('artix', urls, 'today', false)!)!
70 path := os.join_path(dir, 'config.scm')
71 os.write_file(path, '(load "mirrors.scm")\n(repo #:name "system" #:src mirrors-artix)')!
72 load_config(path, [])!
73 assert cfg_repos.len == 1
74 assert cfg_repos[0].servers == urls
75}
76
77// ProbeTally is what a fake probe records across the batch's threads: how
78// many ran at once, at the most, and which mirrors it was handed
79@[heap]
80struct ProbeTally {
81mut:
82 mu &sync.Mutex = sync.new_mutex()
83 in_flight int
84 peak int
85 seen []string
86 // stalled is set by the first probe that gave up waiting for company,
87 // so a serial batch fails the test in one wait rather than one per mirror
88 stalled bool
89}
90
91fn (mut t ProbeTally) enter(url string) {
92 t.mu.lock()
93 t.in_flight++
94 if t.in_flight > t.peak {
95 t.peak = t.in_flight
96 }
97 t.seen << url
98 t.mu.unlock()
99}
100
101fn (mut t ProbeTally) leave() {
102 t.mu.lock()
103 t.in_flight--
104 t.mu.unlock()
105}
106
107// wait_for_peak holds a probe until n probes have been in flight at once, or
108// a second has passed: probes that run one after another never get there
109fn (mut t ProbeTally) wait_for_peak(n int) {
110 deadline := time.now().add(time.second)
111 for {
112 t.mu.lock()
113 done := t.peak >= n || t.stalled
114 t.mu.unlock()
115 if done {
116 return
117 }
118 if time.now() > deadline {
119 t.mu.lock()
120 t.stalled = true
121 t.mu.unlock()
122 return
123 }
124 time.sleep(time.millisecond)
125 }
126}
127
128fn probe_mirrors(n int) []Mirror {
129 return []Mirror{len: n, init: Mirror{
130 url: 'https://m${index}.example/'
131 }}
132}
133
134// probe_batch_with runs a quiet batch with the rank parallelism set to conc,
135// the globals it reads put back after
136fn probe_batch_with(conc int, mirrors []Mirror, probe ProbeFn) []Probe {
137 saved_rank, saved_net := rank_parallel, parallel_downloads
138 defer {
139 rank_parallel, parallel_downloads = saved_rank, saved_net
140 }
141 rank_parallel, parallel_downloads = conc, conc
142 mut ui := new_trans_ui()
143 return probe_batch(mut ui, 'test', mirrors, probe, true)
144}
145
146fn test_probe_batch_answers_once_per_mirror() {
147 mirrors := probe_mirrors(13)
148 mut tally := &ProbeTally{}
149 // every other mirror fails: a failed probe is still its mirror's answer
150 out := probe_batch_with(4, mirrors, fn [mut tally] (m Mirror) Probe {
151 tally.enter(m.url)
152 tally.leave()
153 return Probe{
154 url: m.url
155 ok: m.url.all_after('//m').all_before('.').int() % 2 == 0
156 }
157 })
158 assert out.len == mirrors.len
159 mut got := out.map(it.url)
160 got.sort()
161 mut want := mirrors.map(it.url)
162 want.sort()
163 assert got == want
164 assert out.filter(it.ok).len == 7
165 tally.seen.sort()
166 assert tally.seen == want
167}
168
169fn test_probe_batch_probes_run_in_parallel() {
170 // the probes must overlap, conc of them at once and never more: a probe
171 // evaluated by the collector before its spawn runs the batch serially
172 mirrors := probe_mirrors(9)
173 mut tally := &ProbeTally{}
174 out := probe_batch_with(3, mirrors, fn [mut tally] (m Mirror) Probe {
175 tally.enter(m.url)
176 tally.wait_for_peak(3)
177 tally.leave()
178 return Probe{
179 url: m.url
180 ok: true
181 }
182 })
183 assert out.len == 9
184 assert !tally.stalled, 'the probes ran one at a time'
185 assert tally.peak == 3
186}
187
188fn test_probe_batch_zero_parallelism_still_probes() {
189 // a parallelism of 0 slipped past the config's floor starts one worker,
190 // not none (which would leave the collector waiting forever)
191 mirrors := probe_mirrors(5)
192 mut tally := &ProbeTally{}
193 out := probe_batch_with(0, mirrors, fn [mut tally] (m Mirror) Probe {
194 tally.enter(m.url)
195 tally.leave()
196 return Probe{
197 url: m.url
198 ok: true
199 }
200 })
201 assert out.len == 5
202 assert tally.peak == 1
203}
204
205fn test_probe_batch_more_workers_than_mirrors() {
206 mirrors := probe_mirrors(2)
207 out := probe_batch_with(16, mirrors, fn (m Mirror) Probe {
208 return Probe{
209 url: m.url
210 ok: true
211 }
212 })
213 assert out.len == 2
214}
215
216fn test_probe_batch_empty() {
217 out := probe_batch_with(4, []Mirror{}, fn (m Mirror) Probe {
218 assert false, 'no mirror to probe'
219 return Probe{}
220 })
221 assert out.len == 0
222}
223
224// TrickleServer is one trickle url's listener and the body shape it serves,
225// handed to its serving thread by channel
226struct TrickleServer {
227 listener &net.TcpListener
228 total int
229 pause time.Duration
230}
231
232// the trickle server's spec crosses to its serving thread by channel as a
233// value, and the thread spawns with no arguments, like the fetcher's jobs in
234// mirrors.v: the arguments of a spawned call have been seen carrying another
235// probe's values, and an answer that takes another probe's totals holds that
236// probe's fetch past its deadline
237__global server_specs = chan TrickleServer{cap: 16}
238
239// trickle_mirror_worker answers every connection on the listener with a body
240// of total bytes, sent one byte each pause: each read lands well inside the
241// socket timeout while the whole answer takes total pauses. connections are
242// served one at a time — a probe makes one connection, and a client that
243// hangs up ends its connection's answer at the next write, so the next
244// probe's connection is accepted soon after. the loop ends when the listener
245// closes
246fn trickle_mirror_worker() {
247 spec := <-server_specs or { return }
248 mut l := spec.listener
249 for {
250 mut conn := l.accept() or { return }
251 trickle_answer(mut conn, spec.total, spec.pause)
252 }
253}
254
255fn trickle_answer(mut conn net.TcpConn, total int, pause time.Duration) {
256 defer {
257 conn.close() or {}
258 }
259 mut request := []u8{len: 4096}
260 conn.read(mut request) or { return }
261 conn.write_string('HTTP/1.1 200 OK\r\nContent-Length: ${total}\r\nConnection: close\r\n\r\n') or {
262 return
263 }
264 for _ in 0 .. total {
265 conn.write_string('x') or { return }
266 time.sleep(pause)
267 }
268}
269
270// trickle_url starts a trickling mirror on a port of its own and answers its
271// url with the listener, which the test closes
272fn trickle_url(total int, pause time.Duration) !(&net.TcpListener, string) {
273 mut l := net.listen_tcp(.ip, '127.0.0.1:0')!
274 port := l.addr()!.port()!
275 server_specs <- TrickleServer{
276 listener: l
277 total: total
278 pause: pause
279 }
280 spawn trickle_mirror_worker()
281 return l, 'http://127.0.0.1:${port}/core.db'
282}
283
284// a mirror that keeps every read short of the socket timeout but the whole
285// answer past the rank timeout fails the probe, close to the timeout and not
286// at the answer's end (some six seconds here)
287fn test_timed_get_bounds_the_whole_answer() ! {
288 saved := rank_timeout
289 defer {
290 rank_timeout = saved
291 }
292 rank_timeout = 1
293 mut l, url := trickle_url(30, 200 * time.millisecond)!
294 defer {
295 l.close() or {}
296 }
297 for range in [false, true] {
298 start := time.now()
299 if _, bytes := timed_get(url, range) {
300 assert false, 'a trickled answer of ${bytes} bytes passed the timeout (range ${range})'
301 }
302 took := time.now() - start
303 assert took < 3 * time.second, 'the probe took ${took} (range ${range})'
304 }
305}
306
307// a mirror that answers a byte, then falls silent past the deadline gives the
308// probe neither a progress callback to check the clock with nor a socket
309// timeout to end the wait — each byte lands just inside it. the deadline must
310// be held by the wait on the answer itself, so the probe ends at the deadline
311// and not when the next chunk finally arrives (some 1.8s here)
312fn test_timed_get_holds_the_deadline_when_no_chunk_arrives() ! {
313 saved := rank_timeout
314 defer {
315 rank_timeout = saved
316 }
317 rank_timeout = 1
318 mut l, url := trickle_url(30, 900 * time.millisecond)!
319 defer {
320 l.close() or {}
321 }
322 for range in [false, true] {
323 start := time.now()
324 if _, bytes := timed_get(url, range) {
325 assert false, 'a silent mirror passed the timeout with ${bytes} bytes (range ${range})'
326 }
327 took := time.now() - start
328 assert took < 1500 * time.millisecond, 'the probe took ${took} (range ${range})'
329 }
330}
331
332// an answer that is whole within the timeout is measured as before
333fn test_timed_get_measures_a_prompt_answer() ! {
334 saved := rank_timeout
335 defer {
336 rank_timeout = saved
337 }
338 rank_timeout = 5
339 mut l, url := trickle_url(4, time.millisecond)!
340 defer {
341 l.close() or {}
342 }
343 _, bytes := timed_get(url, false)!
344 assert bytes == 4
345}
346
347fn test_rank_os_names_are_sorted() {
348 // the message spells the oses the same way whatever order the config's
349 // mirrorlist forms defined them in; one os and none are spelled too
350 saved := rank_oses.clone()
351 defer { rank_oses = saved.clone() }
352 rank_oses = map[string]RankOs{}
353 assert rank_os_names() == ''
354 rank_oses['zeta'] = RankOs{}
355 assert rank_os_names() == 'zeta'
356 rank_oses['arch'] = RankOs{}
357 rank_oses['Mid'] = RankOs{}
358 rank_oses['artix'] = RankOs{}
359 assert rank_os_names() == 'Mid, arch, artix, zeta'
360}
361
362fn test_timed_probe_edges() {
363 // latency alone: the bytes are not looked at
364 lat := timed_probe('u', 12, 0, false)
365 assert lat.ok && lat.latency_ms == 12 && lat.speed == 0.0 && lat.url == 'u'
366 // a zero latency is still a mirror that answered
367 assert timed_probe('u', 0, 0, false).ok
368 // speed: bytes over seconds
369 sp := timed_probe('u', 500, 1000, true)
370 assert sp.ok && sp.speed == 2000.0 && sp.latency_ms == 500
371 // a fetch that brought nothing failed, whatever it took
372 assert !timed_probe('u', 500, 0, true).ok
373 assert !timed_probe('u', 0, 0, true).ok
374 // quicker than a millisecond, or a clock that went back, is one
375 // millisecond: a speed, not a division by zero
376 assert timed_probe('u', 0, 10, true).speed == 10000.0
377 assert timed_probe('u', -5, 10, true).speed == 10000.0
378}
379
380fn test_http_text_names_the_refusal() ! {
381 // nothing listens here: the fetch fails as the fetch it was called
382 if body := http_text('http://127.0.0.1:1/x', 1, 'fetching the test', 'the test server') {
383 assert false, 'port 1 answered: ${body}'
384 } else {
385 assert err.msg().starts_with('fetching the test failed: '), err.msg()
386 }
387}
388