windows: autoProxy routes slow sites, and has a page in the app

As upstream's sampler and slow judge: every minute, eleven Clash API
snapshots a second apart; a site whose best direct transfer never beat
slowBelowKiBps three times is owed an exit, and gets the first, in probe
order, that answers it as well as direct does (probe --via); routed
slow, it moves on after crawling twice there, and with no exit left it
stays direct for a TTL. Here the Clash API is always on, so it works
whatever the selection.

The app's autoProxy page: on or off, a site probed or learned, the sites
routed (forget one or all), the exits (bad ones marked), the exclusions
and the slowness threshold. tools/screenshots.sh takes every page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 16:47:45 +03:00
1 parent 694e176353
commit 95ec15e14a
26 files changed
+727 -20

No files matched your search

+202 -3
View File
@@ -288,7 +288,8 @@ pub fn registrable(host: &str) -> Option<String> {
// --- the state -----------------------------------------------------------------------------
/// A destination routed through an exit: probed blocked directly ("destination").
/// A destination routed through an exit: probed blocked directly ("destination"), or
/// crawling directly ("slow").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Route {
@@ -298,6 +299,41 @@ pub struct Route {
#[serde(default)]
pub path: String,
pub at: u64,
/// "slow": times it crawled on its exit since it last did not; two move it on.
#[serde(default, skip_serializing_if = "is_zero")]
pub bad: u32,
/// "slow": the exits tried, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tried: Vec<String>,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
/// What the transfer sampler saw: a host's best connection through an exit, crawling
/// (`slow`) or not, and its fastest second.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation {
pub domain: String,
pub host: String,
pub exit: String,
pub slow: bool,
pub peak: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowHits {
pub n: u32,
pub first: u64,
}
/// A site owed an exit for crawling directly, and the exits tried for it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowWant {
pub host: String,
#[serde(default)]
pub tried: Vec<String>,
}
/// What the last probe of a host found.
@@ -349,6 +385,12 @@ pub struct State {
pub exits: BTreeMap<String, ExitInfo>,
pub backlog: BTreeMap<String, Queued>,
pub last_run: u64,
/// Hosts seen crawling directly, within a day.
pub slow_hits: BTreeMap<String, SlowHits>,
/// Sites owed an exit for crawling, by registrable domain.
pub slow_want: BTreeMap<String, SlowWant>,
/// Sites no exit carried better, left direct until then.
pub slow_skip: BTreeMap<String, u64>,
}
/// Most entries the backlog keeps: every distinct name dialled is one.
@@ -372,6 +414,8 @@ impl State {
self.domains.remove(domain);
self.hosts.retain(|_, h| h.domain != domain);
self.backlog.retain(|_, q| q.domain != domain);
self.slow_want.remove(domain);
self.slow_skip.remove(domain);
for e in self.exits.values_mut() {
if e.strikes.remove(domain).is_some() {
rebad(e);
@@ -383,6 +427,8 @@ impl State {
pub fn clear(&mut self) {
self.domains.clear();
self.hosts.clear();
self.slow_want.clear();
self.slow_skip.clear();
for e in self.exits.values_mut() {
e.strikes.clear();
rebad(e);
@@ -401,7 +447,10 @@ impl State {
if p.verdict == "destination"
&& let Some(exit) = &p.exit
{
self.domains.insert(domain.to_owned(), Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now });
self.domains.insert(
domain.to_owned(),
Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now, bad: 0, tried: Vec::new() },
);
}
let exit = if p.verdict == "destination" { p.exit.clone() } else { None };
self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now });
@@ -466,6 +515,113 @@ impl State {
}
}
impl State {
/// What the sampler saw, folded in (autoproxy-slow-judge.jq). `hits` crawls on direct
/// within a day make a site owed an exit (`slow_want`); once routed it is judged on that
/// exit alone: a fast transfer keeps it, two slow ones move it to the next. Never moved:
/// censor verdicts (zapret's) and sites skipped for a while.
pub fn judge_slow(&mut self, obs: &[Observation], now: u64, hits: u32) {
self.slow_hits.retain(|_, h| h.first + 86400 > now);
for x in obs {
if let Some(r) = self.domains.get_mut(&x.domain)
&& r.verdict == "slow"
{
if x.exit != r.exit {
} else if x.slow {
r.bad += 1;
} else {
r.bad = 0;
r.at = now;
}
continue;
}
let skip = self.domains.contains_key(&x.domain)
|| x.exit != DIRECT
|| !x.slow
|| self.slow_want.contains_key(&x.domain)
|| self.slow_skip.get(&x.domain).is_some_and(|u| *u > now)
|| self.hosts.get(&x.host).is_some_and(|h| h.verdict == "censor");
if skip {
continue;
}
let h = self.slow_hits.entry(x.host.clone()).or_insert(SlowHits { n: 0, first: now });
h.n += 1;
if h.n >= hits {
self.slow_hits.remove(&x.host);
self.slow_want.insert(x.domain.clone(), SlowWant { host: x.host.clone(), tried: Vec::new() });
}
}
let moved: Vec<(String, Route)> =
self.domains.iter().filter(|(_, r)| r.verdict == "slow" && r.bad >= 2).map(|(d, r)| (d.clone(), r.clone())).collect();
for (d, r) in moved {
self.domains.remove(&d);
let tried = if r.tried.is_empty() { vec![r.exit.clone()] } else { r.tried.clone() };
self.slow_want.insert(d, SlowWant { host: r.host, tried });
}
self.slow_skip.retain(|_, until| *until > now);
if self.slow_hits.len() > 5000 {
let mut v: Vec<(String, SlowHits)> = std::mem::take(&mut self.slow_hits).into_iter().collect();
v.sort_by_key(|(_, h)| std::cmp::Reverse(h.n));
v.truncate(5000);
self.slow_hits = v.into_iter().collect();
}
while self.slow_want.len() > 500 {
let last = self.slow_want.keys().next_back().cloned().unwrap();
self.slow_want.remove(&last);
}
}
/// A crawling site's next exit found: routed through it.
pub fn route_slow(&mut self, domain: &str, host: &str, exit: &str, tried: Vec<String>, now: u64) {
self.domains.insert(
domain.to_owned(),
Route { verdict: "slow".into(), exit: exit.to_owned(), host: host.to_owned(), path: String::new(), at: now, bad: 0, tried },
);
self.slow_want.remove(domain);
}
/// No exit carries a crawling site better: left direct for `ttl`.
pub fn skip_slow(&mut self, domain: &str, now: u64, ttl: u64) {
self.slow_skip.insert(domain.to_owned(), now + ttl);
self.slow_want.remove(domain);
}
}
/// From Clash API `/connections` snapshots a second apart: per host and exit that moved at
/// least `min` bytes, its best connection's fastest second, and whether it never beat `below`
/// in any second (paced streams burst, so they read fast). Probe and test listeners skipped;
/// `chains[0]` is the exit that carried it. (autoproxy-slow-sample.jq)
pub fn sample_transfers(snapshots: &[Value], min: u64, below: u64) -> Vec<(String, String, bool, u64)> {
// id -> (host, exit, [download per snapshot])
let mut seen: BTreeMap<String, (String, String, Vec<Option<u64>>)> = BTreeMap::new();
for (i, snap) in snapshots.iter().enumerate() {
for c in snap["connections"].as_array().into_iter().flatten() {
let kind = c["metadata"]["type"].as_str().unwrap_or("");
if kind.contains("/probe-in-") || kind.ends_with("/proxy-suite-test-in") {
continue;
}
let Some(id) = c["id"].as_str() else { continue };
let host = c["metadata"]["host"].as_str().unwrap_or("").to_owned();
let exit = c["chains"][0].as_str().unwrap_or("").to_owned();
let e = seen.entry(id.to_owned()).or_insert_with(|| (host, exit, vec![None; snapshots.len()]));
e.2[i] = c["download"].as_u64();
}
}
let mut best: BTreeMap<(String, String), (u64, u64)> = BTreeMap::new();
for (host, exit, d) in seen.into_values() {
let deltas: Vec<u64> = d.windows(2).filter_map(|w| Some(w[1]?.saturating_sub(w[0]?))).collect();
let (total, peak) = (deltas.iter().sum::<u64>(), deltas.iter().copied().max().unwrap_or(0));
if host.is_empty() || exit.is_empty() || deltas.is_empty() || total < min {
continue;
}
let b = best.entry((host, exit)).or_insert((0, 0));
if peak >= b.0 {
*b = (peak, total);
}
}
best.into_iter().map(|((host, exit), (peak, _))| (host, exit, peak < below, peak)).collect()
}
fn rebad(e: &mut ExitInfo) {
e.bad = e.strikes.len() >= 2;
let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect();
@@ -634,7 +790,7 @@ mod tests {
#[test]
fn the_backlog_skips_what_is_known_and_keeps_counting() {
let mut s = State::default();
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0 });
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0, bad: 0, tried: Vec::new() });
let counts: BTreeMap<String, (String, u64)> = [
("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)),
("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)),
@@ -651,6 +807,49 @@ mod tests {
assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address");
}
fn obs(d: &str, exit: &str, slow: bool) -> Observation {
Observation { domain: d.into(), host: format!("www.{d}"), exit: exit.into(), slow, peak: 1 }
}
#[test]
fn crawling_three_times_owes_a_site_an_exit_and_two_more_move_it_on() {
let mut s = State::default();
s.judge_slow(&[obs("slow.example", "direct", true), obs("fast.example", "direct", false)], 10, 3);
s.judge_slow(&[obs("slow.example", "direct", true)], 20, 3);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "direct", true)], 30, 3);
assert_eq!(s.slow_want["slow.example"].host, "www.slow.example");
s.route_slow("slow.example", "www.slow.example", "nl", vec!["nl".into()], 40);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "nl", true)], 50, 3);
s.judge_slow(&[obs("slow.example", "nl", false)], 60, 3);
assert_eq!(s.domains["slow.example"].bad, 0, "a fast transfer keeps it");
s.judge_slow(&[obs("slow.example", "nl", true)], 70, 3);
s.judge_slow(&[obs("slow.example", "nl", true)], 80, 3);
assert!(!s.domains.contains_key("slow.example"));
assert_eq!(s.slow_want["slow.example"].tried, ["nl"]);
s.skip_slow("slow.example", 90, 1000);
s.judge_slow(&[obs("slow.example", "direct", true)], 100, 1);
assert!(s.slow_want.is_empty(), "skipped for a while");
}
#[test]
fn transfers_are_judged_by_their_fastest_second() {
let snap = |down: &[(&str, &str, &str, u64)]| {
json!({ "connections": down.iter().map(|(id, host, exit, d)| json!({
"id": id, "download": d, "chains": [exit], "metadata": { "host": host, "type": "mixed/mixed-in" },
})).collect::<Vec<_>>() })
};
let snaps = [
snap(&[("1", "a.example", "direct", 0), ("2", "b.example", "direct", 0)]),
snap(&[("1", "a.example", "direct", 100_000), ("2", "b.example", "direct", 400_000)]),
snap(&[("1", "a.example", "direct", 200_000), ("2", "b.example", "direct", 400_100)]),
snap(&[("1", "a.example", "direct", 300_000), ("2", "b.example", "direct", 400_200)]),
];
let out = sample_transfers(&snaps, 250_000, 150 * 1024);
assert_eq!(out, [("a.example".to_owned(), "direct".to_owned(), true, 100_000), ("b.example".to_owned(), "direct".to_owned(), false, 400_000)]);
}
#[test]
fn sites_and_local_targets() {
assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk"));
@@ -131,9 +131,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
v.warn(path, format!("{what} {IGNORED}"));
}
}
if cfg.proxy.enable && cfg.proxy.auto_proxy.enable && cfg.proxy.auto_proxy.slow_below_kibps > 0 {
v.warn("proxy.autoProxy.slowBelowKiBps", "routing slow destinations is not on Windows yet: autoProxy routes the blocked ones");
}
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
}
@@ -316,9 +313,8 @@ fn proxy(cfg: &Config, v: &mut Issues) {
if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend");
}
if p.auto_proxy.slow_below_kibps > 0 && p.auto_proxy.enable && p.selection == Selection::First {
v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\"");
}
// Upstream samples transfers through the Clash API, which "first" selection leaves off
// there; here it is always on, so slow sites are routed whatever the selection.
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}