@[has_globals] module main import blip.vlib.blip.machine import net import sync import time // mirrors_machine is a blip machine set up the way load_config sets one up, // for what a mirrors file needs fn mirrors_machine() &machine.Machine { mut m := machine.new_standalone(&QuietConfigHost{}) m.prims['array-append!'] = prim_array_append return m } fn mirrors_read(mut m machine.Machine, var string) ![]string { return m.run_str(var)!.as_vector().data.map(it.as_string()) } fn test_mirrors_lip_round_trip() ! { urls := [ 'https://ok.example/' + r'$repo/os/$arch', 'https://quote.example/a"b', 'https://backslash.example/a\\b', 'https://newline.example/a\nb', 'https://tab.example/a\tb', // closes its string and the form, then defines something 'https://x.example/"]) (define pwned 1) (array-append! mirrors-arch ["', ] text := mirrors_lip('arch', urls, '2026-11-08') assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n') mut m := mirrors_machine() m.run_str(text)! assert mirrors_read(mut m, 'mirrors-arch')! == urls if _ := m.run_str('pwned') { assert false, 'a url ran as code' } } fn test_mirrors_lip_appends() ! { // the file adds to a list the config may have started already mut m := mirrors_machine() m.run_str('(define mirrors-arch ["https://first.example/"])')! m.run_str(mirrors_lip('arch', ['https://second.example/'], 'today'))! assert mirrors_read(mut m, 'mirrors-arch')! == ['https://first.example/', 'https://second.example/'] } fn test_mirrors_lip_empty() ! { mut m := mirrors_machine() m.run_str(mirrors_lip('artix', [], 'today'))! assert mirrors_read(mut m, 'mirrors-artix')!.len == 0 } // ProbeTally is what a fake probe records across the batch's threads: how // many ran at once, at the most, and which mirrors it was handed @[heap] struct ProbeTally { mut: mu &sync.Mutex = sync.new_mutex() in_flight int peak int seen []string // stalled is set by the first probe that gave up waiting for company, // so a serial batch fails the test in one wait rather than one per mirror stalled bool } fn (mut t ProbeTally) enter(url string) { t.mu.lock() t.in_flight++ if t.in_flight > t.peak { t.peak = t.in_flight } t.seen << url t.mu.unlock() } fn (mut t ProbeTally) leave() { t.mu.lock() t.in_flight-- t.mu.unlock() } // wait_for_peak holds a probe until n probes have been in flight at once, or // a second has passed: probes that run one after another never get there fn (mut t ProbeTally) wait_for_peak(n int) { deadline := time.now().add(time.second) for { t.mu.lock() done := t.peak >= n || t.stalled t.mu.unlock() if done { return } if time.now() > deadline { t.mu.lock() t.stalled = true t.mu.unlock() return } time.sleep(time.millisecond) } } fn probe_mirrors(n int) []Mirror { return []Mirror{len: n, init: Mirror{ url: 'https://m${index}.example/' }} } // probe_batch_with runs a quiet batch with the rank parallelism set to conc, // the globals it reads put back after fn probe_batch_with(conc int, mirrors []Mirror, probe ProbeFn) []Probe { saved_rank, saved_net := rank_parallel, parallel_downloads defer { rank_parallel, parallel_downloads = saved_rank, saved_net } rank_parallel, parallel_downloads = conc, conc mut ui := new_trans_ui() return probe_batch(mut ui, 'test', mirrors, probe, true) } fn test_probe_batch_answers_once_per_mirror() { mirrors := probe_mirrors(13) mut tally := &ProbeTally{} // every other mirror fails: a failed probe is still its mirror's answer out := probe_batch_with(4, mirrors, fn [mut tally] (m Mirror) Probe { tally.enter(m.url) tally.leave() return Probe{ url: m.url ok: m.url.all_after('//m').all_before('.').int() % 2 == 0 } }) assert out.len == mirrors.len mut got := out.map(it.url) got.sort() mut want := mirrors.map(it.url) want.sort() assert got == want assert out.filter(it.ok).len == 7 tally.seen.sort() assert tally.seen == want } fn test_probe_batch_probes_run_in_parallel() { // the probes must overlap, conc of them at once and never more: a probe // evaluated by the collector before its spawn runs the batch serially mirrors := probe_mirrors(9) mut tally := &ProbeTally{} out := probe_batch_with(3, mirrors, fn [mut tally] (m Mirror) Probe { tally.enter(m.url) tally.wait_for_peak(3) tally.leave() return Probe{ url: m.url ok: true } }) assert out.len == 9 assert !tally.stalled, 'the probes ran one at a time' assert tally.peak == 3 } fn test_probe_batch_zero_parallelism_still_probes() { // a parallelism of 0 slipped past the config's floor starts one worker, // not none (which would leave the collector waiting forever) mirrors := probe_mirrors(5) mut tally := &ProbeTally{} out := probe_batch_with(0, mirrors, fn [mut tally] (m Mirror) Probe { tally.enter(m.url) tally.leave() return Probe{ url: m.url ok: true } }) assert out.len == 5 assert tally.peak == 1 } fn test_probe_batch_more_workers_than_mirrors() { mirrors := probe_mirrors(2) out := probe_batch_with(16, mirrors, fn (m Mirror) Probe { return Probe{ url: m.url ok: true } }) assert out.len == 2 } fn test_probe_batch_empty() { out := probe_batch_with(4, []Mirror{}, fn (m Mirror) Probe { assert false, 'no mirror to probe' return Probe{} }) assert out.len == 0 } // TrickleServer is one trickle url's listener and the body shape it serves, // handed to its serving thread by channel struct TrickleServer { listener &net.TcpListener total int pause time.Duration } // the trickle server's spec crosses to its serving thread by channel as a // value, and the thread spawns with no arguments, like the fetcher's jobs in // mirrors.v: the arguments of a spawned call have been seen carrying another // probe's values, and an answer that takes another probe's totals holds that // probe's fetch past its deadline __global server_specs = chan TrickleServer{cap: 16} // trickle_mirror_worker answers every connection on the listener with a body // of total bytes, sent one byte each pause: each read lands well inside the // socket timeout while the whole answer takes total pauses. connections are // served one at a time — a probe makes one connection, and a client that // hangs up ends its connection's answer at the next write, so the next // probe's connection is accepted soon after. the loop ends when the listener // closes fn trickle_mirror_worker() { spec := <-server_specs or { return } mut l := spec.listener for { mut conn := l.accept() or { return } trickle_answer(mut conn, spec.total, spec.pause) } } fn trickle_answer(mut conn net.TcpConn, total int, pause time.Duration) { defer { conn.close() or {} } mut request := []u8{len: 4096} conn.read(mut request) or { return } conn.write_string('HTTP/1.1 200 OK\r\nContent-Length: ${total}\r\nConnection: close\r\n\r\n') or { return } for _ in 0 .. total { conn.write_string('x') or { return } time.sleep(pause) } } // trickle_url starts a trickling mirror on a port of its own and answers its // url with the listener, which the test closes fn trickle_url(total int, pause time.Duration) !(&net.TcpListener, string) { mut l := net.listen_tcp(.ip, '127.0.0.1:0')! port := l.addr()!.port()! server_specs <- TrickleServer{ listener: l total: total pause: pause } spawn trickle_mirror_worker() return l, 'http://127.0.0.1:${port}/core.db' } // a mirror that keeps every read short of the socket timeout but the whole // answer past the rank timeout fails the probe, close to the timeout and not // at the answer's end (some six seconds here) fn test_timed_get_bounds_the_whole_answer() ! { saved := rank_timeout defer { rank_timeout = saved } rank_timeout = 1 mut l, url := trickle_url(30, 200 * time.millisecond)! defer { l.close() or {} } for range in [false, true] { start := time.now() if _, bytes := timed_get(url, range) { assert false, 'a trickled answer of ${bytes} bytes passed the timeout (range ${range})' } took := time.now() - start assert took < 3 * time.second, 'the probe took ${took} (range ${range})' } } // a mirror that answers a byte, then falls silent past the deadline gives the // probe neither a progress callback to check the clock with nor a socket // timeout to end the wait — each byte lands just inside it. the deadline must // be held by the wait on the answer itself, so the probe ends at the deadline // and not when the next chunk finally arrives (some 1.8s here) fn test_timed_get_holds_the_deadline_when_no_chunk_arrives() ! { saved := rank_timeout defer { rank_timeout = saved } rank_timeout = 1 mut l, url := trickle_url(30, 900 * time.millisecond)! defer { l.close() or {} } for range in [false, true] { start := time.now() if _, bytes := timed_get(url, range) { assert false, 'a silent mirror passed the timeout with ${bytes} bytes (range ${range})' } took := time.now() - start assert took < 1500 * time.millisecond, 'the probe took ${took} (range ${range})' } } // an answer that is whole within the timeout is measured as before fn test_timed_get_measures_a_prompt_answer() ! { saved := rank_timeout defer { rank_timeout = saved } rank_timeout = 5 mut l, url := trickle_url(4, time.millisecond)! defer { l.close() or {} } _, bytes := timed_get(url, false)! assert bytes == 4 } fn test_rank_os_names_are_sorted() { // the message spells the oses the same way whatever order the config's // mirrorlist forms defined them in; one os and none are spelled too saved := rank_oses.clone() defer { rank_oses = saved.clone() } rank_oses = map[string]RankOs{} assert rank_os_names() == '' rank_oses['zeta'] = RankOs{} assert rank_os_names() == 'zeta' rank_oses['arch'] = RankOs{} rank_oses['Mid'] = RankOs{} rank_oses['artix'] = RankOs{} assert rank_os_names() == 'Mid, arch, artix, zeta' } fn test_timed_probe_edges() { // latency alone: the bytes are not looked at lat := timed_probe('u', 12, 0, false) assert lat.ok && lat.latency_ms == 12 && lat.speed == 0.0 && lat.url == 'u' // a zero latency is still a mirror that answered assert timed_probe('u', 0, 0, false).ok // speed: bytes over seconds sp := timed_probe('u', 500, 1000, true) assert sp.ok && sp.speed == 2000.0 && sp.latency_ms == 500 // a fetch that brought nothing failed, whatever it took assert !timed_probe('u', 500, 0, true).ok assert !timed_probe('u', 0, 0, true).ok // quicker than a millisecond, or a clock that went back, is one // millisecond: a speed, not a division by zero assert timed_probe('u', 0, 10, true).speed == 10000.0 assert timed_probe('u', -5, 10, true).speed == 10000.0 } fn test_http_text_names_the_refusal() ! { // nothing listens here: the fetch fails as the fetch it was called if body := http_text('http://127.0.0.1:1/x', 1, 'fetching the test', 'the test server') { assert false, 'port 1 answered: ${body}' } else { assert err.msg().starts_with('fetching the test failed: '), err.msg() } }