diff --git a/CHANGELOG.md b/CHANGELOG.md index d7c22c0e..926a37d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -344,6 +344,27 @@ long-term supported release series. Re-probes move the health state but add no sample to the window `leastLoad` reads, which keeps holding the last 16 scheduled probes. Without failures the observatory probes as before. +- `burstObservatory` is read and run as in Xray-core v26.11.9; it used to be + refused as an unknown root field. `pingConfig` takes `destination`, + `connectivity`, `interval`, `sampling`, `timeout` and `httpMethod` with + Xray-core's defaults and lower bounds. Every subject is pinged once at + start and then `sampling` times at random points of each + `interval * sampling`. `leastLoad`, `leastPing`, `random` and `roundRobin` + read Xray's burst statistics: the latest `sampling` pings no older than two + periods, alive while one of them succeeded, the average as the delay. A + failed ping is not counted while the `connectivity` URL fails too. With + `observatory` also present that one drives selection, as in Xray-core, and + `burstObservatory` is not run. The re-probes that failures of real traffic + bring belong to `observatory`: beside `burstObservatory` alone nothing + follows them, and its window stays the scheduled pings. Deliberately + different, for phones: + `interval`, `sampling` and `timeout` are capped at 24h, 100 and 60s with a + warning; at most four pings run at once; while the connectivity check fails + one ping leaves per backoff of 5s up to `interval` instead of every + scheduled one; and after a network change reported through `rebind_quic` + every subject is pinged again within 3 seconds and its first new sample + replaces the old network's. `CoreConfig` gains `burst_observatory` and + `NetworkChanges` gains `observe`. ## 0.10.1 - 2026-11-16 diff --git a/crates/xray-bench/src/lib.rs b/crates/xray-bench/src/lib.rs index 84650f13..1c847b4f 100644 --- a/crates/xray-bench/src/lib.rs +++ b/crates/xray-bench/src/lib.rs @@ -8824,6 +8824,7 @@ fn dns_outbound_selector_probe_config(rule_count: usize) -> CoreConfig { ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -9323,6 +9324,7 @@ fn phase2_selector_config(member_count: usize) -> CoreConfig { ..RoutingConfig::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -9341,6 +9343,7 @@ fn phase2_chain_config(chain_depth: usize) -> CoreConfig { default_outbound_tag: Some("chain-0000".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -9457,6 +9460,7 @@ async fn measure_phase2_connection_registry( default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), }) @@ -10804,6 +10808,7 @@ fn route_probe_config( ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), }) diff --git a/crates/xray-config/src/lib.rs b/crates/xray-config/src/lib.rs index 192559be..62342bc5 100644 --- a/crates/xray-config/src/lib.rs +++ b/crates/xray-config/src/lib.rs @@ -54,6 +54,13 @@ pub use model::{ UdpNoiseSettings, UdpSudoku, XdnsDomain, XdnsMask, XdnsProtocol, XdnsResolver, XicmpMask, XmcMask, XmcProfile, }; +pub use model::{ + BurstObservatoryConfig, BurstPingConfig, DEFAULT_BURST_OBSERVATORY_DESTINATION, + DEFAULT_BURST_OBSERVATORY_HTTP_METHOD, DEFAULT_BURST_OBSERVATORY_INTERVAL, + DEFAULT_BURST_OBSERVATORY_SAMPLING, DEFAULT_BURST_OBSERVATORY_TIMEOUT, + MAX_BURST_OBSERVATORY_INTERVAL, MAX_BURST_OBSERVATORY_SAMPLING, MAX_BURST_OBSERVATORY_TIMEOUT, + MIN_BURST_OBSERVATORY_INTERVAL, +}; pub use model::{MasqueOutboundSettings, MasqueSettings, MasqueWarpSettings, MASQUE_DEFAULT_XMUX}; pub use parser::{ parse_xray_json, parse_xray_json_with_exclusive_geodata_dirs, parse_xray_json_with_geodata_dir, diff --git a/crates/xray-config/src/model.rs b/crates/xray-config/src/model.rs index 087afd75..8b6a1c70 100644 --- a/crates/xray-config/src/model.rs +++ b/crates/xray-config/src/model.rs @@ -49,6 +49,9 @@ pub struct CoreConfig { pub default_outbound_tag: Option, pub routing: RoutingConfig, pub observatory: Option, + /// Xray's `burstObservatory`. When [`CoreConfig::observatory`] is also + /// present that one drives selection, as in Xray-core, and this is unused. + pub burst_observatory: Option, pub dns: DnsConfig, pub policy: PolicyConfig, } @@ -66,6 +69,83 @@ pub struct ObservatoryConfig { pub enable_concurrency: bool, } +/// `pingConfig.destination` of a burst observatory that names none. +pub const DEFAULT_BURST_OBSERVATORY_DESTINATION: &str = + "https://connectivitycheck.gstatic.com/generate_204"; +/// `pingConfig.interval` of a burst observatory that names none: the average +/// time between two pings of one outbound. +pub const DEFAULT_BURST_OBSERVATORY_INTERVAL: Duration = Duration::from_secs(60); +/// Xray-core raises a shorter nonzero `pingConfig.interval` to this. +pub const MIN_BURST_OBSERVATORY_INTERVAL: Duration = Duration::from_secs(10); +/// A longer `pingConfig.interval` is lowered to this, which keeps the +/// sampling period and the validity of a sample well inside a `Duration`. +pub const MAX_BURST_OBSERVATORY_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); +/// `pingConfig.sampling` of a burst observatory that names none. +pub const DEFAULT_BURST_OBSERVATORY_SAMPLING: u32 = 10; +/// A larger `pingConfig.sampling` is lowered to this. It bounds the memory of +/// one outbound's sample window and the pings scheduled for one period. +pub const MAX_BURST_OBSERVATORY_SAMPLING: u32 = 100; +/// `pingConfig.timeout` of a burst observatory that names none. +pub const DEFAULT_BURST_OBSERVATORY_TIMEOUT: Duration = Duration::from_secs(5); +/// A longer `pingConfig.timeout` is lowered to this, the bound of every +/// outbound URL probe. +pub const MAX_BURST_OBSERVATORY_TIMEOUT: Duration = Duration::from_secs(60); +/// `pingConfig.httpMethod` of a burst observatory that names none. +pub const DEFAULT_BURST_OBSERVATORY_HTTP_METHOD: &str = "HEAD"; + +/// Xray's `burstObservatory`: outbound health from a window of pings spread +/// at random over a sampling period. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BurstObservatoryConfig { + pub subject_selectors: Vec, + pub ping: BurstPingConfig, +} + +/// `burstObservatory.pingConfig` with Xray-core's defaults applied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BurstPingConfig { + /// URL pinged through every observed outbound. + pub destination: String, + /// URL requested without any outbound after a failed ping. While it also + /// fails the network is taken to be down and the ping is not counted. + pub connectivity: Option, + /// Average time between two pings of one outbound. + pub interval: Duration, + /// Pings of one outbound per period and the size of its sample window. + pub sampling: u32, + pub timeout: Duration, + /// Request method, sent as written. + pub http_method: String, +} + +impl BurstPingConfig { + /// The time over which `sampling` pings of one outbound are spread. + #[must_use] + pub fn sampling_period(&self) -> Duration { + self.interval.saturating_mul(self.sampling) + } + + /// How long a sample counts. Xray-core keeps it for two periods because + /// pings fall anywhere within one. + #[must_use] + pub fn sample_validity(&self) -> Duration { + self.sampling_period().saturating_mul(2) + } +} + +impl Default for BurstPingConfig { + fn default() -> Self { + Self { + destination: DEFAULT_BURST_OBSERVATORY_DESTINATION.to_owned(), + connectivity: None, + interval: DEFAULT_BURST_OBSERVATORY_INTERVAL, + sampling: DEFAULT_BURST_OBSERVATORY_SAMPLING, + timeout: DEFAULT_BURST_OBSERVATORY_TIMEOUT, + http_method: DEFAULT_BURST_OBSERVATORY_HTTP_METHOD.to_owned(), + } + } +} + #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RoutingConfig { pub rules: Vec, diff --git a/crates/xray-config/src/parser.rs b/crates/xray-config/src/parser.rs index dd3c2a1c..568c7216 100644 --- a/crates/xray-config/src/parser.rs +++ b/crates/xray-config/src/parser.rs @@ -1,4 +1,5 @@ mod blackhole; +mod burst_observatory; mod dns; mod filter; mod fragment; @@ -391,6 +392,7 @@ impl Parser<'_> { let outbounds = self.parse_outbounds(); let routing = self.parse_routing(); let observatory = self.parse_observatory(); + let burst_observatory = self.parse_burst_observatory(); let dns = self.parse_dns(); let policy = self.parse_policy(); let default_outbound_tag = outbounds.first().and_then(|outbound| outbound.tag.clone()); @@ -401,6 +403,7 @@ impl Parser<'_> { default_outbound_tag, routing, observatory, + burst_observatory, dns, policy, } @@ -515,40 +518,7 @@ impl Parser<'_> { } self.reject_unknown_fields(observatory, path, &surface::OBSERVATORY); - let subject_selectors = match observatory.get("subjectSelector") { - None | Some(Value::Null) => Vec::new(), - Some(Value::Array(values)) => { - if values.len() > MAX_OBSERVATORY_SUBJECT_SELECTORS { - self.error( - format!("{path}.subjectSelector"), - format!( - "observatory contains {} subject selectors; maximum supported per configuration is {MAX_OBSERVATORY_SUBJECT_SELECTORS}", - values.len() - ), - ); - return None; - } - let mut selectors = Vec::with_capacity(values.len()); - for (index, value) in values.iter().enumerate() { - let Some(value) = value.as_str() else { - self.error( - format!("{path}.subjectSelector[{index}]"), - "observatory subject selector must be a string", - ); - return None; - }; - selectors.push(value.to_owned()); - } - selectors - } - Some(_) => { - self.error( - format!("{path}.subjectSelector"), - "observatory subjectSelector must be an array", - ); - return None; - } - }; + let subject_selectors = self.parse_subject_selectors(observatory, path, "observatory")?; let probe_url = match observatory.get("probeURL") { None | Some(Value::Null) => DEFAULT_OBSERVATORY_PROBE_URL.to_owned(), Some(Value::String(value)) if value.is_empty() => { diff --git a/crates/xray-config/src/parser/burst_observatory.rs b/crates/xray-config/src/parser/burst_observatory.rs new file mode 100644 index 00000000..39afa3b5 --- /dev/null +++ b/crates/xray-config/src/parser/burst_observatory.rs @@ -0,0 +1,327 @@ +//! `burstObservatory`, as `infra/conf/observatory.go` and +//! `app/observatory/burst/healthping.go` of Xray-core v26.11.9 read it. + +use std::time::Duration; + +use serde_json::Value; + +use super::{parse_xray_duration, Parser, MAX_OBSERVATORY_SUBJECT_SELECTORS}; +use crate::model::{ + BurstObservatoryConfig, BurstPingConfig, DEFAULT_BURST_OBSERVATORY_DESTINATION, + DEFAULT_BURST_OBSERVATORY_HTTP_METHOD, DEFAULT_BURST_OBSERVATORY_INTERVAL, + DEFAULT_BURST_OBSERVATORY_SAMPLING, DEFAULT_BURST_OBSERVATORY_TIMEOUT, + MAX_BURST_OBSERVATORY_INTERVAL, MAX_BURST_OBSERVATORY_SAMPLING, MAX_BURST_OBSERVATORY_TIMEOUT, + MIN_BURST_OBSERVATORY_INTERVAL, +}; +use crate::surface; + +const PATH: &str = "$.burstObservatory"; + +/// A Go `time.ParseDuration` string, which may carry a sign or be a bare `0`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SignedDuration { + Negative, + NonNegative(Duration), +} + +fn parse_signed_duration(raw: &str) -> Option { + let (negative, magnitude) = match raw.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, raw.strip_prefix('+').unwrap_or(raw)), + }; + let magnitude = if magnitude == "0" { + Duration::ZERO + } else { + parse_xray_duration(magnitude)? + }; + Some(if negative && !magnitude.is_zero() { + SignedDuration::Negative + } else { + SignedDuration::NonNegative(magnitude) + }) +} + +/// Go's `net/http` accepts a method made of RFC 7230 token characters. +fn is_http_token(method: &str) -> bool { + !method.is_empty() + && method + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)) +} + +impl Parser<'_> { + pub(super) fn parse_burst_observatory(&mut self) -> Option { + let observatory = self.root.get("burstObservatory")?; + if observatory.is_null() { + return None; + } + if !observatory.is_object() { + self.error(PATH, "burstObservatory must be an object or null"); + return None; + } + self.reject_unknown_fields(observatory, PATH, &surface::BURST_OBSERVATORY); + + let subject_selectors = + self.parse_subject_selectors(observatory, PATH, "burstObservatory")?; + let ping_path = format!("{PATH}.pingConfig"); + let ping = match observatory.get("pingConfig") { + Some(ping @ Value::Object(_)) => self.parse_burst_ping_config(ping, &ping_path)?, + None | Some(Value::Null) => { + self.error(ping_path, "BurstObservatory requires a valid pingConfig"); + return None; + } + Some(_) => { + self.error(ping_path, "burstObservatory pingConfig must be an object"); + return None; + } + }; + if self + .root + .get("observatory") + .is_some_and(|classic| !classic.is_null()) + { + self.warning( + PATH, + "observatory is also present and drives outbound selection, as in Xray-core; burstObservatory is not run", + ); + } + + Some(BurstObservatoryConfig { + subject_selectors, + ping, + }) + } + + /// `subjectSelector` of either observatory: outbound tag prefixes. + pub(super) fn parse_subject_selectors( + &mut self, + observatory: &Value, + path: &str, + owner: &str, + ) -> Option> { + let values = match observatory.get("subjectSelector") { + None | Some(Value::Null) => return Some(Vec::new()), + Some(Value::Array(values)) => values, + Some(_) => { + self.error( + format!("{path}.subjectSelector"), + format!("{owner} subjectSelector must be an array"), + ); + return None; + } + }; + if values.len() > MAX_OBSERVATORY_SUBJECT_SELECTORS { + self.error( + format!("{path}.subjectSelector"), + format!( + "{owner} contains {} subject selectors; maximum supported per configuration is {MAX_OBSERVATORY_SUBJECT_SELECTORS}", + values.len() + ), + ); + return None; + } + let mut selectors = Vec::with_capacity(values.len()); + for (index, value) in values.iter().enumerate() { + let Some(value) = value.as_str() else { + self.error( + format!("{path}.subjectSelector[{index}]"), + format!("{owner} subject selector must be a string"), + ); + return None; + }; + selectors.push(value.to_owned()); + } + Some(selectors) + } + + fn parse_burst_ping_config(&mut self, ping: &Value, path: &str) -> Option { + self.reject_unknown_fields(ping, path, &surface::BURST_PING_CONFIG); + + let destination = self.burst_ping_string(ping, path, "destination")?; + let connectivity = self.burst_ping_string(ping, path, "connectivity")?; + let http_method = match ping.get("httpMethod") { + None | Some(Value::Null) => DEFAULT_BURST_OBSERVATORY_HTTP_METHOD.to_owned(), + Some(Value::String(method)) if method.is_empty() => { + DEFAULT_BURST_OBSERVATORY_HTTP_METHOD.to_owned() + } + // Xray-core trims a nonempty method, and `net/http` reads the + // empty one that whitespace leaves as GET. + Some(Value::String(method)) if method.trim().is_empty() => "GET".to_owned(), + Some(Value::String(method)) if is_http_token(method.trim()) => method.trim().to_owned(), + Some(Value::String(_)) => { + self.error( + format!("{path}.httpMethod"), + "burstObservatory httpMethod must be an HTTP method token", + ); + return None; + } + Some(_) => { + self.error( + format!("{path}.httpMethod"), + "burstObservatory httpMethod must be a string or null", + ); + return None; + } + }; + let interval = match self.burst_ping_duration(ping, path, "interval")? { + None => DEFAULT_BURST_OBSERVATORY_INTERVAL, + Some(SignedDuration::NonNegative(interval)) if interval.is_zero() => { + DEFAULT_BURST_OBSERVATORY_INTERVAL + } + Some(SignedDuration::NonNegative(interval)) + if interval > MAX_BURST_OBSERVATORY_INTERVAL => + { + self.warning( + format!("{path}.interval"), + "burstObservatory interval is too large, 24h is applied", + ); + MAX_BURST_OBSERVATORY_INTERVAL + } + Some(SignedDuration::NonNegative(interval)) + if interval >= MIN_BURST_OBSERVATORY_INTERVAL => + { + interval + } + Some(_) => { + self.warning( + format!("{path}.interval"), + "health check interval is too small, 10s is applied", + ); + MIN_BURST_OBSERVATORY_INTERVAL + } + }; + let timeout = match self.burst_ping_duration(ping, path, "timeout")? { + None | Some(SignedDuration::Negative) => DEFAULT_BURST_OBSERVATORY_TIMEOUT, + Some(SignedDuration::NonNegative(timeout)) if timeout.is_zero() => { + DEFAULT_BURST_OBSERVATORY_TIMEOUT + } + Some(SignedDuration::NonNegative(timeout)) + if timeout > MAX_BURST_OBSERVATORY_TIMEOUT => + { + self.warning( + format!("{path}.timeout"), + "burstObservatory timeout is too large, 60s is applied", + ); + MAX_BURST_OBSERVATORY_TIMEOUT + } + Some(SignedDuration::NonNegative(timeout)) => timeout, + }; + let sampling = match ping.get("sampling") { + None | Some(Value::Null) => DEFAULT_BURST_OBSERVATORY_SAMPLING, + Some(Value::Number(sampling)) if sampling.is_i64() || sampling.is_u64() => { + match sampling.as_i64() { + Some(sampling) if sampling <= 0 => DEFAULT_BURST_OBSERVATORY_SAMPLING, + Some(sampling) if sampling <= i64::from(MAX_BURST_OBSERVATORY_SAMPLING) => { + u32::try_from(sampling).unwrap_or(MAX_BURST_OBSERVATORY_SAMPLING) + } + _ => { + self.warning( + format!("{path}.sampling"), + format!( + "burstObservatory sampling is too large, {MAX_BURST_OBSERVATORY_SAMPLING} is applied" + ), + ); + MAX_BURST_OBSERVATORY_SAMPLING + } + } + } + Some(_) => { + self.error( + format!("{path}.sampling"), + "burstObservatory sampling must be an integer or null", + ); + return None; + } + }; + + Some(BurstPingConfig { + destination: if destination.is_empty() { + DEFAULT_BURST_OBSERVATORY_DESTINATION.to_owned() + } else { + destination + }, + connectivity: (!connectivity.is_empty()).then_some(connectivity), + interval, + sampling, + timeout, + http_method, + }) + } + + /// A URL field, trimmed as Xray-core trims it; absent and null are empty. + fn burst_ping_string(&mut self, ping: &Value, path: &str, key: &str) -> Option { + match ping.get(key) { + None | Some(Value::Null) => Some(String::new()), + Some(Value::String(value)) => Some(value.trim().to_owned()), + Some(_) => { + self.error( + format!("{path}.{key}"), + format!("burstObservatory {key} must be a string or null"), + ); + None + } + } + } + + /// The outer `None` is a reported error, the inner one an absent field. + fn burst_ping_duration( + &mut self, + ping: &Value, + path: &str, + key: &str, + ) -> Option> { + match ping.get(key) { + None | Some(Value::Null) => Some(None), + Some(Value::String(value)) => match parse_signed_duration(value) { + Some(duration) => Some(Some(duration)), + None => { + self.error( + format!("{path}.{key}"), + format!("burstObservatory {key} must be a valid Xray duration string"), + ); + None + } + }, + Some(_) => { + self.error( + format!("{path}.{key}"), + format!("burstObservatory {key} must be a duration string or null"), + ); + None + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signed_durations_follow_go_parse_duration() { + assert_eq!(parse_signed_duration("-5s"), Some(SignedDuration::Negative)); + assert_eq!( + parse_signed_duration("+1m30s"), + Some(SignedDuration::NonNegative(Duration::from_secs(90))) + ); + for zero in ["0", "-0", "0s", "-0s"] { + assert_eq!( + parse_signed_duration(zero), + Some(SignedDuration::NonNegative(Duration::ZERO)), + "{zero}" + ); + } + for invalid in ["", "-", "10", "--5s", "5 s"] { + assert_eq!(parse_signed_duration(invalid), None, "{invalid:?}"); + } + } + + #[test] + fn http_tokens_exclude_separators_and_whitespace() { + assert!(is_http_token("HEAD")); + assert!(is_http_token("get")); + assert!(!is_http_token("GE T")); + assert!(!is_http_token("GET\r\nX: y")); + assert!(!is_http_token("")); + } +} diff --git a/crates/xray-config/src/surface.rs b/crates/xray-config/src/surface.rs index 6a309bf1..7788cc80 100644 --- a/crates/xray-config/src/surface.rs +++ b/crates/xray-config/src/surface.rs @@ -35,6 +35,12 @@ objects! { BLACKHOLE_RESPONSE: ("$.outbounds[].settings.response (blackhole)", ["type", "customResponseData"], "type is required and case-insensitive: none, http (Xray's fixed HTTP 403 reply) or custom. custom sends customResponseData, standard padded base64 of at most 65,535 bytes; absent or null sends nothing. Other types ignore it. Null, empty and unknown responses fail closed, matching Xray."), + BURST_OBSERVATORY: ("$.burstObservatory", + ["subjectSelector", "pingConfig"], + "pingConfig is required, as in Xray-core. With observatory also present that one drives selection, as in Xray-core, and this one is validated and not run."), + BURST_PING_CONFIG: ("$.burstObservatory.pingConfig", + ["destination", "connectivity", "interval", "sampling", "timeout", "httpMethod"], + "Xray-core's defaults: destination https://connectivitycheck.gstatic.com/generate_204, interval 1m (a shorter nonzero one becomes 10s), sampling 10, timeout 5s, httpMethod HEAD. Bounded for phones with a warning: interval at most 24h, sampling at most 100, timeout at most 60s. httpMethod must be an HTTP token."), DNS: ("$.dns", ["fakeIp", "servers", "hosts", "tag", "queryStrategy", "disableCache", "serveStale", "serveExpiredTTL", "disableFallback", "disableFallbackIfMatch", "clientIp", "enableParallelQuery"], "At most 32 servers; the TUN DNS proxy forwards to the first eight distinct ones. clientIp is an IP address every server without its own sends as the EDNS client subnet (/24 for IPv4, /96 for IPv6), as Xray-core sends it. enableParallelQuery asks the selected servers at once, at most eight at a time in selection order; adjacent servers with the same policy race as a group, groups settling in order. Managed selection, cache/fallback policy and IPv4 fake IP only. hosts keys are domain rules as Xray-core reads them, plain text being the whole name; a \"#N\" value answers with DNS RCODE N from 0 to 15. Hosts and server URL semantics require the executable validator."), @@ -216,7 +222,7 @@ objects! { ["version", "status", "reason", "headers"], "The server's response, which the client skips whatever it holds: checked as Xray-core builds it and otherwise unused."), ROOT: ("$", - ["log", "inbounds", "outbounds", "routing", "observatory", "dns", "policy", "reverse", "remarks", "meta", "stats", "api", "metrics", "version", "geodata", "fakeDns", "fakedns"], + ["log", "inbounds", "outbounds", "routing", "observatory", "burstObservatory", "dns", "policy", "reverse", "remarks", "meta", "stats", "api", "metrics", "version", "geodata", "fakeDns", "fakedns"], "log is accepted and ignored. fakeDns (or fakedns, Go reading keys case-insensitively) holds Xray-core's FakeDNS pools, used while a dns server is fakedns. stats, api, metrics, version and geodata are Xray-core apps with no runtime here: an object is accepted with a warning and ignored, any other value but null fails, as Go's decoding does; version's min and max are strings. geodata never downloads files. reverse, the legacy reverse proxy with bridges and portals, is refused unless null, with Xray-core v26.10.31's message: it removed the feature for the VLESS reverse proxy (an outbound's reverse). remarks (a string) and meta (an object) are subscription labels, such as Remnawave's, which Xray-core does not read; they are type-checked and ignored. Missing/non-array inbounds and outbounds currently normalize to empty lists. Non-object JSON roots also normalize to an empty model. Parse success alone does not establish runtime usability."), ROUTING: ("$.routing", ["domainStrategy", "rules", "balancers", "domainMatcher"], diff --git a/crates/xray-config/tests/model_tests.rs b/crates/xray-config/tests/model_tests.rs index abb97e2c..74283b37 100644 --- a/crates/xray-config/tests/model_tests.rs +++ b/crates/xray-config/tests/model_tests.rs @@ -89,6 +89,7 @@ fn normalized_model_can_represent_vless_reality_vision() { default_outbound_tag: Some("proxy".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), }; @@ -150,6 +151,7 @@ fn normalized_model_can_represent_vless_reality_vision() { default_outbound_tag: Some("proxy".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), }; diff --git a/crates/xray-config/tests/parser_tests.rs b/crates/xray-config/tests/parser_tests.rs index 6a991071..76aa7e9a 100644 --- a/crates/xray-config/tests/parser_tests.rs +++ b/crates/xray-config/tests/parser_tests.rs @@ -7208,6 +7208,256 @@ fn raw_with_routing(routing: &str) -> String { raw } +fn raw_with_burst_observatory(burst: &str) -> String { + format!( + r#"{{ + "burstObservatory": {burst}, + "inbounds": [], + "outbounds": [{{ "tag": "direct", "protocol": "freedom" }}] + }}"# + ) +} + +fn burst_ping_config(ping: &str) -> (xray_config::BurstPingConfig, Vec) { + let raw = raw_with_burst_observatory(&format!(r#"{{"pingConfig": {ping}}}"#)); + let parsed = parse_xray_json(&raw).unwrap_or_else(|error| panic!("{ping}: {error:?}")); + let warned = parsed + .diagnostics + .iter() + .filter(|diagnostic| diagnostic.severity == DiagnosticSeverity::Warning) + .filter_map(|diagnostic| diagnostic.path.clone()) + .collect(); + let burst = parsed.config.burst_observatory.expect("burst observatory"); + (burst.ping, warned) +} + +/// Defaults of `app/observatory/burst/healthping.go` `NewHealthPing`. +#[test] +fn burst_observatory_uses_xray_defaults() { + let raw = raw_with_burst_observatory(r#"{"pingConfig": {}}"#); + let parsed = parse_xray_json(&raw).expect("empty pingConfig should use defaults"); + assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics); + assert!(parsed.config.observatory.is_none()); + let burst = parsed.config.burst_observatory.expect("burst observatory"); + + assert!(burst.subject_selectors.is_empty()); + assert_eq!(burst.ping, xray_config::BurstPingConfig::default()); + assert_eq!( + burst.ping.destination, + "https://connectivitycheck.gstatic.com/generate_204" + ); + assert_eq!(burst.ping.connectivity, None); + assert_eq!(burst.ping.interval, Duration::from_secs(60)); + assert_eq!(burst.ping.sampling, 10); + assert_eq!(burst.ping.timeout, Duration::from_secs(5)); + assert_eq!(burst.ping.http_method, "HEAD"); + assert_eq!(burst.ping.sampling_period(), Duration::from_secs(600)); + assert_eq!(burst.ping.sample_validity(), Duration::from_secs(1200)); +} + +#[test] +fn parses_burst_observatory_and_trims_like_xray() { + let raw = raw_with_burst_observatory( + r#"{ + "subjectSelector": ["proxy-", "direct"], + "pingConfig": { + "destination": " https://probe.example/generate_204 ", + "connectivity": " http://connectivity.example/ ", + "interval": "1m30s", + "sampling": 4, + "timeout": "3s", + "httpMethod": " GET " + } + }"#, + ); + + let parsed = parse_xray_json(&raw).expect("burst observatory should parse"); + assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics); + let burst = parsed.config.burst_observatory.expect("burst observatory"); + + assert_eq!(burst.subject_selectors, ["proxy-", "direct"]); + assert_eq!( + burst.ping, + xray_config::BurstPingConfig { + destination: "https://probe.example/generate_204".to_owned(), + connectivity: Some("http://connectivity.example/".to_owned()), + interval: Duration::from_secs(90), + sampling: 4, + timeout: Duration::from_secs(3), + http_method: "GET".to_owned(), + } + ); +} + +/// `NewHealthPing`: interval 0 is 1m and a shorter nonzero one 10s; sampling +/// and timeout at or below zero take their defaults. The upper bounds are +/// xray-rust's. +#[test] +fn burst_observatory_applies_xray_bounds_and_mobile_limits() { + for (ping, interval, warns) in [ + (r#"{"interval": "0s"}"#, 60, false), + (r#"{"interval": "0"}"#, 60, false), + (r#"{"interval": "10s"}"#, 10, false), + (r#"{"interval": "9s"}"#, 10, true), + (r#"{"interval": "-5m"}"#, 10, true), + (r#"{"interval": "24h"}"#, 86_400, false), + (r#"{"interval": "48h"}"#, 86_400, true), + ] { + let (config, warned) = burst_ping_config(ping); + assert_eq!(config.interval, Duration::from_secs(interval), "{ping}"); + let expected: &[&str] = if warns { + &["$.burstObservatory.pingConfig.interval"] + } else { + &[] + }; + assert_eq!(warned, expected, "{ping}"); + } + for (ping, sampling, warns) in [ + (r#"{"sampling": 0}"#, 10, false), + (r#"{"sampling": -3}"#, 10, false), + (r#"{"sampling": 1}"#, 1, false), + (r#"{"sampling": 100}"#, 100, false), + (r#"{"sampling": 101}"#, 100, true), + (r#"{"sampling": 4294967296}"#, 100, true), + ] { + let (config, warned) = burst_ping_config(ping); + assert_eq!(config.sampling, sampling, "{ping}"); + assert_eq!(warned.len(), usize::from(warns), "{ping}"); + } + for (ping, timeout, warns) in [ + (r#"{"timeout": "0s"}"#, 5, false), + (r#"{"timeout": "-1s"}"#, 5, false), + (r#"{"timeout": "60s"}"#, 60, false), + (r#"{"timeout": "5m"}"#, 60, true), + ] { + let (config, warned) = burst_ping_config(ping); + assert_eq!(config.timeout, Duration::from_secs(timeout), "{ping}"); + assert_eq!(warned.len(), usize::from(warns), "{ping}"); + } + for (ping, method) in [ + (r#"{"httpMethod": ""}"#, "HEAD"), + (r#"{"httpMethod": " "}"#, "GET"), + (r#"{"httpMethod": "get"}"#, "get"), + ] { + assert_eq!(burst_ping_config(ping).0.http_method, method, "{ping}"); + } + let (config, _) = burst_ping_config(r#"{"destination": " ", "connectivity": " "}"#); + assert_eq!(config, xray_config::BurstPingConfig::default()); +} + +/// `infra/conf/observatory.go`: "BurstObservatory requires a valid pingConfig". +#[test] +fn burst_observatory_requires_ping_config() { + for burst in [ + "{}", + r#"{"pingConfig": null}"#, + r#"{"subjectSelector": ["proxy-"]}"#, + ] { + assert_parse_error_path( + &raw_with_burst_observatory(burst), + "$.burstObservatory.pingConfig", + ); + } + let parsed = parse_xray_json(&raw_with_burst_observatory("null")) + .expect("a null burstObservatory is absent"); + assert!(parsed.config.burst_observatory.is_none()); +} + +#[test] +fn rejects_unknown_and_mistyped_burst_observatory_fields() { + for (burst, path) in [ + (r#"[]"#, "$.burstObservatory"), + ( + r#"{"pingConfig": {}, "probeURL": "https://probe.example/"}"#, + "$.burstObservatory.probeURL", + ), + ( + r#"{"pingConfig": {"samplingCount": 3}}"#, + "$.burstObservatory.pingConfig.samplingCount", + ), + ( + r#"{"pingConfig": {}, "subjectSelector": "proxy"}"#, + "$.burstObservatory.subjectSelector", + ), + ( + r#"{"pingConfig": {}, "subjectSelector": [1]}"#, + "$.burstObservatory.subjectSelector[0]", + ), + (r#"{"pingConfig": []}"#, "$.burstObservatory.pingConfig"), + ( + r#"{"pingConfig": {"interval": 60}}"#, + "$.burstObservatory.pingConfig.interval", + ), + ( + r#"{"pingConfig": {"interval": "soon"}}"#, + "$.burstObservatory.pingConfig.interval", + ), + ( + r#"{"pingConfig": {"interval": ""}}"#, + "$.burstObservatory.pingConfig.interval", + ), + ( + r#"{"pingConfig": {"timeout": 5}}"#, + "$.burstObservatory.pingConfig.timeout", + ), + ( + r#"{"pingConfig": {"sampling": 2.5}}"#, + "$.burstObservatory.pingConfig.sampling", + ), + ( + r#"{"pingConfig": {"sampling": "10"}}"#, + "$.burstObservatory.pingConfig.sampling", + ), + ( + r#"{"pingConfig": {"destination": 1}}"#, + "$.burstObservatory.pingConfig.destination", + ), + ( + r#"{"pingConfig": {"connectivity": false}}"#, + "$.burstObservatory.pingConfig.connectivity", + ), + ( + r#"{"pingConfig": {"httpMethod": "GE T"}}"#, + "$.burstObservatory.pingConfig.httpMethod", + ), + ] { + assert_parse_error_path(&raw_with_burst_observatory(burst), path); + } +} + +/// Xray-core registers both as the observatory feature and its strategies +/// read the first, `observatory` (`infra/conf/xray.go`, `core/xray.go` +/// `getFeature`). Both are still built, so both must be valid. +#[test] +fn observatory_wins_when_both_observatories_are_present() { + let both = |burst: &str| { + format!( + r#"{{ + "observatory": {{"subjectSelector": ["proxy-"], "probeInterval": "30s"}}, + "burstObservatory": {burst}, + "inbounds": [], + "outbounds": [{{ "tag": "direct", "protocol": "freedom" }}] + }}"# + ) + }; + + let parsed = parse_xray_json(&both( + r#"{"subjectSelector": ["proxy-"], "pingConfig": {}}"#, + )) + .expect("both observatories should parse"); + assert!(parsed.config.observatory.is_some()); + assert!(parsed.config.burst_observatory.is_some()); + let warned = parsed + .diagnostics + .iter() + .filter(|diagnostic| diagnostic.severity == DiagnosticSeverity::Warning) + .map(|diagnostic| diagnostic.path.as_deref()) + .collect::>(); + assert_eq!(warned, [Some("$.burstObservatory")]); + + assert_parse_error_path(&both("{}"), "$.burstObservatory.pingConfig"); +} + fn raw_with_observatory(observatory: &str) -> String { format!( r#"{{ diff --git a/crates/xray-core-rs/src/dns.rs b/crates/xray-core-rs/src/dns.rs index fca60a1e..991e9dad 100644 --- a/crates/xray-core-rs/src/dns.rs +++ b/crates/xray-core-rs/src/dns.rs @@ -1410,6 +1410,7 @@ mod tests { default_outbound_tag: Some("dns-out".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns, policy: PolicyConfig::default(), }) @@ -1499,6 +1500,7 @@ mod tests { domain_strategy: RoutingDomainStrategy::IpIfNonMatch, }, observatory: None, + burst_observatory: None, dns: DnsConfig { servers: vec![DnsServerConfig::Domain { domain: server_domain.to_owned(), @@ -2008,6 +2010,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -2256,6 +2259,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3075,6 +3079,7 @@ mod tests { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig { hosts: DomainHostIndex::from_iter([ ( @@ -3152,6 +3157,7 @@ mod tests { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3226,6 +3232,7 @@ mod tests { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3318,6 +3325,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3629,6 +3637,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3713,6 +3722,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); @@ -3842,6 +3852,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), }); diff --git a/crates/xray-core-rs/src/health.rs b/crates/xray-core-rs/src/health.rs index a51e9ea6..cc6e44b7 100644 --- a/crates/xray-core-rs/src/health.rs +++ b/crates/xray-core-rs/src/health.rs @@ -4,23 +4,34 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use rand::Rng; use tokio::sync::futures::Notified; use tokio::sync::{watch, Notify}; use tokio::task::JoinSet; use tokio::time::Instant; -use xray_config::{ObservatoryConfig, OBSERVATORY_PROBE_TIMEOUT}; +use xray_config::{BurstPingConfig, ObservatoryConfig, OBSERVATORY_PROBE_TIMEOUT}; use xray_transport::{DnsResolver, TransportDialer, TransportError}; use crate::outbound::{ - OutboundGraph, OutboundHealthState, OutboundNodeId, OutboundNodeKind, OutboundRouter, - OutboundSelectionOverlay, + OutboundGraph, OutboundHealthFailure, OutboundHealthState, OutboundNodeId, OutboundNodeKind, + OutboundRouter, OutboundSelectionOverlay, }; use crate::startup_probe::{ - run_outbound_url_probe, ProbeStatusPolicy, StartupProbeError, StartupProbeOptions, + run_health_probe, run_outbound_url_probe, ProbePath, ProbeRequest, ProbeStatusPolicy, + StartupProbeError, StartupProbeOptions, }; use crate::CoreError; const MAX_CONCURRENT_HEALTH_PROBES: usize = 4; +/// After the device changes network a burst observatory waits this long for +/// the new one to carry traffic before it probes its subjects again. +const BURST_NETWORK_SETTLE: Duration = Duration::from_secs(1); +/// The probes that follow a network change are spread over this much more, +/// so that they do not all leave in one radio burst. +const BURST_NETWORK_REPROBE_JITTER: Duration = Duration::from_secs(2); +/// The first wait before a burst observatory tries the network again after +/// its connectivity check failed. It doubles up to `pingConfig.interval`. +const BURST_CONNECTIVITY_BACKOFF_MIN: Duration = Duration::from_secs(5); /// How long after its last probe finished an outbound real traffic failed /// through is probed again, and how long a failed re-probe waits for the @@ -265,6 +276,374 @@ pub(crate) async fn run_observatory( } } +/// Xray's burst observatory over the probe and the health overlay the +/// classic one uses. +pub(crate) struct BurstObservatoryRuntime { + ping: Arc, + nodes: Vec, + selection: Arc, + probes: BurstProbes, + network_changes: watch::Receiver, +} + +/// What one ping needs, shared by every ping task. +#[derive(Clone)] +struct BurstProbes { + outbound_router: Arc, + destination_resolver: Arc, + bootstrap_resolver: Arc, + transport_dialer: Arc, +} + +impl BurstObservatoryRuntime { + pub(crate) fn new( + ping: BurstPingConfig, + nodes: Vec, + outbound_router: Arc, + selection: Arc, + destination_resolver: Arc, + bootstrap_resolver: Arc, + transport_dialer: Arc, + ) -> Self { + Self { + ping: Arc::new(ping), + nodes, + selection, + network_changes: transport_dialer.network_changes().observe(), + probes: BurstProbes { + outbound_router, + destination_resolver, + bootstrap_resolver, + transport_dialer, + }, + } + } +} + +/// The extra ping of every subject that opens a round. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BurstKick { + /// At once: Xray-core's one-time check when the scheduler starts. + Start, + /// Once the network the device moved to has settled. + NetworkChange, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ScheduledPing { + /// From the start of the round. + offset: Duration, + /// Index into the runtime's subjects. + subject: usize, +} + +/// One period of pings in firing order: `sampling` per subject, each at a +/// uniformly random point of the period as in `healthping.go` `doCheck`, +/// after the kick's one per subject. +fn burst_schedule( + subjects: usize, + sampling: u32, + period: Duration, + kick: Option, + rng: &mut impl Rng, +) -> Vec { + let period_nanos = u64::try_from(period.as_nanos()).unwrap_or(u64::MAX).max(1); + let per_subject = sampling as usize + usize::from(kick.is_some()); + let mut schedule = Vec::with_capacity(subjects.saturating_mul(per_subject)); + for subject in 0..subjects { + match kick { + Some(BurstKick::Start) => schedule.push(ScheduledPing { + offset: Duration::ZERO, + subject, + }), + Some(BurstKick::NetworkChange) => { + let jitter = rng.gen_range(0..=BURST_NETWORK_REPROBE_JITTER.as_millis() as u64); + schedule.push(ScheduledPing { + offset: BURST_NETWORK_SETTLE + Duration::from_millis(jitter), + subject, + }); + } + None => {} + } + for _ in 0..sampling { + schedule.push(ScheduledPing { + offset: Duration::from_nanos(rng.gen_range(0..period_nanos)), + subject, + }); + } + } + schedule.sort_by_key(|ping| ping.offset); + schedule +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PingRole { + Scheduled, + /// The one ping let through while the network is taken to be down. + Canary, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BurstSample { + Rtt(Duration), + Failed(OutboundHealthFailure), + /// The ping failed and so did the connectivity check: not a sample. + NetworkDown, +} + +/// Holds scheduled pings back while the connectivity check says the device +/// has no network, letting one through after each backoff. +#[derive(Debug, Default)] +struct ConnectivityGate { + pause: Option, +} + +#[derive(Debug)] +struct ConnectivityPause { + backoff: Duration, + next_canary: tokio::time::Instant, + canary_in_flight: bool, +} + +impl ConnectivityGate { + /// Whether a ping due at `now` is sent, and as what. + fn admit(&mut self, now: tokio::time::Instant) -> Option { + let Some(pause) = &mut self.pause else { + return Some(PingRole::Scheduled); + }; + if pause.canary_in_flight || now < pause.next_canary { + return None; + } + pause.canary_in_flight = true; + Some(PingRole::Canary) + } + + /// A ping and the connectivity check after it both failed. `longest` is + /// the longest wait between two canaries. + fn network_down(&mut self, role: PingRole, now: tokio::time::Instant, longest: Duration) { + match (&mut self.pause, role) { + (None, _) => { + let backoff = BURST_CONNECTIVITY_BACKOFF_MIN.min(longest); + self.pause = Some(ConnectivityPause { + backoff, + next_canary: now + backoff, + canary_in_flight: false, + }); + } + (Some(pause), PingRole::Canary) => { + pause.backoff = pause.backoff.saturating_mul(2).min(longest); + pause.next_canary = now + pause.backoff; + pause.canary_in_flight = false; + } + // A ping sent before the pause began says nothing new. + (Some(_), PingRole::Scheduled) => {} + } + } + + /// A ping produced a sample, so the network carries traffic. + fn network_up(&mut self) { + self.pause = None; + } + + /// The canary's task ended without a result. + fn canary_lost(&mut self) { + if let Some(pause) = &mut self.pause { + pause.canary_in_flight = false; + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BurstRoundEnd { + Shutdown, + Elapsed, + NetworkChanged, +} + +pub(crate) async fn run_burst_observatory( + mut runtime: BurstObservatoryRuntime, + mut shutdown: watch::Receiver, +) { + if runtime.nodes.is_empty() { + return; + } + + let mut gate = ConnectivityGate::default(); + let mut kick = Some(BurstKick::Start); + loop { + match run_burst_round(&mut runtime, kick.take(), &mut gate, &mut shutdown).await { + BurstRoundEnd::Shutdown => return, + BurstRoundEnd::Elapsed => {} + BurstRoundEnd::NetworkChanged => { + runtime.selection.start_health_epoch(); + gate = ConnectivityGate::default(); + kick = Some(BurstKick::NetworkChange); + } + } + } +} + +/// Runs the pings of one sampling period. Pings still pending or in flight +/// when it ends are dropped, as Xray-core cancels a round the next overtakes. +async fn run_burst_round( + runtime: &mut BurstObservatoryRuntime, + kick: Option, + gate: &mut ConnectivityGate, + shutdown: &mut watch::Receiver, +) -> BurstRoundEnd { + let period = runtime.ping.sampling_period(); + let schedule = burst_schedule( + runtime.nodes.len(), + runtime.ping.sampling, + period, + kick, + &mut rand::thread_rng(), + ); + let started = tokio::time::Instant::now(); + let deadline = started + period; + let mut tasks = JoinSet::new(); + let mut next = 0; + // The previous round's canary, if any, was dropped with its tasks. + gate.canary_lost(); + runtime + .selection + .expire_health_samples(std::time::Instant::now()); + + loop { + let due = schedule.get(next).map(|ping| started + ping.offset); + tokio::select! { + biased; + () = wait_for_shutdown(shutdown) => return BurstRoundEnd::Shutdown, + () = network_changed(&mut runtime.network_changes) => { + return BurstRoundEnd::NetworkChanged; + } + () = tokio::time::sleep_until(deadline) => return BurstRoundEnd::Elapsed, + Some(joined) = tasks.join_next(), if !tasks.is_empty() => { + let Ok((node, role, sample)) = joined else { + gate.canary_lost(); + continue; + }; + let outcome = match sample { + BurstSample::Rtt(delay) => Ok(delay), + BurstSample::Failed(failure) => Err(failure), + BurstSample::NetworkDown => { + gate.network_down( + role, + tokio::time::Instant::now(), + runtime.ping.interval, + ); + // Nothing is recorded while the network is down, so + // only time can change an outbound's statistics. + runtime.selection.expire_health_samples(std::time::Instant::now()); + continue; + } + }; + gate.network_up(); + runtime + .selection + .record_health_probe(node, outcome, unix_ms_now(), std::time::Instant::now()); + } + () = sleep_until_due(due), if due.is_some() && tasks.len() < MAX_CONCURRENT_HEALTH_PROBES => { + let subject = schedule[next].subject; + next += 1; + let Some(role) = gate.admit(tokio::time::Instant::now()) else { + continue; + }; + let node = runtime.nodes[subject]; + let probes = runtime.probes.clone(); + let ping = Arc::clone(&runtime.ping); + tasks.spawn(async move { (node, role, burst_ping(&probes, &ping, node).await) }); + } + } + } +} + +/// One ping of `node`, as `healthping.go` `doCheck` judges it: a failure +/// counts against the outbound unless the connectivity URL, requested over +/// the device's own network, fails too. +async fn burst_ping( + probes: &BurstProbes, + ping: &BurstPingConfig, + node: OutboundNodeId, +) -> BurstSample { + let outbound_tag = probes + .outbound_router + .graph() + .node(node) + .and_then(|node| node.tag()) + .map(ToOwned::to_owned); + let error = match burst_request( + probes, + ping, + &ping.destination, + outbound_tag, + ProbePath::Outbound, + ) + .await + { + Ok(delay) => return BurstSample::Rtt(delay), + Err(error) => error, + }; + if let Some(connectivity) = &ping.connectivity { + if burst_request(probes, ping, connectivity, None, ProbePath::Direct) + .await + .is_err() + { + return BurstSample::NetworkDown; + } + } + BurstSample::Failed(error.health_failure()) +} + +async fn burst_request( + probes: &BurstProbes, + ping: &BurstPingConfig, + url: &str, + outbound_tag: Option, + path: ProbePath, +) -> Result { + run_health_probe( + &probes.outbound_router, + StartupProbeOptions { + url: url.to_owned(), + timeout: ping.timeout, + outbound_tag, + }, + ProbeRequest { + method: &ping.http_method, + path, + }, + probes.destination_resolver.as_ref(), + probes.bootstrap_resolver.as_ref(), + &probes.transport_dialer, + ProbeStatusPolicy::AnyResponse, + ) + .await +} + +async fn sleep_until_due(due: Option) { + match due { + Some(due) => tokio::time::sleep_until(due).await, + None => std::future::pending().await, + } +} + +/// Resolves on the next network change, and never once nothing can announce one. +async fn network_changed(changes: &mut watch::Receiver) { + if changes.changed().await.is_err() { + std::future::pending::<()>().await; + } +} + +fn unix_ms_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u128::from(u64::MAX)) as u64 +} + +#[allow(clippy::too_many_arguments)] async fn run_sequential_round( runtime: &ObservatoryRuntime, reprobes: &mut Reprobes, @@ -774,11 +1153,7 @@ fn record_result( result: Result, kind: ProbeKind, ) { - let now_unix_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() - .min(u128::from(u64::MAX)) as u64; + let now_unix_ms = unix_ms_now(); match (result, kind) { (Ok(delay), ProbeKind::Scheduled) => { selection.record_health_success(node, delay, now_unix_ms); @@ -812,7 +1187,6 @@ mod call_site_tests; #[cfg(test)] mod tests { use super::*; - use crate::outbound::OutboundHealthFailure; use serde_json::{json, Value}; use std::sync::atomic::AtomicUsize; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -827,6 +1201,96 @@ mod tests { Duration::from_secs(secs) } + /// `healthping.go` `doCheck`: `sampling` pings per subject, each at a + /// random point of `interval * sampling`. + #[test] + fn burst_schedule_spreads_sampling_pings_per_subject_over_the_period() { + let period = Duration::from_secs(600); + let schedule = burst_schedule(3, 10, period, None, &mut rand::thread_rng()); + + assert_eq!(schedule.len(), 30); + for subject in 0..3 { + let pings = schedule.iter().filter(|ping| ping.subject == subject); + assert_eq!(pings.count(), 10, "subject {subject}"); + } + assert!(schedule.iter().all(|ping| ping.offset < period)); + assert!(schedule.is_sorted_by_key(|ping| ping.offset)); + let distinct = schedule + .iter() + .map(|ping| ping.offset) + .collect::>(); + assert!(distinct.len() > 20, "pings must not fire together"); + } + + #[test] + fn burst_schedule_opens_with_one_ping_per_subject() { + let period = Duration::from_secs(600); + + let start = burst_schedule( + 4, + 2, + period, + Some(BurstKick::Start), + &mut rand::thread_rng(), + ); + assert_eq!(start.len(), 4 * 3); + let immediate = start + .iter() + .take_while(|ping| ping.offset.is_zero()) + .map(|ping| ping.subject) + .collect::>(); + assert_eq!(immediate, [0, 1, 2, 3]); + + let moved = burst_schedule( + 4, + 0, + period, + Some(BurstKick::NetworkChange), + &mut rand::thread_rng(), + ); + assert_eq!(moved.len(), 4); + assert!(moved.iter().all(|ping| { + (BURST_NETWORK_SETTLE..=BURST_NETWORK_SETTLE + BURST_NETWORK_REPROBE_JITTER) + .contains(&ping.offset) + })); + } + + /// While the connectivity check fails only one ping per backoff leaves, + /// and the backoff never exceeds `pingConfig.interval`. + #[tokio::test(start_paused = true)] + async fn connectivity_gate_lets_one_canary_through_per_bounded_backoff() { + let interval = Duration::from_secs(15); + let mut gate = ConnectivityGate::default(); + let now = tokio::time::Instant::now(); + assert_eq!(gate.admit(now), Some(PingRole::Scheduled)); + + gate.network_down(PingRole::Scheduled, now, interval); + // A ping already in flight when the pause began changes nothing. + gate.network_down(PingRole::Scheduled, now, interval); + assert_eq!(gate.admit(now + Duration::from_secs(4)), None); + + let mut now = now + BURST_CONNECTIVITY_BACKOFF_MIN; + let mut waits = Vec::new(); + for _ in 0..4 { + assert_eq!(gate.admit(now), Some(PingRole::Canary)); + assert_eq!(gate.admit(now), None, "one canary at a time"); + gate.network_down(PingRole::Canary, now, interval); + let wait = gate.pause.as_ref().expect("still paused").backoff; + assert_eq!(gate.admit(now + wait - Duration::from_millis(1)), None); + waits.push(wait); + now += wait; + } + assert_eq!( + waits, + [10, 15, 15, 15].map(Duration::from_secs), + "doubles from 5s up to the interval" + ); + + assert_eq!(gate.admit(now), Some(PingRole::Canary)); + gate.network_up(); + assert_eq!(gate.admit(now), Some(PingRole::Scheduled)); + } + #[test] fn failure_classification_is_structured() { let error = StartupProbeError::HttpStatus { @@ -1664,6 +2128,57 @@ mod tests { .expect("the probes finish in time"); } + /// With `burstObservatory` alone nothing watches the failures of real + /// traffic: a failed open is dropped where it is reported and brings no + /// re-probe. A re-probe's result recorded all the same would leave the + /// `sampling` window, and the health read from it, as the pings left + /// them. + #[test] + fn traffic_failures_bring_no_reprobe_under_the_burst_observatory() { + let router = OutboundRouter::new(Arc::new(parse(&json!({ + "outbounds": [ + {"tag": "direct", "protocol": "freedom"}, + socks("proxy-a", "127.0.0.1", 9), + ], + })))); + let selection = router.selection(); + selection.use_burst_health(crate::outbound::BurstHealthPolicy { + sampling: 4, + validity: Duration::from_secs(600), + }); + let proxy_a = router.graph().node_for_tag("proxy-a").unwrap(); + let status = || { + selection + .health_snapshot() + .outbounds + .into_iter() + .find(|outbound| outbound.outbound_tag == "proxy-a") + .expect("proxy-a has a health status") + }; + + // Two pings of the burst schedule: a success and a failure. + let at = std::time::Instant::now(); + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(20)), 1, at); + selection.record_health_probe(proxy_a, Err(OutboundHealthFailure::Timeout), 2, at); + let pinged = selection.least_load_window_of(proxy_a).unwrap(); + assert_eq!(pinged, (2, 1)); + assert_eq!(status().state, OutboundHealthState::Healthy); + assert_eq!(status().delay_ms, Some(20)); + + // A flow fails to open through it. No observatory watches the slot, + // so nothing is left pending for anyone to probe. + selection.report_dial_failure(proxy_a); + let slot = selection.leaf_index(proxy_a).unwrap(); + assert!(!selection.failure_reports().is_pending(slot)); + + selection.record_reprobe_failure(proxy_a, OutboundHealthFailure::Transport, 3); + assert_eq!(selection.least_load_window_of(proxy_a).unwrap(), pinged); + assert_eq!(status().state, OutboundHealthState::Healthy); + selection.record_reprobe_success(proxy_a, Duration::from_millis(5), 4); + assert_eq!(selection.least_load_window_of(proxy_a).unwrap(), pinged); + assert_eq!(status().delay_ms, Some(20)); + } + async fn wait_for_state( selection: &OutboundSelectionOverlay, node: OutboundNodeId, diff --git a/crates/xray-core-rs/src/lib.rs b/crates/xray-core-rs/src/lib.rs index 77165df5..541fd220 100644 --- a/crates/xray-core-rs/src/lib.rs +++ b/crates/xray-core-rs/src/lib.rs @@ -791,6 +791,17 @@ impl Core { }) { return Err(CoreError::InvalidObservatoryProbeUrl); } + if config + .burst_observatory + .as_ref() + .is_some_and(|observatory| { + std::iter::once(&observatory.ping.destination) + .chain(&observatory.ping.connectivity) + .any(|url| startup_probe::parse_probe_url(url).is_err()) + }) + { + return Err(CoreError::InvalidObservatoryProbeUrl); + } if config.dns.fake_ip.as_ref().is_some_and(|fake_ip| { fake_ip.enabled && fake_dns::FakeIpMapper::from_config( @@ -1662,6 +1673,37 @@ impl Core { .tasks .push(task); } + } else if let Some(observatory) = config.burst_observatory.clone() { + // With both observatories Xray-core's strategies read the classic + // one, registered first; only without it does the burst one run. + let selection = outbound_router.selection_handle(); + selection.use_burst_health(outbound::BurstHealthPolicy { + sampling: observatory.ping.sampling as usize, + validity: observatory.ping.sample_validity(), + }); + let nodes = outbound_router + .graph() + .leaf_nodes_matching_prefixes(&observatory.subject_selectors); + if !nodes.is_empty() { + let runtime = health::BurstObservatoryRuntime::new( + observatory.ping, + nodes, + Arc::clone(&outbound_router), + selection, + Arc::clone(&runtime_dns_resolvers.destination), + Arc::clone(&runtime_dns_resolvers.bootstrap), + Arc::clone(&self.transport_dialer), + ); + let task = tokio::spawn(health::run_burst_observatory( + runtime, + self.shutdown.subscribe(), + )); + self.runtime + .as_mut() + .expect("running core retains runtime state") + .tasks + .push(task); + } } Ok(()) diff --git a/crates/xray-core-rs/src/outbound.rs b/crates/xray-core-rs/src/outbound.rs index 0200e682..5944fc75 100644 --- a/crates/xray-core-rs/src/outbound.rs +++ b/crates/xray-core-rs/src/outbound.rs @@ -58,7 +58,7 @@ use std::pin::Pin; use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, RwLock}; use std::task::{Context, Poll}; -use std::time::Duration; +use std::time::{Duration, Instant}; use async_trait::async_trait; use rand::Rng; @@ -101,7 +101,14 @@ const VISION_UDP443_FLOW: &str = "xtls-rprx-vision-udp443"; const DNS_OUTBOUND_HARD_OPERATION_TIMEOUT: Duration = Duration::from_secs(5); const LEAST_LOAD_HEALTH_WINDOW: usize = 16; const COST_MILLIONTHS_ONE: u64 = 1_000_000; -const LEAST_LOAD_RTT_BITS: u32 = 27; +/// Bits of each sample count in the packed window metrics. A burst +/// observatory's `sampling` is bounded by `MAX_BURST_OBSERVATORY_SAMPLING`, +/// which fits. +const LEAST_LOAD_COUNT_BITS: u32 = 8; +const LEAST_LOAD_COUNT_MAX: u64 = (1 << LEAST_LOAD_COUNT_BITS) - 1; +/// Bits of the average and of the deviation, in milliseconds: over four +/// hours, where a probe is bounded by a minute. +const LEAST_LOAD_RTT_BITS: u32 = 24; const LEAST_LOAD_RTT_MAX: u64 = (1 << LEAST_LOAD_RTT_BITS) - 1; static NEXT_DNS_OUTBOUND_RUNTIME_IDENTITY: AtomicU64 = AtomicU64::new(1); static NEXT_OUTBOUND_GRAPH_RUNTIME_IDENTITY: AtomicU64 = AtomicU64::new(1); @@ -841,6 +848,23 @@ impl FreedomOutbound { }) } + /// Freedom with no settings: the device's own network, protected from + /// the tunnel like every other outbound socket. + pub(crate) fn direct() -> Self { + Self { + fragment: None, + happy_eyeballs: None, + socket_options: None, + domain_strategy: DomainStrategy::default(), + redirect: None, + user_level: 0, + proxy_protocol: None, + final_rules: None, + noises: None, + udp_masks: None, + } + } + /// UDP reads neither the fragment mask nor Happy Eyeballs. fn for_udp( settings: &FreedomOutboundSettings, @@ -2188,39 +2212,64 @@ struct OutboundHealthAtomicState { history: Mutex, } -#[derive(Debug)] +/// How a burst observatory's samples become an outbound's health, as +/// `app/observatory/burst/healthping_result.go` computes it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct BurstHealthPolicy { + /// Samples kept per outbound: `pingConfig.sampling`. + pub(crate) sampling: usize, + /// A sample older than this no longer counts. + pub(crate) validity: Duration, +} + +#[derive(Debug, Clone, Copy)] +struct OutboundHealthSample { + /// `None` is a failed probe. + delay_ms: Option, + at: Instant, +} + +/// The latest probe outcomes of one outbound, oldest overwritten first. +#[derive(Debug, Default)] struct OutboundHealthWindow { - samples: [Option; LEAST_LOAD_HEALTH_WINDOW], + samples: Vec, next: usize, - len: usize, + /// The network epoch the samples were taken in. + epoch: u64, } -impl Default for OutboundHealthWindow { - fn default() -> Self { - Self { - samples: [None; LEAST_LOAD_HEALTH_WINDOW], - next: 0, - len: 0, +impl OutboundHealthWindow { + fn record(&mut self, sample: OutboundHealthSample, capacity: usize, epoch: u64) { + if self.epoch != epoch { + // Samples of the network the device has left describe another path. + self.samples.clear(); + self.next = 0; + self.epoch = epoch; + } + match self.samples.get_mut(self.next) { + Some(slot) => *slot = sample, + None => self.samples.push(sample), } + self.next = (self.next + 1) % capacity.max(1); } -} - -impl OutboundHealthWindow { - fn record(&mut self, delay_ms: Option) -> OutboundHealthWindowMetrics { - self.samples[self.next] = delay_ms; - self.next = (self.next + 1) % LEAST_LOAD_HEALTH_WINDOW; - self.len = (self.len + 1).min(LEAST_LOAD_HEALTH_WINDOW); - let samples = &self.samples[..self.len]; - let successes = samples - .iter() - .filter_map(|sample| *sample) + fn metrics( + &self, + burst: Option, + now: Instant, + ) -> OutboundHealthWindowMetrics { + let valid = self.samples.iter().filter(|sample| { + burst.is_none_or(|burst| now.saturating_duration_since(sample.at) <= burst.validity) + }); + let sample_count = valid.clone().count() as u64; + let successes = valid + .filter_map(|sample| sample.delay_ms) .collect::>(); let success_count = successes.len() as u64; - let failure_count = self.len as u64 - success_count; + let failure_count = sample_count - success_count; if successes.is_empty() { return OutboundHealthWindowMetrics { - sample_count: self.len as u64, + sample_count, failure_count, average_ms: u64::MAX, deviation_ms: u64::MAX, @@ -2230,21 +2279,29 @@ impl OutboundHealthWindow { .iter() .fold(0u128, |sum, sample| sum + u128::from(*sample)); let average = sum / u128::from(success_count); - let variance = successes.iter().fold(0u128, |sum, sample| { - let sample = u128::from(*sample); - let difference = sample.abs_diff(average); - sum.saturating_add(difference.saturating_mul(difference)) - }) / u128::from(success_count); + let deviation = if burst.is_some() && success_count < 2 { + // Xray-core's burst statistics take half the average for the + // deviation of a single sample, or a node pinged once would + // always rank before one pinged twice. + average / 2 + } else { + let variance = successes.iter().fold(0u128, |sum, sample| { + let sample = u128::from(*sample); + let difference = sample.abs_diff(average); + sum.saturating_add(difference.saturating_mul(difference)) + }) / u128::from(success_count); + variance.isqrt() + }; OutboundHealthWindowMetrics { - sample_count: self.len as u64, + sample_count, failure_count, average_ms: u64::try_from(average).unwrap_or(u64::MAX), - deviation_ms: u64::try_from(variance.isqrt()).unwrap_or(u64::MAX), + deviation_ms: u64::try_from(deviation).unwrap_or(u64::MAX), } } } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] struct OutboundHealthWindowMetrics { sample_count: u64, failure_count: u64, @@ -2256,20 +2313,41 @@ impl OutboundHealthWindowMetrics { fn encode(self) -> u64 { let average = self.average_ms.min(LEAST_LOAD_RTT_MAX); let deviation = self.deviation_ms.min(LEAST_LOAD_RTT_MAX); - self.sample_count.min(31) - | (self.failure_count.min(31) << 5) - | (average << 10) - | (deviation << (10 + LEAST_LOAD_RTT_BITS)) + self.sample_count.min(LEAST_LOAD_COUNT_MAX) + | (self.failure_count.min(LEAST_LOAD_COUNT_MAX) << LEAST_LOAD_COUNT_BITS) + | (average << (2 * LEAST_LOAD_COUNT_BITS)) + | (deviation << (2 * LEAST_LOAD_COUNT_BITS + LEAST_LOAD_RTT_BITS)) } fn decode(value: u64) -> Self { Self { - sample_count: value & 31, - failure_count: (value >> 5) & 31, - average_ms: (value >> 10) & LEAST_LOAD_RTT_MAX, - deviation_ms: (value >> (10 + LEAST_LOAD_RTT_BITS)) & LEAST_LOAD_RTT_MAX, + sample_count: value & LEAST_LOAD_COUNT_MAX, + failure_count: (value >> LEAST_LOAD_COUNT_BITS) & LEAST_LOAD_COUNT_MAX, + average_ms: (value >> (2 * LEAST_LOAD_COUNT_BITS)) & LEAST_LOAD_RTT_MAX, + deviation_ms: (value >> (2 * LEAST_LOAD_COUNT_BITS + LEAST_LOAD_RTT_BITS)) + & LEAST_LOAD_RTT_MAX, } } + + fn has_success(self) -> bool { + self.failure_count < self.sample_count + } +} + +impl OutboundHealthAtomicState { + /// Burst health: alive while the window holds a success, with the + /// window's average as the delay (`burstobserver.go` `createResult`). + fn store_window_health(&self, metrics: OutboundHealthWindowMetrics) { + self.least_load_metrics + .store(metrics.encode(), Ordering::Release); + let (state, delay_ms) = if metrics.has_success() { + (OutboundHealthState::HEALTHY, metrics.average_ms) + } else { + (OutboundHealthState::UNHEALTHY, u64::MAX) + }; + self.delay_ms.store(delay_ms, Ordering::Release); + self.state.store(state, Ordering::Release); + } } impl Default for OutboundHealthAtomicState { @@ -2296,18 +2374,6 @@ enum HealthSample { StateOnly, } -impl OutboundHealthAtomicState { - fn record_sample(&self, delay_ms: Option) { - let metrics = self - .history - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .record(delay_ms); - self.least_load_metrics - .store(metrics.encode(), Ordering::Release); - } -} - /// Small mutable layer over an immutable outbound graph. /// /// Candidate membership never changes. An override is one release-store and @@ -2320,6 +2386,11 @@ pub struct OutboundSelectionOverlay { health: Box<[OutboundHealthAtomicState]>, /// Failures of real traffic, from the flows to the observatory. failure_reports: crate::health::FailureReports, + /// Set once, before a burst observatory records its first sample. + burst_health: OnceLock, + /// Advanced when the device changes network. A window drops the samples + /// of an earlier epoch when it records the first one of the current. + health_epoch: AtomicU64, revision: AtomicU64, update_lock: Mutex<()>, } @@ -2343,6 +2414,8 @@ impl OutboundSelectionOverlay { groups, health, failure_reports, + burst_health: OnceLock::new(), + health_epoch: AtomicU64::new(0), revision: AtomicU64::new(0), update_lock: Mutex::new(()), } @@ -2456,26 +2529,40 @@ impl OutboundSelectionOverlay { } } + /// Makes every later probe outcome count as a burst observatory's sample: + /// an outbound is alive while its window holds a success, and its delay + /// is the window's average. The first policy set stays. + pub(crate) fn use_burst_health(&self, policy: BurstHealthPolicy) { + let _ = self.burst_health.set(policy); + } + + /// The device changed network: samples taken so far describe another + /// path. They keep driving selection until an outbound is probed again, + /// and that probe's sample replaces them. + pub(crate) fn start_health_epoch(&self) { + self.health_epoch.fetch_add(1, Ordering::AcqRel); + } + /// Records a successful probe of the scheduled round: in the health - /// state, and as a sample of the `leastLoad` window. + /// state, and as a sample of the window. pub(crate) fn record_health_success( &self, node: OutboundNodeId, delay: Duration, now_unix_ms: u64, ) { - self.store_health_success(node, delay, now_unix_ms, HealthSample::Window); + self.record_health_probe(node, Ok(delay), now_unix_ms, Instant::now()); } /// Records a failed probe of the scheduled round: in the health state, - /// and as a sample of the `leastLoad` window. + /// and as a sample of the window. pub(crate) fn record_health_failure( &self, node: OutboundNodeId, failure: OutboundHealthFailure, now_unix_ms: u64, ) { - self.store_health_failure(node, failure, now_unix_ms, HealthSample::Window); + self.record_health_probe(node, Err(failure), now_unix_ms, Instant::now()); } /// Records a successful probe outside the scheduled round, as one run @@ -2488,7 +2575,13 @@ impl OutboundSelectionOverlay { delay: Duration, now_unix_ms: u64, ) { - self.store_health_success(node, delay, now_unix_ms, HealthSample::StateOnly); + self.store_health_probe( + node, + Ok(delay), + now_unix_ms, + Instant::now(), + HealthSample::StateOnly, + ); } /// Records a failed probe outside the scheduled round, leaving the @@ -2499,14 +2592,33 @@ impl OutboundSelectionOverlay { failure: OutboundHealthFailure, now_unix_ms: u64, ) { - self.store_health_failure(node, failure, now_unix_ms, HealthSample::StateOnly); + self.store_health_probe( + node, + Err(failure), + now_unix_ms, + Instant::now(), + HealthSample::StateOnly, + ); } - fn store_health_success( + /// Records one probe outcome taken at `at`, which orders burst samples + /// and ages them out, as a sample of the window. + pub(crate) fn record_health_probe( &self, node: OutboundNodeId, - delay: Duration, + outcome: Result, + now_unix_ms: u64, + at: Instant, + ) { + self.store_health_probe(node, outcome, now_unix_ms, at, HealthSample::Window); + } + + fn store_health_probe( + &self, + node: OutboundNodeId, + outcome: Result, now_unix_ms: u64, + at: Instant, sample: HealthSample, ) { let Some(health) = self.health_state(node) else { @@ -2516,56 +2628,99 @@ impl OutboundSelectionOverlay { .update_lock .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let delay_ms = delay.as_millis().min(u128::from(u64::MAX)) as u64; - health.delay_ms.store(delay_ms, Ordering::Release); - if sample == HealthSample::Window { - health.record_sample(Some(delay_ms)); - } + let burst = self.burst_health.get().copied(); + let delay_ms = outcome + .ok() + .map(|delay| delay.as_millis().min(u128::from(u64::MAX)) as u64); + // Only a sample enters the window and changes its metrics. + let metrics = (sample == HealthSample::Window).then(|| { + let mut history = health + .history + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + history.record( + OutboundHealthSample { delay_ms, at }, + burst.map_or(LEAST_LOAD_HEALTH_WINDOW, |burst| burst.sampling), + self.health_epoch.load(Ordering::Acquire), + ); + history.metrics(burst, at) + }); health .last_try_unix_ms .store(now_unix_ms, Ordering::Release); - health - .last_seen_unix_ms - .store(now_unix_ms, Ordering::Release); - health.consecutive_failures.store(0, Ordering::Release); - health - .last_failure - .store(OutboundHealthFailure::NONE, Ordering::Release); - health - .state - .store(OutboundHealthState::HEALTHY, Ordering::Release); + match outcome { + Ok(_) => { + health + .last_seen_unix_ms + .store(now_unix_ms, Ordering::Release); + health.consecutive_failures.store(0, Ordering::Release); + health + .last_failure + .store(OutboundHealthFailure::NONE, Ordering::Release); + } + Err(failure) => { + health.consecutive_failures.fetch_add(1, Ordering::AcqRel); + health + .last_failure + .store(failure.encode(), Ordering::Release); + } + } + match (burst, metrics) { + // A burst observatory's health is what its window says. + (Some(_), Some(metrics)) => health.store_window_health(metrics), + // No re-probe runs beside a burst observatory, and a probe that + // is no sample says nothing about its window. + (Some(_), None) => {} + (None, metrics) => { + if let Some(metrics) = metrics { + health + .least_load_metrics + .store(metrics.encode(), Ordering::Release); + } + health + .delay_ms + .store(delay_ms.unwrap_or(u64::MAX), Ordering::Release); + let state = if delay_ms.is_some() { + OutboundHealthState::HEALTHY + } else { + OutboundHealthState::UNHEALTHY + }; + health.state.store(state, Ordering::Release); + } + } self.revision.fetch_add(1, Ordering::AcqRel); } - fn store_health_failure( - &self, - node: OutboundNodeId, - failure: OutboundHealthFailure, - now_unix_ms: u64, - sample: HealthSample, - ) { - let Some(health) = self.health_state(node) else { + /// Ages burst samples out as of `now`. An outbound whose samples have all + /// expired is no longer alive, as in Xray-core, until a ping succeeds. + pub(crate) fn expire_health_samples(&self, now: Instant) { + let Some(burst) = self.burst_health.get().copied() else { return; }; let _update = self .update_lock .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - if sample == HealthSample::Window { - health.record_sample(None); + let mut changed = false; + for health in &self.health { + let metrics = { + let history = health + .history + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if history.samples.is_empty() { + continue; + } + history.metrics(Some(burst), now) + }; + if metrics.encode() != health.least_load_metrics.load(Ordering::Acquire) { + health.store_window_health(metrics); + changed = true; + } + } + if changed { + self.revision.fetch_add(1, Ordering::AcqRel); } - health.delay_ms.store(u64::MAX, Ordering::Release); - health - .last_try_unix_ms - .store(now_unix_ms, Ordering::Release); - health.consecutive_failures.fetch_add(1, Ordering::AcqRel); - health - .last_failure - .store(failure.encode(), Ordering::Release); - health - .state - .store(OutboundHealthState::UNHEALTHY, Ordering::Release); - self.revision.fetch_add(1, Ordering::AcqRel); } /// The balancer's pick, its `fallbackTag` when the strategy picks no @@ -5733,6 +5888,7 @@ mod tests { ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -8186,6 +8342,207 @@ mod tests { assert_eq!(selected.tag.as_deref(), Some("proxy-b")); } + fn burst_selector_router( + strategy: RoutingBalancerStrategy, + sampling: usize, + validity: Duration, + ) -> (OutboundRouter, OutboundNodeId, OutboundNodeId) { + let graph = Arc::new(OutboundGraph::new(Arc::new(selector_group_config( + strategy, + )))); + let proxy_a = graph.node_for_tag("proxy-a").unwrap(); + let proxy_b = graph.node_for_tag("proxy-b").unwrap(); + let router = OutboundRouter::from_factory(Arc::new(OutboundFactory::new(graph))); + router + .selection() + .use_burst_health(BurstHealthPolicy { sampling, validity }); + (router, proxy_a, proxy_b) + } + + fn selected_tag(router: &OutboundRouter) -> Option { + router + .select_tcp_outbound_for_session_with_tag( + &xray_config::RouteContext::default(), + &domain_tcp_target("example.test"), + true, + ) + .unwrap() + .tag + } + + fn health_of(router: &OutboundRouter, tag: &str) -> OutboundHealthStatusSnapshot { + router + .selection() + .health_snapshot() + .outbounds + .into_iter() + .find(|status| status.outbound_tag == tag) + .unwrap_or_else(|| panic!("no health status for {tag}")) + } + + /// `healthping_result.go`: an outbound is alive while its window of + /// `sampling` pings holds one success, and its delay is their average. + #[test] + fn burst_health_is_alive_while_the_sampling_window_holds_a_success() { + let (router, proxy_a, _) = burst_selector_router( + RoutingBalancerStrategy::LeastPing, + 3, + Duration::from_secs(600), + ); + let selection = router.selection(); + let start = Instant::now(); + + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(40)), 1_000, start); + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(80)), 2_000, start); + selection.record_health_probe(proxy_a, Err(OutboundHealthFailure::Timeout), 3_000, start); + let status = health_of(&router, "proxy-a"); + assert_eq!(status.state, OutboundHealthState::Healthy); + assert_eq!(status.delay_ms, Some(60)); + assert_eq!(status.last_failure, Some(OutboundHealthFailure::Timeout)); + + // Two more failures push both successes out of the window of three. + for unix_ms in [4_000, 5_000] { + selection.record_health_probe( + proxy_a, + Err(OutboundHealthFailure::Timeout), + unix_ms, + start, + ); + } + assert_eq!( + health_of(&router, "proxy-a").state, + OutboundHealthState::Unhealthy + ); + + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(20)), 6_000, start); + let status = health_of(&router, "proxy-a"); + assert_eq!(status.state, OutboundHealthState::Healthy); + assert_eq!(status.delay_ms, Some(20)); + } + + /// `healthping_result.go` `getStatistics` skips a sample older than the + /// validity, and `burstobserver.go` reports `All == Fail` as not alive. + #[test] + fn burst_samples_expire_after_their_validity() { + let validity = Duration::from_secs(120); + let (router, proxy_a, proxy_b) = + burst_selector_router(RoutingBalancerStrategy::LeastPing, 10, validity); + let selection = router.selection(); + let start = Instant::now(); + + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(10)), 1_000, start); + selection.record_health_probe( + proxy_b, + Ok(Duration::from_millis(90)), + 2_000, + start + Duration::from_secs(100), + ); + selection.expire_health_samples(start + validity); + assert_eq!(selected_tag(&router).as_deref(), Some("proxy-a")); + + selection.expire_health_samples(start + validity + Duration::from_secs(1)); + assert_eq!( + health_of(&router, "proxy-a").state, + OutboundHealthState::Unhealthy + ); + assert_eq!(selected_tag(&router).as_deref(), Some("proxy-b")); + } + + /// leastLoad reads the burst statistics: deviation, then average, over + /// the last `sampling` pings rather than a fixed sixteen. + #[test] + fn least_load_ranks_by_burst_statistics_of_the_sampling_window() { + let (router, proxy_a, proxy_b) = burst_selector_router( + RoutingBalancerStrategy::LeastLoad(RoutingLeastLoadSettings::default()), + 3, + Duration::from_secs(600), + ); + let selection = router.selection(); + let start = Instant::now(); + + for delay_ms in [10, 50, 30] { + selection.record_health_probe( + proxy_a, + Ok(Duration::from_millis(delay_ms)), + 1_000, + start, + ); + } + for _ in 0..3 { + selection.record_health_probe(proxy_b, Ok(Duration::from_millis(100)), 1_000, start); + } + assert_eq!( + selected_tag(&router).as_deref(), + Some("proxy-b"), + "the steadier outbound wins over the faster one" + ); + + // Three steady pings replace the whole window of three: equal + // deviation now, so the lower average decides. + for _ in 0..3 { + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(20)), 2_000, start); + } + assert_eq!(selected_tag(&router).as_deref(), Some("proxy-a")); + } + + /// With one success Xray-core takes half the average for the deviation, + /// so an outbound pinged once does not outrank a steadier one. + #[test] + fn burst_deviation_of_a_single_sample_is_half_its_average() { + let (router, proxy_a, proxy_b) = burst_selector_router( + RoutingBalancerStrategy::LeastLoad(RoutingLeastLoadSettings::default()), + 10, + Duration::from_secs(600), + ); + let selection = router.selection(); + let start = Instant::now(); + + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(40)), 1_000, start); + for delay_ms in [100, 110] { + selection.record_health_probe( + proxy_b, + Ok(Duration::from_millis(delay_ms)), + 1_000, + start, + ); + } + + assert_eq!(selected_tag(&router).as_deref(), Some("proxy-b")); + } + + /// After a network change the old network's samples keep driving + /// selection only until an outbound is pinged on the new one. + #[test] + fn burst_samples_of_the_previous_network_yield_to_the_first_new_one() { + let (router, proxy_a, proxy_b) = burst_selector_router( + RoutingBalancerStrategy::LeastPing, + 10, + Duration::from_secs(600), + ); + let selection = router.selection(); + let start = Instant::now(); + for _ in 0..5 { + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(10)), 1_000, start); + selection.record_health_probe(proxy_b, Ok(Duration::from_millis(50)), 1_000, start); + } + + selection.start_health_epoch(); + assert_eq!( + selected_tag(&router).as_deref(), + Some("proxy-a"), + "nothing better is known until the new network is probed" + ); + + selection.record_health_probe(proxy_a, Ok(Duration::from_millis(300)), 2_000, start); + let status = health_of(&router, "proxy-a"); + assert_eq!( + status.delay_ms, + Some(300), + "old samples are not averaged in" + ); + assert_eq!(selected_tag(&router).as_deref(), Some("proxy-b")); + } + #[test] fn least_load_distributes_only_across_the_bounded_top_n() { let settings = RoutingLeastLoadSettings { diff --git a/crates/xray-core-rs/src/policy.rs b/crates/xray-core-rs/src/policy.rs index 4ee73fb6..e32d02a7 100644 --- a/crates/xray-core-rs/src/policy.rs +++ b/crates/xray-core-rs/src/policy.rs @@ -478,6 +478,7 @@ mod tests { default_outbound_tag: Some("direct".to_owned()), routing: Default::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: PolicyConfig { levels: BTreeMap::from([(level, policy)]), diff --git a/crates/xray-core-rs/src/startup_probe.rs b/crates/xray-core-rs/src/startup_probe.rs index b5e0044a..a125634c 100644 --- a/crates/xray-core-rs/src/startup_probe.rs +++ b/crates/xray-core-rs/src/startup_probe.rs @@ -7,7 +7,8 @@ use xray_transport::stream::{apply_masquerade, serialize_request, HeaderMap}; use xray_transport::{DnsResolver, TlsClientConfig, TlsConnector, TransportDialer}; use crate::outbound::{ - open_tcp_stream_with_resolvers_and_dialer, OutboundGraph, OutboundHealthFailure, + open_tcp_stream_with_resolvers_and_dialer, FreedomOutbound, OutboundGraph, + OutboundHealthFailure, TcpOutbound, }; use crate::{CoreError, OutboundRouter}; @@ -33,6 +34,32 @@ pub(crate) enum ProbeStatusPolicy { Success, } +/// What a probe sends and which way, where Xray-core's observers differ. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ProbeRequest<'a> { + /// Request method, written as it is. + pub(crate) method: &'a str, + pub(crate) path: ProbePath, +} + +impl Default for ProbeRequest<'_> { + fn default() -> Self { + Self { + method: "GET", + path: ProbePath::Outbound, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProbePath { + /// Through the outbound the probe options name. + Outbound, + /// Over the device's own network, through no configured outbound: the + /// burst observatory's connectivity check. + Direct, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct StartupProbeOptions { pub url: String, @@ -212,6 +239,28 @@ pub(crate) async fn run_outbound_url_probe( bootstrap_resolver: &dyn DnsResolver, transport_dialer: &TransportDialer, status_policy: ProbeStatusPolicy, +) -> Result { + run_health_probe( + outbound_router, + options, + ProbeRequest::default(), + destination_resolver, + bootstrap_resolver, + transport_dialer, + status_policy, + ) + .await +} + +/// One bounded URL probe with the request an observatory asks for. +pub(crate) async fn run_health_probe( + outbound_router: &OutboundRouter, + options: StartupProbeOptions, + request: ProbeRequest<'_>, + destination_resolver: &dyn DnsResolver, + bootstrap_resolver: &dyn DnsResolver, + transport_dialer: &TransportDialer, + status_policy: ProbeStatusPolicy, ) -> Result { let timeout_ms = options.timeout.as_millis(); let url = diagnostic_probe_url(&options.url); @@ -220,6 +269,7 @@ pub(crate) async fn run_outbound_url_probe( run_startup_probe_inner( outbound_router, &options, + request, destination_resolver, bootstrap_resolver, transport_dialer, @@ -237,9 +287,11 @@ pub(crate) fn diagnostic_probe_url(raw: &str) -> String { .unwrap_or_else(|_| "".to_owned()) } +#[allow(clippy::too_many_arguments)] async fn run_startup_probe_inner( outbound_router: &OutboundRouter, options: &StartupProbeOptions, + request: ProbeRequest<'_>, destination_resolver: &dyn DnsResolver, bootstrap_resolver: &dyn DnsResolver, transport_dialer: &TransportDialer, @@ -250,12 +302,15 @@ async fn run_startup_probe_inner( let parsed = parse_probe_url(&options.url)?; let url = parsed.diagnostic_label(); let step_timeout = options.timeout; - let outbound = outbound_router - .select_tcp_outbound_direct(options.outbound_tag.as_deref()) - .map_err(|source| StartupProbeError::Core { - url: url.clone(), - source: Box::new(source), - })?; + let outbound = match request.path { + ProbePath::Outbound => outbound_router + .select_tcp_outbound_direct(options.outbound_tag.as_deref()) + .map_err(|source| StartupProbeError::Core { + url: url.clone(), + source: Box::new(source), + })?, + ProbePath::Direct => TcpOutbound::Freedom(FreedomOutbound::direct()), + }; let target = Target::new( probe_target_addr(&parsed.host), parsed.port, @@ -319,7 +374,7 @@ async fn run_startup_probe_inner( })?; } - let request = probe_request(&parsed); + let request = probe_request(&parsed, request.method); timeout(step_timeout, stream.write_all(&request)) .await .map_err(|_| StartupProbeError::Timeout { @@ -362,11 +417,11 @@ async fn run_startup_probe_inner( /// then writes `Host`, `User-Agent`, the sorted header map and finally the /// transport's own `Accept-Encoding: gzip` (`Transport.DisableCompression` is /// unset and the persona sets no `Accept-Encoding`). -fn probe_request(parsed: &ParsedProbeUrl) -> Vec { +fn probe_request(parsed: &ParsedProbeUrl, method: &str) -> Vec { let mut headers = HeaderMap::new(); apply_masquerade(&mut headers, "nav"); let mut request = serialize_request( - "GET", + method, &parsed.path_and_query, &host_header_value(parsed), &headers, @@ -866,6 +921,7 @@ mod https_tests { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -877,7 +933,7 @@ mod https_tests { #[test] fn probe_request_carries_xray_navigation_persona_in_go_order() { let parsed = parse_probe_url("http://probe.test:8080/generate_204?x=1").unwrap(); - let request = String::from_utf8(probe_request(&parsed)).unwrap(); + let request = String::from_utf8(probe_request(&parsed, "GET")).unwrap(); assert!(!request.to_ascii_lowercase().contains("xray"), "{request}"); assert!(request.ends_with("\r\n\r\n"), "{request}"); @@ -1008,6 +1064,7 @@ mod https_tests { run_startup_probe_inner( &outbound_router, &options, + ProbeRequest::default(), &resolver, &resolver, &transport_dialer, diff --git a/crates/xray-core-rs/tests/core_lifecycle_tests.rs b/crates/xray-core-rs/tests/core_lifecycle_tests.rs index 9433371f..6561df15 100644 --- a/crates/xray-core-rs/tests/core_lifecycle_tests.rs +++ b/crates/xray-core-rs/tests/core_lifecycle_tests.rs @@ -67,6 +67,7 @@ fn runtime_config() -> CoreConfig { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } diff --git a/crates/xray-core-rs/tests/health_observatory_tests.rs b/crates/xray-core-rs/tests/health_observatory_tests.rs index e0ecb1af..1f7855df 100644 --- a/crates/xray-core-rs/tests/health_observatory_tests.rs +++ b/crates/xray-core-rs/tests/health_observatory_tests.rs @@ -3,8 +3,9 @@ use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; use xray_config::{ - CoreConfig, InboundConfig, InboundProtocol, Network, ObservatoryConfig, OutboundConfig, - OutboundSettings, RoutingConfig, StreamSecurity, StreamSettings, StreamTransport, + BurstObservatoryConfig, BurstPingConfig, CoreConfig, InboundConfig, InboundProtocol, Network, + ObservatoryConfig, OutboundConfig, OutboundSettings, RoutingConfig, StreamSecurity, + StreamSettings, StreamTransport, }; use xray_core_rs::{Core, CoreState, OutboundHealthState}; @@ -56,6 +57,7 @@ fn observatory_config(probe_url: String) -> CoreConfig { probe_interval: Duration::from_secs(1), enable_concurrency: true, }), + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -201,3 +203,311 @@ fn invalid_observatory_url_is_rejected_before_runtime_start() { xray_core_rs::CoreError::InvalidObservatoryProbeUrl )); } + +fn burst_observatory_config(ping: BurstPingConfig) -> CoreConfig { + CoreConfig { + observatory: None, + burst_observatory: Some(BurstObservatoryConfig { + subject_selectors: vec!["proxy-".to_owned()], + ping, + }), + ..observatory_config(String::new()) + } +} + +/// A local address nothing listens on: a connection to it is refused. +async fn refused_url() -> String { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind a port to release"); + let port = listener.local_addr().expect("released address").port(); + drop(listener); + format!("http://127.0.0.1:{port}/generate_204") +} + +async fn wait_for_health(core: &Core, state: OutboundHealthState) { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let snapshot = core.outbound_health_snapshot(); + if snapshot.outbounds.len() == 2 + && snapshot + .outbounds + .iter() + .all(|status| status.state == state) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "outbounds should become {state:?}: {:?}", + core.outbound_health_snapshot() + ) + }); +} + +/// `app/observatory/burst/healthping.go`: every subject is pinged once when +/// the scheduler starts, with `pingConfig.httpMethod` (HEAD unless named) and +/// the navigation persona `ping.go` sets. +#[tokio::test] +async fn burst_observatory_pings_subjects_at_start_with_the_configured_method() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind local ping server"); + let addr = listener.local_addr().expect("local ping address"); + let server = tokio::spawn(async move { + let mut requests = Vec::new(); + for _ in 0..2 { + let (mut stream, _) = listener.accept().await.expect("accept burst ping"); + let mut request = [0u8; 2048]; + let read = stream.read(&mut request).await.expect("read burst ping"); + requests.push(String::from_utf8_lossy(&request[..read]).into_owned()); + stream + .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") + .await + .expect("write burst response"); + } + requests + }); + let mut core = Core::new(burst_observatory_config(BurstPingConfig { + destination: format!("http://127.0.0.1:{}/generate_204", addr.port()), + ..BurstPingConfig::default() + })) + .expect("build core with burst observatory"); + + core.start().await.expect("start core"); + wait_for_health(&core, OutboundHealthState::Healthy).await; + core.stop().await.expect("stop core"); + + for request in server.await.expect("ping server should finish") { + assert!( + request.starts_with("HEAD /generate_204 HTTP/1.1\r\n"), + "{request}" + ); + assert!( + request.contains("Sec-Fetch-Mode: navigate\r\n"), + "{request}" + ); + } +} + +/// With both observatories configured the classic one governs, as in +/// Xray-core, whose strategies read the one registered first: its probes +/// run, and with them the re-probes that failures of real traffic bring, +/// while the burst observatory sends no ping at all. +#[tokio::test] +async fn the_classic_observatory_governs_when_both_are_configured() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + /// Answers every request with 204 and counts the connections it took. + async fn counting_server() -> ( + std::net::SocketAddr, + Arc, + tokio::task::JoinHandle<()>, + ) { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind local server"); + let address = listener.local_addr().expect("local address"); + let connections = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&connections); + let server = tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + counted.fetch_add(1, Ordering::SeqCst); + let mut request = [0u8; 2048]; + let _ = stream.read(&mut request).await; + let _ = stream + .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") + .await; + } + }); + (address, connections, server) + } + + let (classic, classic_probes, classic_server) = counting_server().await; + let (burst, burst_pings, burst_server) = counting_server().await; + let config = CoreConfig { + burst_observatory: Some(BurstObservatoryConfig { + subject_selectors: vec!["proxy-".to_owned()], + ping: BurstPingConfig { + destination: format!("http://127.0.0.1:{}/generate_204", burst.port()), + ..BurstPingConfig::default() + }, + }), + ..observatory_config(format!("http://127.0.0.1:{}/generate_204", classic.port())) + }; + let mut core = Core::new(config).expect("build core with both observatories"); + + core.start().await.expect("start core"); + wait_for_health(&core, OutboundHealthState::Healthy).await; + // A burst observatory pings every subject the moment it starts; give + // one that had started the time to be seen. + tokio::time::sleep(Duration::from_millis(300)).await; + core.stop().await.expect("stop core"); + + assert!(classic_probes.load(Ordering::SeqCst) >= 2); + assert_eq!(burst_pings.load(Ordering::SeqCst), 0); + classic_server.abort(); + burst_server.abort(); +} + +/// `healthping.go` `doCheck`: a failed ping counts against the outbound when +/// the connectivity URL answers over the device's own network. +#[tokio::test] +async fn burst_observatory_counts_a_failed_ping_while_connectivity_answers() { + let connectivity = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind connectivity server"); + let addr = connectivity.local_addr().expect("connectivity address"); + let server = tokio::spawn(async move { + loop { + let (mut stream, _) = connectivity.accept().await.expect("accept connectivity"); + let mut request = [0u8; 2048]; + let _ = stream.read(&mut request).await; + let _ = stream + .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") + .await; + } + }); + let mut core = Core::new(burst_observatory_config(BurstPingConfig { + destination: refused_url().await, + connectivity: Some(format!("http://127.0.0.1:{}/", addr.port())), + ..BurstPingConfig::default() + })) + .expect("build core with burst observatory"); + + core.start().await.expect("start core"); + wait_for_health(&core, OutboundHealthState::Unhealthy).await; + core.stop().await.expect("stop core"); + server.abort(); +} + +/// `healthping.go` `doCheck`: when the connectivity URL fails too the network +/// is down and the ping is not a sample, so no outbound is marked dead. +#[tokio::test] +async fn burst_observatory_does_not_count_pings_while_connectivity_fails() { + let connectivity = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind connectivity server"); + let addr = connectivity.local_addr().expect("connectivity address"); + let (checked, mut checks) = tokio::sync::mpsc::unbounded_channel(); + let server = tokio::spawn(async move { + loop { + // Closing without an answer fails the check. + let (stream, _) = connectivity.accept().await.expect("accept connectivity"); + drop(stream); + let _ = checked.send(()); + } + }); + let mut core = Core::new(burst_observatory_config(BurstPingConfig { + destination: refused_url().await, + connectivity: Some(format!("http://127.0.0.1:{}/", addr.port())), + ..BurstPingConfig::default() + })) + .expect("build core with burst observatory"); + + core.start().await.expect("start core"); + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(3), checks.recv()) + .await + .expect("each failed ping should check connectivity") + .expect("connectivity server is running"); + } + // Long enough for a failure to be recorded if it were counted. + tokio::time::sleep(Duration::from_millis(200)).await; + let snapshot = core.outbound_health_snapshot(); + assert_eq!(snapshot.outbounds.len(), 2, "{snapshot:?}"); + assert!( + snapshot + .outbounds + .iter() + .all(|status| status.state == OutboundHealthState::Unknown + && status.last_failure.is_none()), + "{snapshot:?}" + ); + + core.stop().await.expect("stop core"); + server.abort(); +} + +/// xray-rust only: after the device changes network every subject is pinged +/// again within seconds instead of at its next random point of the period. +#[tokio::test] +async fn burst_observatory_pings_subjects_again_after_a_network_change() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind local ping server"); + let addr = listener.local_addr().expect("local ping address"); + let (pinged, mut pings) = tokio::sync::mpsc::unbounded_channel(); + let server = tokio::spawn(async move { + loop { + let (mut stream, _) = listener.accept().await.expect("accept burst ping"); + let mut request = [0u8; 2048]; + let _ = stream.read(&mut request).await; + let _ = stream + .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") + .await; + let _ = pinged.send(()); + } + }); + // Ten pings per outbound over a day leave the test's seconds to the + // pings a start and a network change add. + let mut core = Core::new(burst_observatory_config(BurstPingConfig { + destination: format!("http://127.0.0.1:{}/generate_204", addr.port()), + interval: Duration::from_secs(8_640), + ..BurstPingConfig::default() + })) + .expect("build core with burst observatory"); + core.start().await.expect("start core"); + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(3), pings.recv()) + .await + .expect("every subject is pinged at start") + .expect("ping server is running"); + } + + assert_eq!( + core.rebind_quic(), + 0, + "the observatory is not a connection asked to move" + ); + + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(5), pings.recv()) + .await + .expect("every subject is pinged again on the new network") + .expect("ping server is running"); + } + core.stop().await.expect("stop core"); + server.abort(); +} + +#[test] +fn invalid_burst_observatory_urls_are_rejected_before_runtime_start() { + for ping in [ + BurstPingConfig { + destination: "file:///private/config".to_owned(), + ..BurstPingConfig::default() + }, + BurstPingConfig { + connectivity: Some("ftp://example.com/".to_owned()), + ..BurstPingConfig::default() + }, + ] { + let error = match Core::new(burst_observatory_config(ping)) { + Ok(_) => panic!("invalid burst observatory URL must be rejected"), + Err(error) => error, + }; + assert!(matches!( + error, + xray_core_rs::CoreError::InvalidObservatoryProbeUrl + )); + } +} diff --git a/crates/xray-core-rs/tests/local_xray_interop_tests.rs b/crates/xray-core-rs/tests/local_xray_interop_tests.rs index fe9b2c37..ef0c6bb3 100644 --- a/crates/xray-core-rs/tests/local_xray_interop_tests.rs +++ b/crates/xray-core-rs/tests/local_xray_interop_tests.rs @@ -2130,6 +2130,7 @@ fn rust_core_config_with_transport( default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } diff --git a/crates/xray-core-rs/tests/runtime_data_path_tests.rs b/crates/xray-core-rs/tests/runtime_data_path_tests.rs index ece8bdf8..9a1ded76 100644 --- a/crates/xray-core-rs/tests/runtime_data_path_tests.rs +++ b/crates/xray-core-rs/tests/runtime_data_path_tests.rs @@ -277,6 +277,7 @@ fn config_with_outbound(outbound: OutboundConfig) -> CoreConfig { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -502,6 +503,7 @@ fn runtime_config_with_freedom_outbound() -> CoreConfig { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -549,6 +551,7 @@ fn runtime_tun_config_with_freedom_outbound() -> CoreConfig { default_outbound_tag: Some("direct".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -609,6 +612,7 @@ fn runtime_listener_config_with_dns_outbound( ..RoutingConfig::default() }, observatory: None, + burst_observatory: None, dns: DnsConfig::default(), policy: PolicyConfig::default(), } @@ -650,6 +654,7 @@ fn runtime_tun_config_with_routed_freedom_outbound(unused_proxy_port: u16) -> Co ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -823,6 +828,7 @@ fn runtime_tun_config_with_vless_server(vless_addr: SocketAddr) -> CoreConfig { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -847,6 +853,7 @@ fn runtime_socks_config_with_vless_server(vless_addr: SocketAddr) -> CoreConfig default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -900,6 +907,7 @@ fn runtime_tun_config_with_tls_vision_vless_domain_server( default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -930,6 +938,7 @@ fn runtime_tun_config_with_reality_vision_vless_server(port: u16) -> CoreConfig default_outbound_tag: Some("proxy".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -983,6 +992,7 @@ fn runtime_config_with_routed_freedom_outbound(unused_proxy_port: u16) -> CoreCo ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1027,6 +1037,7 @@ fn runtime_config_with_domain_routed_freedom_outbound(unused_proxy_port: u16) -> ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1099,6 +1110,7 @@ fn runtime_config_with_ip_routed_freedom_outbound(unused_proxy_port: u16) -> Cor ..Default::default() }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1147,6 +1159,7 @@ fn runtime_config_with_ip_if_non_match_routed_freedom_outbound( domain_strategy: RoutingDomainStrategy::IpIfNonMatch, }, observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1171,6 +1184,7 @@ fn runtime_config_with_vless_server(vless_addr: SocketAddr) -> CoreConfig { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1195,6 +1209,7 @@ fn runtime_http_config_with_vless_server(vless_addr: SocketAddr) -> CoreConfig { default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1219,6 +1234,7 @@ fn runtime_config_with_vless_domain_server(domain: &str, port: u16) -> CoreConfi default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1254,6 +1270,7 @@ fn runtime_config_with_tls_vless_domain_server( default_outbound_tag: None, routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } @@ -1387,6 +1404,7 @@ fn selects_default_outbound_tag_when_present() { default_outbound_tag: Some("proxy".to_owned()), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), }; diff --git a/crates/xray-core-rs/tests/startup_probe_tests.rs b/crates/xray-core-rs/tests/startup_probe_tests.rs index 1bb92a78..74e6c0c5 100644 --- a/crates/xray-core-rs/tests/startup_probe_tests.rs +++ b/crates/xray-core-rs/tests/startup_probe_tests.rs @@ -61,6 +61,7 @@ fn config_with_outbounds(outbounds: Vec, default: Option<&str>) default_outbound_tag: default.map(ToOwned::to_owned), routing: RoutingConfig::default(), observatory: None, + burst_observatory: None, dns: Default::default(), policy: Default::default(), } diff --git a/crates/xray-transport/src/network_change.rs b/crates/xray-transport/src/network_change.rs index 965baa6d..9cc21c9d 100644 --- a/crates/xray-transport/src/network_change.rs +++ b/crates/xray-transport/src/network_change.rs @@ -14,11 +14,22 @@ use tokio::sync::watch; /// datagrams leave from another address now; otherwise it waits a short /// while for its peer, and fails if the peer is not heard. #[derive(Clone, Debug)] -pub struct NetworkChanges(Arc>); +pub struct NetworkChanges(Arc); + +#[derive(Debug)] +struct Signals { + /// Followed by the connections that take a fresh socket. + connections: watch::Sender, + /// Followed by whoever only needs to know, and is not counted. + observers: watch::Sender, +} impl Default for NetworkChanges { fn default() -> Self { - Self(Arc::new(watch::channel(0).0)) + Self(Arc::new(Signals { + connections: watch::channel(0).0, + observers: watch::channel(0).0, + })) } } @@ -29,19 +40,27 @@ impl NetworkChanges { /// paths validated nor connections that will survive. An mKCP connection /// is counted until its driver is gone, a while after its stream. pub fn notify(&self) -> u64 { - self.0 - .send_modify(|generation| *generation = generation.wrapping_add(1)); - self.0.receiver_count() as u64 + for signal in [&self.0.connections, &self.0.observers] { + signal.send_modify(|generation| *generation = generation.wrapping_add(1)); + } + self.0.connections.receiver_count() as u64 } /// How many changes were reported so far. For whoever drops what it /// dialed before a change, where a follower keeps and moves it. pub(crate) fn generation(&self) -> u64 { - *self.0.borrow() + *self.0.connections.borrow() } pub(crate) fn follow(&self) -> watch::Receiver { - self.0.subscribe() + self.0.connections.subscribe() + } + + /// Sees every later change without being counted among the connections + /// [`NetworkChanges::notify`] reports: for a listener that moves no + /// socket, such as the burst observatory probing the new network. + pub fn observe(&self) -> watch::Receiver { + self.0.observers.subscribe() } } @@ -65,6 +84,14 @@ mod tests { drop(follower); assert_eq!(base.network_changes().notify(), 0); + let observer = derived.network_changes().observe(); + assert_eq!( + base.network_changes().notify(), + 0, + "observers move no socket" + ); + assert!(observer.has_changed().unwrap()); + let other = crate::TransportDialer::system().unwrap(); let _stranger = other.network_changes().follow(); assert_eq!(base.network_changes().notify(), 0); diff --git a/docs/config-compatibility.md b/docs/config-compatibility.md index 37c6e9c6..29f31648 100644 --- a/docs/config-compatibility.md +++ b/docs/config-compatibility.md @@ -775,6 +775,7 @@ exposes an unauthenticated proxy to the network. | `outbounds` | Supported subset below | | `routing` | Ordered `field` rules and selector-group subset below | | `observatory` | Bounded periodic HTTP(S) URL probes for tagged outbounds | +| `burstObservatory` | Xray's `pingConfig`: a window of `sampling` pings per outbound spread at random over `interval * sampling`; unused while `observatory` is present | | `dns` | Hosts, string/object servers with managed selection policy, global and per-server `queryStrategy` including `UseSystem`, and `fakeIp` subset | | `policy` | Level/system fields are parsed; runtime timeout/buffer behavior is a subset | | `log` | Accepted for input compatibility, but runtime file logging is configured through the embedding API | @@ -4083,7 +4084,11 @@ they pick among every candidate, the unhealthy ones too, as Xray-core's two strategies consult the observatory only when one is set. `leastPing` requires a successful observation and deterministically chooses the lowest delay, using lexicographic candidate order to break ties. `leastLoad` retains the latest 16 probe outcomes per outbound and orders healthy -candidates by RTT deviation, average RTT, failures, sample count, and tag. It +candidates by RTT deviation, average RTT, failures, sample count, and tag. +Under `burstObservatory` every strategy reads Xray's burst statistics instead: +the window is the latest `pingConfig.sampling` pings no older than two sampling +periods, an outbound is alive while that window holds one success, and its +delay, which `leastPing` and `maxRTT` compare, is the window's average. It accepts `expected` from 0 through 16, `maxRTT` up to the 5-second probe timeout, `tolerance` from 0 through 1, at most 16 positive duration `baselines`, and at most 64 positive literal-substring `costs`. The cost multiplier is applied to @@ -4186,6 +4191,49 @@ host timeout of 1 to 60000 ms, and returns the delay or the same typed failure category. Its result is not written to health snapshots and does not influence selector groups. +### Burst observatory + +The top-level `burstObservatory` object accepts Xray's `subjectSelector` and +`pingConfig`. `subjectSelector` is read as for `observatory`. `pingConfig` is +required, with Xray-core's error when it is absent or null, and takes: + +| Field | Meaning and default | +| --- | --- | +| `destination` | URL pinged through every subject. Trimmed; empty means `https://connectivitycheck.gstatic.com/generate_204` | +| `connectivity` | URL requested over the device's own network after a failed ping. Trimmed; empty means no check | +| `interval` | Average time between two pings of one outbound. `0` means `1m`; a shorter or negative one becomes `10s` with a warning, as in Xray-core; above `24h` becomes `24h` with a warning | +| `sampling` | Pings of one outbound per period, and the size of its window. Zero or negative means 10; above 100 becomes 100 with a warning | +| `timeout` | Bound of one ping. Zero or negative means `5s`; above `60s` becomes `60s` with a warning | +| `httpMethod` | Request method, sent as written. Absent or empty means `HEAD`; only whitespace means `GET`, as Go's `net/http` reads the empty method Xray-core's trim leaves. Anything but an HTTP token is refused | + +Durations are Go duration strings and may carry a sign; a number is refused, as +in Xray-core. Unknown fields are refused in both objects. Both URLs must be +HTTP or HTTPS URLs the startup-probe parser accepts. + +One sampling period is `interval * sampling`. When the core starts every +subject is pinged once; in each period every subject is then pinged `sampling` +times, each at a uniformly random point of the period, at most four pings at a +time. A ping is the observatory's probe with `httpMethod`: any HTTP response +is a success, whatever its status. A ping still pending when the period ends is +dropped. + +A failed ping counts against its outbound unless `connectivity` is set and +that URL fails too: then the network is taken to be down and nothing is +recorded for the outbound. xray-rust then holds the scheduled pings back and +lets one through after 5 seconds, doubling up to `interval`, until a ping +produces a sample again. A sample older than two periods no longer counts; an +outbound whose samples have all expired is not alive until a ping succeeds. + +When the host reports a network change (`rebind_quic`), xray-rust starts a new +period: every subject is pinged again 1 to 3 seconds later, and an outbound's +first sample on the new network replaces its window. Until then the old +samples keep driving selection. + +With both `observatory` and `burstObservatory` present, `observatory` drives +selection, as in Xray-core where strategies read the first registered +observatory. `burstObservatory` is still validated, raises a warning, and is +not run. + Domain matchers, read in routing rules as Xray-core's `ParseDomainRules` reads them: diff --git a/docs/config-contract.json b/docs/config-contract.json index b92476d0..3c38c5cf 100644 --- a/docs/config-contract.json +++ b/docs/config-contract.json @@ -569,6 +569,28 @@ "id": "BLACKHOLE_RESPONSE", "notes": "type is required and case-insensitive: none, http (Xray's fixed HTTP 403 reply) or custom. custom sends customResponseData, standard padded base64 of at most 65,535 bytes; absent or null sends nothing. Other types ignore it. Null, empty and unknown responses fail closed, matching Xray." }, + { + "context": "$.burstObservatory", + "fields": [ + "subjectSelector", + "pingConfig" + ], + "id": "BURST_OBSERVATORY", + "notes": "pingConfig is required, as in Xray-core. With observatory also present that one drives selection, as in Xray-core, and this one is validated and not run." + }, + { + "context": "$.burstObservatory.pingConfig", + "fields": [ + "destination", + "connectivity", + "interval", + "sampling", + "timeout", + "httpMethod" + ], + "id": "BURST_PING_CONFIG", + "notes": "Xray-core's defaults: destination https://connectivitycheck.gstatic.com/generate_204, interval 1m (a shorter nonzero one becomes 10s), sampling 10, timeout 5s, httpMethod HEAD. Bounded for phones with a warning: interval at most 24h, sampling at most 100, timeout at most 60s. httpMethod must be an HTTP token." + }, { "context": "$.dns", "fields": [ @@ -1291,6 +1313,7 @@ "outbounds", "routing", "observatory", + "burstObservatory", "dns", "policy", "reverse", diff --git a/docs/xray-core-differences.md b/docs/xray-core-differences.md index cf599863..83b45ab8 100644 --- a/docs/xray-core-differences.md +++ b/docs/xray-core-differences.md @@ -1712,6 +1712,85 @@ or to complete its handshake, and marks it unhealthy when two such probes 10 seconds apart fail, as described under [Observatory and outbound health](config-compatibility.md#observatory-and-outbound-health). +## burstObservatory + +xray-rust reads `burstObservatory` as Xray-core v26.11.9 does and feeds the +same statistics to the balancer strategies. From the reference: + +- `pingConfig` is required (`infra/conf/observatory.go` lines 29-32). Defaults + and lower bounds are `NewHealthPing`'s (`app/observatory/burst/healthping.go` + lines 40-79): destination `https://connectivitycheck.gstatic.com/generate_204`, + interval `1m` with a nonzero one below `10s` raised to `10s`, sampling 10, + timeout `5s`, method `HEAD`. +- One ping per subject at start (`healthping.go` lines 99-107), then `sampling` + pings per subject at uniformly random points of `interval * sampling` + (lines 95 and 180-186). The next period cancels what is pending (lines + 116-121). +- A failed ping is a failure sample unless the `connectivity` URL, requested + through no outbound, fails too; then nothing is recorded (lines 190-224 and + 274-286). +- An outbound keeps its latest `sampling` samples, each valid for two periods + (lines 241-248; `healthping_result.go` lines 81-124). It is alive while + `All != Fail`, its delay is the average of the successes + (`burstobserver.go` lines 44-45), and the deviation of a single success is + half of it. `leastLoad` ranks by that deviation, average, failures and count + and applies `tolerance` to `Fail / All` (`app/router/strategy_leastload.go` + lines 168-174 and 185-199); `leastPing` and `maxRTT` compare the average. +- With `observatory` also present both are registered as the observatory + feature (`infra/conf/xray.go` lines 689-703) and every strategy receives the + first, `observatory` (`core/xray.go` `getFeature` and `callbackResolution`, + lines 38-58). xray-rust selects on `observatory` too. + +Deliberate differences: + +- **Unused burst observatory.** With both present Xray-core still starts the + burst scheduler, whose results nothing reads (`burstobserver.go` lines + 68-81). xray-rust validates it, warns, and sends no ping. +- **Failures of real traffic.** `observatory` probes an outbound again within + seconds when a flow fails to open through it; `burstObservatory` does not. + Nothing follows those failures while it runs, so an outbound's window stays + its last `sampling` scheduled pings, as in `healthping_result.go`, and a + dead server is left when its pings say so. With both configured, + `observatory` governs and its re-probes apply. +- **Upper bounds.** Xray-core has none (`healthping.go` lines 66-79). + xray-rust lowers `interval` above `24h`, `sampling` above 100 and `timeout` + above `60s` to those values with a warning. They bound an outbound's window + and the pings scheduled for one period. +- **Method.** Xray-core accepts any string and, when `net/http` refuses it, + fails every ping (`ping.go` line 61). xray-rust refuses a method that is + not an HTTP token when it reads the configuration. +- **URLs.** A URL the probe cannot request (another scheme, user info, an IPv6 + literal) fails every ping in Xray-core and is refused by `Core::new` here. +- **Concurrency.** Xray-core fires every timer on its own goroutine + (`healthping.go` line 186). xray-rust runs at most four pings at once, as + its `observatory` does; a ping whose turn comes late leaves late, and one + not sent by the end of the period is dropped. +- **No network.** After a failed connectivity check Xray-core keeps sending + every scheduled ping, and a connectivity request after each (`healthping.go` + lines 190-203). xray-rust holds the scheduled pings back and lets one + through after 5 seconds, then 10, doubling up to `interval`; a ping that + produces a sample, success or counted failure, resumes the schedule. Nothing + is recorded meanwhile, as in Xray-core, and samples expire as there. +- **Network change.** Xray-core keeps balancing on samples of the network the + device left until the random schedule replaces them, up to two periods + (`healthping.go` lines 241-248). When the host reports a change through + `rebind_quic`, xray-rust starts a new period, pings every subject 1 to 3 + seconds later, and lets an outbound's first sample on the new network + replace its window. Old samples drive selection only until then. +- **Expiry.** Xray-core ages samples out when a strategy reads them + (`healthping_result.go` line 91). xray-rust does at every recorded sample + of that outbound, at the start of a period and at every failed connectivity + check, so an outbound that stopped being pinged can stay alive up to one + period longer. +- **Resolution.** Statistics are kept in milliseconds, as for `observatory`; + Xray-core compares nanoseconds. A ping stops at the status line, so a `GET` + does not time the body (`ping.go` lines 72-77). + +Not done: re-probing a dead outbound sooner than the schedule, limiting +subjects to the members of a balancer, and counting real dial failures as +samples. Each would change what a window of `sampling` pings means to +`leastLoad`. + ## XHTTP HTTP/2 connection preface Xray's XHTTP client dials HTTP/2 with a bare `golang.org/x/net/http2` diff --git a/tests/fixtures/config-tooling/cases.json b/tests/fixtures/config-tooling/cases.json index fced9668..ccf47c4f 100644 --- a/tests/fixtures/config-tooling/cases.json +++ b/tests/fixtures/config-tooling/cases.json @@ -6017,6 +6017,54 @@ "/\r\nX-Injected: 1" ] } + }, + { + "name": "burst-observatory", + "accepted": true, + "objects": { + "BURST_OBSERVATORY": "/burstObservatory", + "BURST_PING_CONFIG": "/burstObservatory/pingConfig" + }, + "config": { + "inbounds": [], + "outbounds": [ + { + "protocol": "freedom", + "tag": "direct" + } + ], + "burstObservatory": { + "subjectSelector": [ + "direct" + ], + "pingConfig": { + "destination": "https://connectivitycheck.gstatic.com/generate_204", + "connectivity": "http://connectivitycheck.platform.hicloud.com/generate_204", + "interval": "1m", + "sampling": 10, + "timeout": "5s", + "httpMethod": "HEAD" + } + } + } + }, + { + "name": "burst-observatory-without-ping-config", + "accepted": false, + "errorPath": "$.burstObservatory.pingConfig", + "base": "burst-observatory", + "set": { + "/burstObservatory/pingConfig": null + } + }, + { + "name": "burst-observatory-interval-raised", + "accepted": true, + "warningPath": "$.burstObservatory.pingConfig.interval", + "base": "burst-observatory", + "set": { + "/burstObservatory/pingConfig/interval": "2s" + } } ] }