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");
}
+1 -1
View File
@@ -5,7 +5,7 @@ use std::borrow::Cow;
use gpui_kit::*;
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp]);
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route]);
pub struct AppAssets;
+338
View File
@@ -0,0 +1,338 @@
//! autoProxy: on or off; a site probed through each exit, or learned now; the sites it routed
//! and through what, each forgotten on its own; the exits, bad ones marked; what it never
//! touches, and how slow a site must be to be moved.
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::{Value, json};
use super::widgets::{card, hint, page};
use crate::model::Model;
pub struct AutoProxyPage {
model: Entity<Model>,
site: Entity<InputState>,
exclude: Entity<TextareaState>,
slow: Entity<InputState>,
/// What the service listed last, or why it could not.
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// The last probe: its answer, or that it runs.
probe: Option<Result<Value, String>>,
probing: bool,
/// The exclusions and threshold the inputs were last filled from (see the DPI page).
shown: (String, String),
_subscriptions: Vec<Subscription>,
}
impl AutoProxyPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let site = cx.new(|cx| InputState::new(window, cx).placeholder("example.com"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder("intranet.example — one per line"));
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
this.sync(window, cx);
// The listing with the service's own refresh, every few seconds at most.
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(5)) {
this.load(cx);
}
})];
let mut this = Self {
model,
site,
exclude,
slow,
list: Ok(Value::Null),
loaded_at: None,
probe: None,
probing: false,
shown: Default::default(),
_subscriptions: subscriptions,
};
this.sync(window, cx);
this.load(cx);
this
}
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let a = self.model.read(cx).config()["proxy"]["autoProxy"].clone();
let exclude = a["exclude"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n");
let slow = a["slowBelowKiBps"].as_u64().map(|n| n.to_string()).unwrap_or_default();
let fresh = (exclude, slow);
if fresh != self.shown {
if self.exclude.read(cx).value() == self.shown.0.as_str() {
let v = fresh.0.clone();
self.exclude.update(cx, |s, cx| s.set_value(v, window, cx));
}
if self.slow.read(cx).value() == self.shown.1.as_str() {
let v = fresh.1.clone();
self.slow.update(cx, |s, cx| s.set_value(v, window, cx));
}
self.shown = fresh;
}
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AutoList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let site = self.site.read(cx).value().trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_owned();
if site.is_empty() {
window.push_notification(Notification::error("Type a site first: example.com"), cx);
return None;
}
Some(site)
}
fn probe(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(target) = self.site(window, cx) else { return };
self.probing = true;
self.probe = None;
cx.notify();
let job = self.model.read(cx).bridge().call(Request::AutoProbe { target, exits: None, via: None, keep_going: true });
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.probing = false;
this.probe = Some(r.map_err(|e| format!("{e:#}")));
cx.notify();
})
.ok();
})
.detach();
}
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(site) = self.site(window, cx) else { return };
let site = site.split('/').next().unwrap_or("").to_owned();
self.model.update(cx, |m, cx| m.request(format!("{site}: probed now, routed if it needs it"), Request::AutoLearn { hosts: vec![site] }, cx));
}
fn forget(&mut self, domain: Option<String>, cx: &mut Context<Self>) {
let what = domain.as_ref().map_or("Everything learned is forgotten".to_owned(), |d| format!("{d} is forgotten"));
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
let slow_text = self.slow.read(cx).value().trim().to_owned();
let Ok(slow) = (if slow_text.is_empty() { Ok(0) } else { slow_text.parse::<u32>() }) else {
window.push_notification(Notification::error(format!("“{slow_text}” is not a speed in KiB/s (0 turns it off)")), cx);
return;
};
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
self.model.update(cx, |m, cx| {
m.edit(
"autoProxy saved",
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "exclude"], json!(exclude));
edits::set_path(c, &["proxy", "autoProxy", "slowBelowKiBps"], json!(slow));
Ok(())
},
cx,
)
});
}
}
fn row(cx: &App) -> Div {
div().h_flex().gap_3().items_center().py_2().border_t_1().border_color(cx.theme().border)
}
impl Render for AutoProxyPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let a = m.config()["proxy"]["autoProxy"].clone();
let body = page("autoProxy", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let list = self.list.clone();
let on = a["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("ap-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "autoProxy is on" } else { "autoProxy is off" },
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
let state = match (on, running) {
(false, _) => Tag::secondary().child("off"),
(true, false) => Tag::warning().child("waiting for the local proxy"),
(true, true) => Tag::success().child("running"),
};
let about = card("autoProxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state))
.child(hint(
"It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct.",
cx,
));
let probing = self.probing;
let mut try_card = card("Probe or learn a site", None, cx)
.child(hint("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", cx))
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(&self.site)))
.child(
Button::new("ap-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { "Probing…" } else { "Probe" })
.disabled(probing || !running)
.on_click(cx.listener(|this, _, window, cx| this.probe(window, cx))),
)
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label("Learn").disabled(!running).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
);
match &self.probe {
Some(Ok(p)) => {
let verdict = p["verdict"].as_str().unwrap_or("");
let text = match verdict {
"ok" => "Reachable directly: nothing to do".to_owned(),
"destination" => format!("Blocked directly: routed through {}", p["exit"].as_str().unwrap_or("an exit")),
"censor" => "Cut on the way: zapret's to fix, left direct".to_owned(),
"both-fail" => "Fails through every exit: not a block".to_owned(),
"unreachable" => "No exit reaches it at all".to_owned(),
v => v.to_owned(),
};
try_card = try_card.child(div().font_medium().child(text));
for r in p["rows"].as_array().into_iter().flatten() {
let f = &r["fetch"];
let what = match f["status"].as_u64() {
Some(s) => format!("{s}, {} bytes{}", f["bytes"], f["block"].as_str().filter(|b| !b.is_empty()).map(|b| format!(", {b} page")).unwrap_or_default()),
None => format!("no answer ({})", f["error"].as_str().unwrap_or("")),
};
let judgement = r["judgement"].as_str().unwrap_or("");
let tag = match judgement {
"ok" => Tag::success(),
"dead" => Tag::danger(),
_ => Tag::warning(),
};
try_card = try_card.child(
row(cx)
.text_sm()
.child(div().w(px(150.)).truncate().child(r["tag"].as_str().unwrap_or("").to_owned()))
.child(div().w(px(100.)).text_color(cx.theme().muted_foreground).child(r["path"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().child(what))
.child(tag.child(judgement.to_owned())),
);
}
}
Some(Err(e)) => try_card = try_card.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
None => {}
}
let mut routed = card(
"Routed sites",
Some(
div()
.h_flex()
.gap_2()
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label("Forget all").on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.into_any_element(),
),
cx,
);
match &list {
Err(e) => routed = routed.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let domains = l["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
routed = routed.child(hint("Nothing routed yet.", cx));
}
for (i, d) in domains.iter().enumerate() {
let domain = d["domain"].as_str().unwrap_or("").to_owned();
let why = if d["verdict"] == "slow" { Tag::warning().child("slow") } else { Tag::danger().child("blocked") };
let forget = domain.clone();
routed = routed.child(
row(cx)
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
.child(why)
.child(div().w(px(160.)).truncate().text_sm().child(format!("via {}", d["exit"].as_str().unwrap_or(""))))
.child(Button::new(("ap-forget", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.forget(Some(forget.clone()), cx)))),
);
}
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
routed = routed.child(hint(
format!(
"{} site(s) judged; {censored} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
l["hostsJudged"].as_u64().unwrap_or(0),
l["backlog"].as_u64().unwrap_or(0),
l["slowWaiting"].as_u64().unwrap_or(0)
),
cx,
));
}
}
let mut exits = card("Exits", None, cx).child(hint("Probed one per network first. One that two sites refused is bad, and probed last.", cx));
if let Ok(l) = &list {
for e in l["exits"].as_array().into_iter().flatten() {
let bad = e["bad"] == true;
exits = exits.child(
row(cx)
.child(div().w(px(180.)).truncate().font_medium().child(e["tag"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().text_sm().text_color(cx.theme().muted_foreground).child(format!(
"{} {}",
e["ip"].as_str().unwrap_or(""),
e["asn"].as_str().unwrap_or("")
)))
.child(if bad { Tag::danger().child("bad") } else { Tag::success().child("ok") }),
);
}
}
let options = card("Options", Some(Button::new("ap-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
.child(
div()
.h_flex()
.gap_4()
.items_start()
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Never probe or route (with their subdomains)")).child(Textarea::new(&self.exclude)))
.child(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child("Move sites slower than (KiB/s, 0: never)")).child(Input::new(&self.slow))),
)
.child(hint("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", cx));
body.child(about).child(try_card).child(routed).child(exits).child(options)
}
}
+12 -2
View File
@@ -1,6 +1,7 @@
//! The window: a sidebar of pages, the page shown, and what came of each change as a
//! notification.
mod autoproxy;
mod components;
mod dpi;
mod logs;
@@ -26,13 +27,15 @@ pub enum Page {
Telegram,
Whitelist,
Outbounds,
AutoProxy,
Logs,
Settings,
Components,
}
impl Page {
const ALL: [Page; 8] = [Page::Overview, Page::Dpi, Page::Telegram, Page::Whitelist, Page::Outbounds, Page::Logs, Page::Settings, Page::Components];
const ALL: [Page; 9] =
[Page::Overview, Page::Dpi, Page::Telegram, Page::Whitelist, Page::Outbounds, Page::AutoProxy, Page::Logs, Page::Settings, Page::Components];
fn title(self) -> &'static str {
match self {
@@ -41,6 +44,7 @@ impl Page {
Page::Telegram => "Telegram proxy",
Page::Whitelist => "Whitelist bypass",
Page::Outbounds => "Outbounds",
Page::AutoProxy => "autoProxy",
Page::Logs => "Logs",
Page::Settings => "Settings",
Page::Components => "Components",
@@ -54,6 +58,7 @@ impl Page {
Page::Telegram => IconName::Send,
Page::Whitelist => IconName::Video,
Page::Outbounds => IconName::Globe,
Page::AutoProxy => IconName::Route,
Page::Logs => IconName::SquareTerminal,
Page::Settings => IconName::Settings,
Page::Components => IconName::Package,
@@ -69,6 +74,7 @@ pub struct AppView {
outbounds: Entity<outbounds::OutboundsPage>,
/// Made when first shown.
whitelist: Option<Entity<whitelist::WhitelistPage>>,
autoproxy: Option<Entity<autoproxy::AutoProxyPage>>,
/// Made when first shown: following the logs starts then.
logs: Option<Entity<logs::LogsPage>>,
/// Made when first shown, as it loads the configuration into its editor then.
@@ -92,7 +98,7 @@ impl AppView {
let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx));
let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx));
let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx));
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
}
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
@@ -125,6 +131,10 @@ impl Render for AppView {
self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element()
}
Page::Outbounds => self.outbounds.clone().into_any_element(),
Page::AutoProxy => {
let model = self.model.clone();
self.autoproxy.get_or_insert_with(|| cx.new(|cx| autoproxy::AutoProxyPage::new(model, window, cx))).clone().into_any_element()
}
Page::Logs => {
let model = self.model.clone();
self.logs.get_or_insert_with(|| cx.new(|cx| logs::LogsPage::new(model, cx))).clone().into_any_element()
+93 -1
View File
@@ -35,6 +35,8 @@ pub struct AutoProxy {
pub requests: std::sync::Mutex<Vec<String>>,
/// Hosts apps dialled directly since the last run, with how often.
pub dialled: std::sync::Mutex<BTreeMap<String, u64>>,
/// What the transfer sampler saw since the last run: host, exit, crawling, fastest second.
pub samples: std::sync::Mutex<Vec<(String, String, bool, u64)>>,
pub wake: tokio::sync::Notify,
}
@@ -390,6 +392,65 @@ pub async fn run(shared: &Shared, mode: Mode) {
.collect();
state.queue(&counts, now, ttl);
save_and(&state, false).await;
// What the sampler saw crawl: each such site gets the next exit, in probe order, that
// answers it as well as direct does; none left, it stays direct for a TTL.
let samples = std::mem::take(&mut *auto.samples.lock().unwrap());
if opts.slow_below_kibps > 0 && !samples.is_empty() {
let obs: Vec<ap::Observation> = samples
.into_iter()
.filter(|(h, ..)| ap::host_ok(h) && !excluded(&opts, h))
.filter_map(|(host, exit, slow, peak)| ap::registrable(&host).map(|domain| ap::Observation { domain, host, exit, slow, peak }))
.collect();
let before = state.domains.clone();
state.judge_slow(&obs, now, 3);
let (_, _, ordered) = ap::rounds(&exits.tags(), &state);
let wanted: Vec<(String, ap::SlowWant)> = state.slow_want.iter().take(20).map(|(d, w)| (d.clone(), w.clone())).collect();
for (dom, want) in wanted {
let mut tried = want.tried.clone();
let was = tried.last().cloned();
// It crawled twice on the exit it was routed through.
if let Some(was) = &was {
state.strike(std::slice::from_ref(was), &dom, "slow", now, ttl);
}
let mut via = None;
for tag in &ordered {
if tried.contains(tag) {
continue;
}
tried.push(tag.clone());
let host = want.host.as_str();
let fetch = |t: String, path: String| async move { exits.fetch(&t, host, &path).await };
let p = ap::stand_in(host, tag, &PATHS, fetch).await;
if p.verdict == "ok" {
via = Some(tag.clone());
break;
}
// Refused what direct gets: by a block page, or by the origin.
let rows: Vec<&ap::Row> = p.rows.iter().filter(|r| &r.tag == tag).collect();
let why = rows
.iter()
.find(|r| r.judgement == ap::Judgement::Wall)
.map(|r| format!("wall:{}", r.fetch.block))
.or_else(|| rows.iter().any(|r| r.judgement == ap::Judgement::Blocked).then(|| "refused".to_owned()));
if let Some(why) = why {
state.strike(std::slice::from_ref(tag), &dom, &why, now, ttl);
}
}
let how = was.as_deref().map_or("directly".to_owned(), |w| format!("via {w}"));
match via {
Some(v) => {
note(format!("slow {dom}: crawls {how}, routed via {v}")).await;
state.route_slow(&dom, &want.host, &v, tried, now);
}
None => {
note(format!("slow {dom}: crawls {how}, and no other exit reaches it; left direct")).await;
state.skip_slow(&dom, now, ttl);
}
}
}
save_and(&state, state.domains != before).await;
}
}
// Probe: the requests, then broken routes, then the backlog.
@@ -539,6 +600,36 @@ pub async fn sample(shared: Shared) {
}
}
/// Live transfers every minute while slow sites are routed (`slowBelowKiBps`): eleven Clash
/// API snapshots a second apart, the transfers that moved enough kept for the next run, as
/// upstream's sampler timer does.
pub async fn sample_slow(shared: Shared) {
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
let (clash, auto, below) = {
let s = shared.lock().await;
let cfg = s.cfg();
let below = cfg.proxy.auto_proxy.slow_below_kibps;
if below == 0 || exits(&s).is_none() {
continue;
}
(crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone(), below)
};
let mut snapshots = Vec::with_capacity(11);
for i in 0..11 {
if i > 0 {
tokio::time::sleep(Duration::from_secs(1)).await;
}
snapshots.push(clash.connections().await.unwrap_or(Value::Null));
}
let seen = ap::sample_transfers(&snapshots, 300 * 1024, u64::from(below) * 1024);
let mut samples = auto.samples.lock().unwrap();
samples.extend(seen);
let over = samples.len().saturating_sub(10_000);
samples.drain(..over);
}
}
/// What `proxy-ctl proxy auto` lists. Without `detail` (the secrets scope) the sites routed
/// and the counts only: the hosts probed, those left to zapret and the sites behind each
/// strike are browsing history, as the logs are.
@@ -579,6 +670,7 @@ pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options, detail: boo
"hostsJudged": s.hosts.len(),
"censored": censored,
"backlog": s.backlog.len(),
"slowWaiting": s.slow_want.len(),
})
}
@@ -624,7 +716,7 @@ mod tests {
ProbeExit { tag: "nl".into(), port: 2, rule_set: Some("autoproxy-1".into()), path: Some(path.to_string_lossy().into()) },
];
let mut s = State::default();
s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1 });
s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1, bad: 0, tried: Vec::new() });
publish(&exits, &s).unwrap();
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v, json!({ "version": 1, "rules": [{ "domain_suffix": ["x.example"] }] }));
+1
View File
@@ -106,6 +106,7 @@ pub async fn run(
tokio::spawn(api::serve(server, shared.clone()));
tokio::spawn(autoproxy::runner(shared.clone()));
tokio::spawn(autoproxy::sample(shared.clone()));
tokio::spawn(autoproxy::sample_slow(shared.clone()));
// First fetches: what the configuration needs and has not got yet.
{
let shared = shared.clone();