@[has_globals] module main import blip.vlib.blip.printer import json2 import net.http import os import time // mirror ranking, after rate-mirrors (westandskif/rate-mirrors): gather the // candidates, drop the unusable ones, time one byte for latency, then time a // repo database for speed, and rank by speed. the oses the ranker knows are // in rank_oses; the protocols to rank come from the config // the rank form's filters and sizes, (rank :completion :max-delay :candidates // :retest :top): how complete and how fresh a mirror must be to be probed, // how many of the lowest latencies get the speed test, how many of the // fastest are timed again, and how many are answered when -n names none __global rank_min_completion = 1.0 __global rank_max_delay = i64(86400) // rank_parallelism is how many mirrors to probe at once: the rank form's // :parallel when it sets one, else the network's :parallel fn rank_parallelism() int { return if rank_parallel > 0 { rank_parallel } else { parallel_downloads } } __global rank_speed_candidates = 40 __global rank_retest = 5 __global rank_top = 10 // RankOs is one os the ranker knows. the mirror data comes from the status // api when the os publishes one, else from a plain Server = mirrorlist, which // carries no completion or delay to filter by. repo is the repo whose db the // speed test pulls, named again in the written urls struct RankOs { status_json string mirrorlist string repo string } // default_rank_oses are the oses the ranker knows before the config speaks fn default_rank_oses() map[string]RankOs { return { 'artix': RankOs{ status_json: 'https://status.artixlinux.org/mirrors/status/json/' repo: 'system' } 'arch': RankOs{ status_json: 'https://archlinux.org/mirrors/status/json/' repo: 'core' } 'cachyos': RankOs{ mirrorlist: 'https://raw.githubusercontent.com/CachyOS/CachyOS-PKGBUILDS/master/cachyos-mirrorlist/cachyos-mirrorlist' repo: 'cachyos' } } } // rank_oses are the oses the ranker knows: the defaults, and every one the // config's (mirrorlist ...) form defines or redefines. rank_dir is where a // ranking is written for the config to require, (rank :dir) __global rank_oses = default_rank_oses() __global rank_dir = '/etc/vpac.d/mirrors' // rank_os_names spells the known oses for a message, sorted: the text is // the same whatever order the config's forms came in fn rank_os_names() string { mut names := rank_oses.keys() names.sort() return names.join(', ') } // rank_os_name picks the os to rank: the one named on the command line, or // the running system's, read from /etc/os-release fn rank_os_name(query []string) !string { if query.len > 1 { return error('rank takes one os: ${rank_os_names()}') } if query.len == 1 { if query[0] !in rank_oses.keys() { return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist :name ...) in the config') } return query[0] } text := os.read_file('/etc/os-release') or { return error('could not read /etc/os-release to detect the os: pass one of ${rank_os_names()}') } mut id := '' mut like := '' for line in text.split_into_lines() { if line.starts_with('ID=') { id = line[3..].trim_space().trim('"\'') } else if line.starts_with('ID_LIKE=') { like = line[8..].trim_space().trim('"\'') } } for candidate in [id, ...like.split(' ')] { if candidate in rank_oses.keys() { return candidate } } return error('this system (${id}) is not one the ranker knows: pass one of ${rank_os_names()}, or define it with (mirrorlist :name ...) in the config') } // rank_write_target is where a ranked os is written for the config to require fn rank_write_target(os_name string) string { return os.join_path(rank_dir, '${os_name}.lip') } struct StatusMirror { url string protocol string last_sync string completion_pct ?f64 delay ?i64 active bool country_code string } struct StatusList { urls []StatusMirror } // Mirror is a candidate: its full url template, with the repo and arch // placeholders left in place the way the config's mirror files hold them, and // when it last synced struct Mirror { url string last_sync string } // probe_url is the concrete url of one mirror's repo db: the template with // the repo and arch substituted in, plus the db file. a path override takes // the mirror root instead, which is where a custom file hangs from fn probe_url(m Mirror, spec RankOs, override string) string { if override != '' { return m.url.all_before('$') + override } return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db' } fn with_slash(url string) string { return if url.ends_with('/') { url } else { url + '/' } } // timed_fetch fetches one url with the rank timeout on both directions, and // hands back the body: it is what the ranker asks of the network, from the // mirror status on to the mirrorlists, since a stalled dns or a captive // portal would otherwise visit its hang on the ranking fn timed_fetch(url string, what string) !string { return http_text(url, rank_timeout, what, url) } // http_text is one GET bounded by a timeout, in seconds, on both // directions, answering the body of an answer that succeeded. what names // the fetch and from the server in the error, so a refusal is told from a // stall. the ranker's fetches and the pkgbuild rpc both go through it fn http_text(url string, seconds int, what string, from string) !string { mut req := http.Request{ url: url read_timeout: seconds * time.second write_timeout: seconds * time.second } resp := req.do() or { return error('${what} failed: ${err}') } if resp.status_code < 200 || resp.status_code >= 300 { return error('${what} failed: http ${resp.status_code} from ${from}') } return resp.body } // fetch_status_mirrors reads an os's mirror status and keeps the mirrors that // are usable: active, on a configured protocol, fully synced, recently synced, // with a known country fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror { body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')! status := json2.decode[StatusList](body) or { return error('could not read the ${os_name} mirror status: ${err.msg()}') } mut out := []Mirror{} for m in status.urls { completion := m.completion_pct or { continue } delay := m.delay or { continue } if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion && delay <= rank_max_delay && m.country_code != '' { // the status api gives the mirror root; the repo layout of the os // completes it to the template the config's mirror files hold out << Mirror{ url: with_slash(m.url) + '$repo/os/$arch' last_sync: m.last_sync } } } return out } // fetch_mirrorlist reads a plain Server = list, for the oses that publish no // status api: fetched, or read from the disk when the config names a path fn fetch_mirrorlist(spec RankOs) ![]Mirror { if spec.mirrorlist.starts_with('/') { text := os.read_file(spec.mirrorlist) or { return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}') } return parse_mirrors(text) } body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')! return parse_mirrors(body) } // parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the // mirrorlists write them. the line already carries the os's repo layout, so // it is kept whole fn parse_mirrors(text string) []Mirror { mut out := []Mirror{} mut seen := map[string]bool{} for line in text.split_into_lines() { mut s := line.trim_space() if s.starts_with('Server = ') { s = s.all_after('Server = ').trim_space() } if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) { continue } if seen[s] { continue } seen[s] = true out << Mirror{ url: s } } return out } // stdin_text reads stdin to its end, the lines joined again. a read error is // an error here, not an end: a mirror list cut short must not rank as the // whole of it fn stdin_text() !string { mut lines := []string{} for { lines << stdin_line() or { if err is StdinEnd { break } return err } } return lines.join('\n') } // FetchOutcome is what a fetch hands back over its job's reply channel: the // measurement of an answer that came whole, the failure text of one that did // not struct FetchOutcome { ms i64 size int err string } // FetchJob is one fetch for a fetcher thread: the request to make and the // channel to answer on. the job crosses to the fetcher as a value: the // arguments of a spawned call and heap objects handed across threads have // been seen carrying another probe's values, so a fetch travels by copy and // the fetcher spawns with no arguments at all struct FetchJob { url string range bool limit i64 deadline time.Time reply chan FetchOutcome } // fetch_jobs is the queue the fetcher threads serve __global fetch_jobs = chan FetchJob{cap: 256} // timed_get fetches a url and returns the milliseconds it took and the size // of the answer. range asks for the first byte only, which measures latency. // the timeout comes from the config, and it bounds the probe twice over: each // read and write on its own, and the answer as a whole. the socket timeouts // alone start over with every read, so a mirror that trickles its db a few // bytes at a time would hold a speed probe for as long as it cared to. the // request therefore runs on a fetcher thread and the wait on its answer is // bounded by the deadline directly — a bound that holds even when no chunk // arrives to fire on_progress, as from a mirror that falls silent. the // callback stays as the fetcher's own early exit: the first chunk past the // deadline unwinds it, so a stalled fetch does not linger past its read_timeout fn timed_get(url string, range bool) !(i64, int) { limit := rank_timeout job := FetchJob{ url: url range: range limit: limit deadline: time.now().add(limit * time.second) reply: chan FetchOutcome{cap: 1} } fetch_jobs <- job spawn fetch_worker() mut res := FetchOutcome{} mut timed := false select { res = <-job.reply { } // the timeout branch counts nanoseconds, the unit of time.Duration job.deadline - time.now() { timed = true } } if timed { return error('no whole answer within ${limit}s') } if res.err != '' { return error(res.err) } return res.ms, res.size } // fetch_worker serves one queued fetch and dies. it takes no arguments on // purpose — the job comes off the queue — and one fetcher per fetch keeps the // pairing exact: every queued job has a thread waiting to pop it, whichever // thread answers which fn fetch_worker() { job := <-fetch_jobs or { return } mut req := http.Request{ url: job.url read_timeout: job.limit * time.second write_timeout: job.limit * time.second on_progress: fn [job] (_ &http.Request, _ []u8, _ u64) ! { if time.now() > job.deadline { return error('no whole answer within ${job.limit}s') } } } if job.range { req.header.add_custom('Range', 'bytes=0-0') or { job.reply <- FetchOutcome{ err: err.msg() } return } } start := time.now() resp := req.do() or { job.reply <- FetchOutcome{ err: err.msg() } return } // an answer that needs no body — a 404, a 403 — is a mirror that does // not serve the repo db: a probe without body size is ranked on air // unless the status is turned into the probe's failure if resp.status_code < 200 || resp.status_code >= 300 { job.reply <- FetchOutcome{ err: 'http ${resp.status_code} from ${job.url}' } return } job.reply <- FetchOutcome{ ms: (time.now() - start).milliseconds() size: resp.body.len } } fn probe_latency(m Mirror, spec RankOs, override string) Probe { ms, _ := timed_get(probe_url(m, spec, override), true) or { return Probe{ url: m.url } } return timed_probe(m.url, ms, 0, false) } fn probe_speed(m Mirror, spec RankOs, override string) Probe { ms, bytes := timed_get(probe_url(m, spec, override), false) or { return Probe{ url: m.url } } return timed_probe(m.url, ms, bytes, true) } // timed_probe is a probe's result out of what the timed request measured: // the latency always, and with speed the bytes a second of a whole fetch — // one that brought no bytes failed, and one quicker than the clock's // millisecond counts as one, never a division by zero fn timed_probe(url string, ms i64, bytes int, speed bool) Probe { if !speed { return Probe{ url: url latency_ms: ms ok: true } } if bytes <= 0 { return Probe{ url: url } } elapsed := if ms <= 0 { 1 } else { ms } return Probe{ url: url latency_ms: ms speed: f64(bytes) / (f64(elapsed) / 1000.0) ok: true } } // Probe is the result of testing one mirror struct Probe { url string latency_ms i64 speed f64 ok bool } // ProbeFn measures one mirror, the os and the path override closed over. it // answers a Probe on every path — a failure is a Probe that is not ok — and // that is what lets probe_batch count on one answer per mirror type ProbeFn = fn (Mirror) Probe // probe_batch tests every mirror, rank_parallelism() at a time, and advances // the bar by each finished probe. quiet draws no bar, so the output can be // piped. the answers come back in the order they finish, not the input's fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe { mut out := []Probe{cap: mirrors.len} if mirrors.len == 0 { return out } mut bar := unsafe { &Meter(nil) } if !quiet { bar = ui.meter(i64(mirrors.len), label) bar.start() } // a parallelism that slipped past the config's floor would start no // worker at all: one at a time is the least conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() } workers := if conc < mirrors.len { conc } else { mirrors.len } // the whole batch is queued, then the queue closed: a worker that finds // it drained is done. a pool rather than slots of conc means a slow probe // holds back only its own worker, not the next slot's fast ones jobs := chan Mirror{cap: mirrors.len} for m in mirrors { jobs <- m } jobs.close() // the answers channel holds a whole batch, so a worker never waits on the // collector to hand its answer over answers := chan Probe{cap: mirrors.len} for _ in 0 .. workers { spawn probe_worker(jobs, answers, probe) } // one answer per mirror, each sent by the worker that took it: the probe // answers on every path, and a panic in any thread ends the process // rather than stranding this loop. a probe that hangs is bounded by the // network's own timeouts (rank_timeout on read and write, the net // module's on connect) and by timed_get's deadline on the whole answer for _ in 0 .. mirrors.len { out << <-answers if !quiet { bar.add(i64(1)) } } return out } // probe_worker measures mirrors until the queue runs dry. the probe runs on // this thread: the arguments of a spawned call are evaluated by the caller, // so spawning the send of a probe's result runs every probe on the collector, // one after another fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) { for { m := <-jobs or { return } answers <- probe(m) } } fn speed_mib(bytes_per_sec f64) string { return '${bytes_per_sec / 1048576.0:.2f} MiB/s' } fn sync_age(last_sync string) string { if last_sync == '' { return '-' } synced := time.parse_rfc3339(last_sync) or { return '-' } hours := (time.now().unix() - synced.unix()) / 3600 return '${hours}h ago' } // mirrors_lip is the blip file of the ranked urls: mirrors/.lip defines // mirrors-, the way repos.lip expects. each url is a string literal // escaped by blip's own printer: the urls come from the network and the file // is config that vpac runs as root, so a quote in a url must stay inside its // string fn mirrors_lip(os_name string, urls []string, date string) string { var := 'mirrors-${os_name}' mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n' content += '(unless (defined? ${var}) (define ${var} []))\n' content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n' return content } // write_config_mirrors writes the ranked urls as the blip file the config // requires fn write_config_mirrors(os_name string, urls []string) !string { target := rank_write_target(os_name) os.mkdir_all(os.dir(target))! os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))! return target } // Ranked is one mirror of a ranking: its probe, and when it last synced as // the mirror status says ('' when it is not known) struct Ranked { Probe last_sync string } // rank_mirrors measures the mirrors of an os and returns the best of them, // at most config.top, fastest first. the probes draw on the ui unless the // result goes to a file or a mirrorlist fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked { spec := rank_oses[os_name] mirrors := if config.stdin { parse_mirrors(stdin_text()!) } else if spec.status_json != '' { fetch_status_mirrors(os_name, spec)! } else { fetch_mirrorlist(spec)! } if mirrors.len == 0 { return error('no usable mirrors to rank') } mut sync_of := map[string]string{} for m in mirrors { sync_of[m.url] = m.last_sync } quiet := config.mirrorlist || config.output != '' override := config.path mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe { return probe_latency(m, spec, override) }, quiet).filter(it.ok) latency.sort(a.latency_ms < b.latency_ms) if latency.len > rank_speed_candidates { latency = latency[..rank_speed_candidates].clone() } candidates := latency.map(Mirror{ url: it.url last_sync: sync_of[it.url] or { '' } }) mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe { return probe_speed(m, spec, override) }, quiet).filter(it.ok) results.sort(a.speed > b.speed) // the best few are measured again, one at a time, and averaged, so one // lucky or unlucky transfer does not decide the order for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } { again := probe_speed(Mirror{ url: results[i].url }, spec, config.path) if again.ok { results[i] = Probe{ url: results[i].url latency_ms: results[i].latency_ms speed: (results[i].speed + again.speed) / 2.0 ok: true } } } results.sort(a.speed > b.speed) ui.stop() if results.len == 0 { return error('no mirror answered the speed test') } top := if results.len < config.top { results.len } else { config.top } return results[..top].map(Ranked{ Probe: it last_sync: sync_of[it.url] or { '' } }) } // rank ranks the mirrors, then writes them where config says, or prints them fn rank(config ConfigRank) ! { os_name := rank_os_name(config.query)! mut ui := new_trans_ui() defer { ui.stop() } ranked := rank_mirrors(mut ui, os_name, config)! urls := ranked.map(it.url) if config.write { target := write_config_mirrors(os_name, urls)! report('wrote ${urls.len} mirrors to ${target}') } // a frontend gets the ranking itself, and formats it as it needs: the // mirrorlist and output forms shape the printable text, which under // --ui ipc lands in the log anyway, so the event goes out before // whatever those flags do with the result if ipc_on() { emit(MirrorsEvent{ mirrors: ranked.map(MirrorEvent{ url: it.url latency_ms: it.latency_ms speed: it.speed last_sync: it.last_sync }) }) } if config.output != '' { os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')! report('wrote ${urls.len} mirrors to ${config.output}') return } if config.mirrorlist { println(urls.map('Server = ${it}').join('\n')) return } if ipc_on() { return } // sync paints the finished spinner frames before the ranking prints ui.sync() mut rows := []Row{} for i, m in ranked { rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed), sync_age(m.last_sync)) } println(table_text(rows, '', ' ')) }