ts_runtime/status.rs
1//! Netmap status aggregation, WhoIs lookups, and a netmap-change watcher.
2//!
3//! These surface the internal netmap state ([`ts_control::StateUpdate`], consumed by the
4//! [`PeerTracker`](crate::peer_tracker::PeerTracker)) to embedders, mirroring tsnet's
5//! `LocalClient::Status`, `WhoIs`, and `WatchIPNBus`.
6//!
7//! ## Capability / user / online surfacing (do not fabricate)
8//!
9//! tsnet's `Status`/`WhoIs` also carry per-node *online* state, the owning *user* (login/profile),
10//! and a *capability map*. Status of each in this fork:
11//! - **Capabilities** — surfaced: [`WhoIs::capabilities`] is populated from the domain
12//! [`Node`](ts_control::Node)'s `cap_map` (the control-pushed `CapMap`), which the domain model
13//! retains.
14//! - **User (login/profile)** — surfaced when the netmap provided it: [`WhoIs::user`] is the owning
15//! user's login/display name, resolved by joining the node's owning user id against the netmap's
16//! `UserProfiles` table (accumulated by the [`PeerTracker`](crate::peer_tracker::PeerTracker)
17//! across delta updates). `None` when control sent no profile for that user.
18//! - **Online state** — surfaced: [`StatusNode::online`] / [`StatusNode::last_seen`] reflect the
19//! domain [`Node`](ts_control::Node)'s retained `online`/`last_seen`, populated from the netmap
20//! node and its online deltas (`PeerChange`, `MapResponse.online_change`/`peer_seen_change`).
21//! `online` stays tri-state (`None` = unknown), never fabricated to `false`.
22
23use std::{
24 collections::BTreeMap,
25 net::{IpAddr, SocketAddr},
26};
27
28use ts_control::{Node, StableNodeId, UserId};
29
30/// A snapshot of the local netmap: this node plus every known peer.
31///
32/// Analogous to tsnet's `ipnstate.Status`. Built by [`Runtime::status`](crate::Runtime::status)
33/// from the self node held by the control runner and the peers held by the peer tracker.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Status {
36 /// This node, if a netmap has been received from control yet.
37 pub self_node: Option<StatusNode>,
38 /// Every peer currently known in the netmap.
39 pub peers: Vec<StatusNode>,
40 /// The stable id of the exit node traffic is **currently** egressing through, if any (Go's
41 /// `Status.ExitNodeStatus.ID`). This is the *resolved + fail-closed* answer from the route
42 /// updater — `None` when no exit node is configured, the configured selector matches no peer, or
43 /// the matched peer no longer advertises a default route — so it reflects what is actually
44 /// engaged, not merely what [`Config::exit_node`](ts_control::Config) requested. Find the peer's
45 /// details by matching this id against [`peers`](Status::peers).
46 pub active_exit_node: Option<StableNodeId>,
47 /// The tailnet's MagicDNS suffix (e.g. `"tail0123.ts.net"`) — Go `ipnstate.Status.MagicDNSSuffix`.
48 /// Derived (like Go's `NetworkMap.MagicDNSSuffix`) from the self node's FQDN minus its host label,
49 /// **not** from the DNS config and **not** from the tailnet `Domain` name. `None` before the first
50 /// netmap, or when the self FQDN has no tailnet component (a bare hostname).
51 pub magic_dns_suffix: Option<String>,
52}
53
54/// A single node entry in a [`Status`] snapshot.
55///
56/// Analogous to tsnet's `ipnstate.PeerStatus`.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct StatusNode {
59 /// The node's stable id (stable across re-registration).
60 pub stable_id: StableNodeId,
61 /// A display name for the node: its fqdn if a tailnet component is known, else its bare
62 /// hostname.
63 pub display_name: String,
64 /// The node's tailnet IPv4 address.
65 pub ipv4: IpAddr,
66 /// The node's tailnet IPv6 address.
67 pub ipv6: IpAddr,
68 /// Whether the node is online, if known (`ipnstate.PeerStatus.Online`). Tri-state: `Some(true)`
69 /// connected to control, `Some(false)` offline, `None` unknown (control sent no online status or
70 /// the local node lacks permission to know). Reflects control's liveness state, retained from the
71 /// netmap node + its online deltas — `None` is *unknown*, never fabricated to `false`.
72 pub online: Option<bool>,
73 /// When control last saw this node online (`ipnstate.PeerStatus.LastSeen`). Per Go, only
74 /// meaningful while the node is not currently online. `None` when unknown or never seen.
75 pub last_seen: Option<chrono::DateTime<chrono::Utc>>,
76 /// The routes this node accepts traffic for (its own `/32` and `/128`, plus any advertised
77 /// subnet routes and possibly the exit-node default route).
78 pub allowed_routes: Vec<ipnet::IpNet>,
79 /// Whether this node advertises a default route (`0.0.0.0/0` or `::/0`), making it eligible to
80 /// be selected as an exit node.
81 pub is_exit_node: bool,
82 /// The current trusted direct UDP endpoint for this peer, if a direct path is confirmed right now
83 /// (Go `ipnstate.PeerStatus.CurAddr`). `Some` ⇒ traffic to this peer flows directly to this
84 /// address; `None` ⇒ it relays via DERP (see [`relay`](Self::relay)). Mutually exclusive with a
85 /// `relay` for a routed peer, mirroring Go's empty-vs-set `CurAddr`/`Relay` strings. A live
86 /// snapshot — the direct path can expire/re-confirm between calls. Always `None` for the self node
87 /// and a whois lookup (no path to oneself; whois is an ownership query).
88 pub cur_addr: Option<SocketAddr>,
89 /// The DERP region code this peer relays through when there is **no** direct path (Go
90 /// `ipnstate.PeerStatus.Relay`, e.g. `"nyc"`). `Some` ⇔ [`cur_addr`](Self::cur_addr) is `None`
91 /// and the peer's home DERP region is known; `None` when a direct path is confirmed, or the
92 /// region code is unknown. Carries the region **code**, not its numeric id.
93 pub relay: Option<String>,
94}
95
96impl StatusNode {
97 /// Build a [`StatusNode`] from a domain [`Node`].
98 pub fn from_node(node: &Node) -> Self {
99 let is_exit_node = node
100 .accepted_routes
101 .iter()
102 .any(|route| route.prefix_len() == 0);
103
104 Self {
105 stable_id: node.stable_id.clone(),
106 display_name: node
107 .fqdn_opt(false)
108 .unwrap_or_else(|| node.hostname.clone()),
109 ipv4: node.tailnet_address.ipv4.addr().into(),
110 ipv6: node.tailnet_address.ipv6.addr().into(),
111 online: node.online,
112 last_seen: node.last_seen,
113 allowed_routes: node.accepted_routes.clone(),
114 is_exit_node,
115 // A bare `Node` carries no live path state, so connectivity is unknown here. The peer
116 // tracker overwrites these in `status_peers` by joining against the direct manager; the
117 // self node and whois lookups (which also use `from_node`) correctly keep `None`.
118 cur_addr: None,
119 relay: None,
120 }
121 }
122}
123
124/// The result of a [`Runtime::whois`](crate::Runtime::whois) lookup: the node that owns a tailnet
125/// source address, plus its user and capabilities.
126///
127/// Analogous to tsnet's `apitype.WhoIsResponse`.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct WhoIs {
130 /// The node that owns the queried source IP.
131 pub node: Node,
132 /// The login/email of the user that owns the node, if known.
133 ///
134 /// Always `None` in this fork: the domain [`Node`](ts_control::Node) does not retain the
135 /// wire-level user/login mapping (see the module-level capability/user gap note).
136 pub user: Option<String>,
137 /// The node's **node-level** capability map (Go `Node.CapMap` — node attributes like
138 /// `can-funnel`), as `(capability, args)` pairs, populated from the domain
139 /// [`Node`](ts_control::Node)'s `cap_map`, sorted by capability name. Distinct from
140 /// [`cap_map`](Self::cap_map), which is the flow-scoped *peer-capability* grants.
141 pub capabilities: Vec<(String, Vec<String>)>,
142 /// The **flow-scoped** peer-capability grants for the queried `src -> dst` flow — Go
143 /// `apitype.WhoIsResponse.CapMap` (`tailcfg.PeerCapMap`). The grants control's packet-filter
144 /// application rules authorize for traffic from this node to the queried address, keyed by
145 /// capability name with raw-JSON values. Empty when no grant matches the flow (or no scoped
146 /// query was made). Distinct from the node-level [`capabilities`](Self::capabilities).
147 pub cap_map: BTreeMap<String, Vec<String>>,
148}
149
150impl WhoIs {
151 /// Build a [`WhoIs`] from the owning node and its resolved owner login/display name (if the
152 /// netmap's `UserProfiles` table mapped the node's owning user id to a profile; `None` when
153 /// control sent no profile — e.g. a tagged node with no human owner).
154 ///
155 /// `capabilities` is the node-level cap map; `cap_map` (the flow-scoped grants) is filled
156 /// separately by [`Runtime::whois`](crate::Runtime::whois) and defaults to empty here.
157 pub(crate) fn from_node_with_user(node: Node, user: Option<String>) -> Self {
158 let capabilities = node
159 .cap_map
160 .iter()
161 .map(|(cap, args)| (cap.clone(), args.clone()))
162 .collect();
163 Self {
164 node,
165 user,
166 capabilities,
167 cap_map: BTreeMap::new(),
168 }
169 }
170}
171
172/// Resolve which node owns a tailnet source address, used by WhoIs.
173pub(crate) fn whois_addr(addr: SocketAddr) -> IpAddr {
174 addr.ip()
175}
176
177/// A measured-latency entry for one DERP region in a [`NetcheckReport`].
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct RegionLatency {
180 /// The DERP region id (Go `tailcfg.DERPRegionID`).
181 pub region_id: u32,
182 /// The measured round-trip latency to the region's closest DERP node.
183 pub latency: std::time::Duration,
184}
185
186/// A snapshot of this node's latest network conditions report — the Rust analog of Go's
187/// `netcheck.Report` as `tailscale netcheck` surfaces it.
188///
189/// ## Surfaced subset (do not fabricate)
190/// Go's `netcheck.Report` also carries UDP/IPv4/IPv6 reachability, port-mapping support
191/// (UPnP/PMP/PCP), `MappingVariesByDestIP`, global-address discovery, etc. This fork's net-report
192/// path measures only **DERP-region latency** (the data that drives home-region selection), so the
193/// report carries exactly that — the preferred (lowest-latency) region and the per-region latency
194/// map — rather than inventing fields we never probe. Empty before the first measurement.
195#[derive(Debug, Clone, PartialEq, Eq, Default, kameo::Reply)]
196pub struct NetcheckReport {
197 /// The id of the preferred DERP region — the lowest-latency region this node measured, the one it
198 /// homes to (Go `Report.PreferredDERP`). `None` before the first measurement / when no region
199 /// was reachable.
200 pub preferred_derp: Option<u32>,
201 /// Per-region measured latencies, sorted by latency ascending (Go `Report.RegionLatency`, here as
202 /// an ordered list). The first entry, when present, is the [`preferred_derp`](Self::preferred_derp)
203 /// region.
204 pub region_latencies: Vec<RegionLatency>,
205}
206
207impl NetcheckReport {
208 /// Build a report from the latest DERP-region measurements (the `RegionResult` set the latency
209 /// measurer produces). `results` is expected sorted by latency ascending (the measurer's
210 /// `RegionResult` `Ord` sorts on latency first), so the first entry is the preferred region; we
211 /// do not re-sort beyond trusting that contract for `preferred_derp`, but the list is emitted in
212 /// the order given. An empty `results` yields the default (no preferred region, empty list).
213 pub(crate) fn from_region_results(results: &[ts_netcheck::RegionResult]) -> NetcheckReport {
214 let region_latencies: Vec<RegionLatency> = results
215 .iter()
216 .map(|r| RegionLatency {
217 // `ts_derp::RegionId` is a `NonZeroU32` newtype (its `.0` is the public inner).
218 region_id: r.id.0.get(),
219 latency: r.latency,
220 })
221 .collect();
222 NetcheckReport {
223 preferred_derp: region_latencies.first().map(|r| r.region_id),
224 region_latencies,
225 }
226 }
227}
228
229/// A tailnet peer this node can send a Taildrop file *to*, plus the peerAPI base URL to reach it.
230///
231/// Analogous to tsnet's `apitype.FileTarget`. The set is produced by
232/// [`Runtime::file_targets`](crate::Runtime::file_targets) (exposed as `Device::file_targets`).
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct FileTarget {
235 /// The target peer's node record — pass straight to the Taildrop send path
236 /// (`Device::send_file`), which re-derives the same peerAPI address.
237 pub node: Node,
238 /// The `http://ip:port` base URL of the peer's peerAPI, with no trailing path — the exact shape
239 /// of Go's `apitype.FileTarget.PeerAPIURL`. Derived from
240 /// [`Node::peerapi_addr`](ts_control::Node::peerapi_addr).
241 pub peerapi_url: String,
242}
243
244/// Compute the sorted Taildrop send-target list from the peer set, given the local node's owning
245/// user id. The pure core of [`Runtime::file_targets`](crate::Runtime::file_targets) — separated out
246/// so the eligibility + ordering rules are unit-testable without spinning up the actor graph (the
247/// node-level file-sharing gate is applied by the caller before this runs).
248///
249/// A peer is a target when it advertises a reachable peerAPI (Go `PeerAPIBase(p) != ""`) **and** is
250/// either owned by `self_user_id` **or** carries the file-sharing-target capability — Go's two-way
251/// OR. Sorted by MagicDNS name (Go sorts by `Node.Name`), falling back to the bare hostname.
252pub(crate) fn build_file_targets(peers: Vec<Node>, self_user_id: UserId) -> Vec<FileTarget> {
253 let mut targets: Vec<FileTarget> = peers
254 .into_iter()
255 .filter_map(|peer| {
256 // Must advertise a reachable peerAPI (Go `PeerAPIBase(p) != ""`).
257 let addr = peer.peerapi_addr()?;
258 // Same owner OR explicitly an ACL file-sharing target (Go's two-way OR).
259 let eligible = peer.user_id == self_user_id || peer.is_file_sharing_target();
260 if !eligible {
261 return None;
262 }
263 Some(FileTarget {
264 peerapi_url: format!("http://{addr}"),
265 node: peer,
266 })
267 })
268 .collect();
269 // Sort by MagicDNS name (Go sorts by `Node.Name`), bare hostname as the fallback key.
270 targets.sort_by(|a, b| {
271 let name = |t: &FileTarget| {
272 t.node
273 .fqdn_opt(false)
274 .unwrap_or_else(|| t.node.hostname.clone())
275 };
276 name(a).cmp(&name(b))
277 });
278 targets
279}
280
281#[cfg(test)]
282mod tests {
283 use ts_control::{Node, StableNodeId, TailnetAddress};
284
285 use super::*;
286
287 fn node(stable: &str, hostname: &str, tailnet: Option<&str>, ipv4: &str) -> Node {
288 Node {
289 id: 1,
290 stable_id: StableNodeId(stable.to_string()),
291 hostname: hostname.to_string(),
292 user_id: 0,
293 tailnet: tailnet.map(str::to_string),
294 tags: vec![],
295 tailnet_address: TailnetAddress {
296 ipv4: format!("{ipv4}/32").parse().unwrap(),
297 ipv6: "fd7a::1/128".parse().unwrap(),
298 },
299 node_key: [0u8; 32].into(),
300 node_key_expiry: None,
301 online: None,
302 last_seen: None,
303 key_signature: vec![],
304 machine_key: None,
305 disco_key: None,
306 accepted_routes: vec![],
307 underlay_addresses: vec![],
308 derp_region: None,
309 cap: Default::default(),
310 cap_map: Default::default(),
311 peerapi_port: None,
312 peerapi_dns_proxy: false,
313 is_wireguard_only: false,
314 exit_node_dns_resolvers: vec![],
315 peer_relay: false,
316 service_vips: Default::default(),
317 }
318 }
319
320 #[test]
321 fn status_node_display_name_prefers_fqdn() {
322 let with_tailnet = node("n1", "host", Some("ts.net"), "100.64.0.1");
323 assert_eq!(
324 StatusNode::from_node(&with_tailnet).display_name,
325 "host.ts.net"
326 );
327
328 let bare = node("n2", "solo", None, "100.64.0.2");
329 assert_eq!(StatusNode::from_node(&bare).display_name, "solo");
330 }
331
332 #[test]
333 fn status_node_addresses_and_online_surfaced() {
334 let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
335 let s = StatusNode::from_node(&n);
336
337 assert_eq!(s.ipv4, "100.64.0.7".parse::<IpAddr>().unwrap());
338 assert_eq!(s.ipv6, "fd7a::1".parse::<IpAddr>().unwrap());
339 // A node with no online data surfaces `None` (unknown) — never a fabricated `false`.
340 assert_eq!(s.online, None);
341 assert_eq!(s.last_seen, None);
342
343 // A node whose domain online state is known surfaces it through StatusNode (no longer
344 // hardwired to None).
345 let mut online = node("n2", "up", Some("ts.net"), "100.64.0.8");
346 online.online = Some(true);
347 assert_eq!(StatusNode::from_node(&online).online, Some(true));
348
349 let mut offline = node("n3", "down", Some("ts.net"), "100.64.0.9");
350 offline.online = Some(false);
351 assert_eq!(StatusNode::from_node(&offline).online, Some(false));
352 }
353
354 #[test]
355 fn status_node_detects_exit_node() {
356 let mut not_exit = node("n1", "a", Some("ts.net"), "100.64.0.1");
357 not_exit.accepted_routes = vec!["100.64.0.1/32".parse().unwrap()];
358 assert!(!StatusNode::from_node(¬_exit).is_exit_node);
359
360 let mut exit = node("n2", "b", Some("ts.net"), "100.64.0.2");
361 exit.accepted_routes = vec![
362 "100.64.0.2/32".parse().unwrap(),
363 "0.0.0.0/0".parse().unwrap(),
364 ];
365 assert!(StatusNode::from_node(&exit).is_exit_node);
366
367 let mut exit6 = node("n3", "c", Some("ts.net"), "100.64.0.3");
368 exit6.accepted_routes = vec!["::/0".parse().unwrap()];
369 assert!(StatusNode::from_node(&exit6).is_exit_node);
370 }
371
372 /// `from_node` carries NO live connectivity: a bare domain `Node` has no path state, so
373 /// `cur_addr`/`relay` default to `None`. `Runtime::status` overwrites `cur_addr` by joining the
374 /// direct manager's `best_addrs`; the self node and whois (which also use `from_node`) keep
375 /// `None`. This pins the default so the enrichment seam stays the single source of connectivity.
376 #[test]
377 fn status_node_from_node_has_no_connectivity_by_default() {
378 let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
379 let s = StatusNode::from_node(&n);
380 assert_eq!(s.cur_addr, None, "a bare Node has no direct endpoint");
381 assert_eq!(s.relay, None, "a bare Node has no resolved relay");
382 }
383
384 #[test]
385 fn whois_caps_empty_when_node_has_none() {
386 // A node with no cap_map surfaces empty capabilities (not fabricated), and no user unless a
387 // profile was joined in.
388 let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
389 let whois = WhoIs::from_node_with_user(n.clone(), None);
390
391 assert_eq!(whois.node, n);
392 assert_eq!(whois.user, None);
393 assert!(whois.capabilities.is_empty());
394 }
395
396 #[test]
397 fn whois_populates_capabilities_from_cap_map() {
398 // WhoIs surfaces the domain Node's cap_map verbatim, sorted by capability name (BTreeMap).
399 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
400 n.cap_map
401 .insert("https://tailscale.com/cap/is-admin".to_string(), vec![]);
402 n.cap_map.insert(
403 "cap/ssh".to_string(),
404 vec!["root".to_string(), "ubuntu".to_string()],
405 );
406 let whois = WhoIs::from_node_with_user(n, None);
407
408 // BTreeMap iteration is sorted: "cap/ssh" < "https://…".
409 assert_eq!(
410 whois.capabilities,
411 vec![
412 (
413 "cap/ssh".to_string(),
414 vec!["root".to_string(), "ubuntu".to_string()]
415 ),
416 ("https://tailscale.com/cap/is-admin".to_string(), vec![]),
417 ]
418 );
419 }
420
421 #[test]
422 fn whois_from_node_with_user_sets_user_and_caps() {
423 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
424 n.cap_map.insert("cap/x".to_string(), vec!["y".to_string()]);
425 let whois = WhoIs::from_node_with_user(n, Some("alice@example.com".to_string()));
426
427 assert_eq!(whois.user, Some("alice@example.com".to_string()));
428 assert_eq!(
429 whois.capabilities,
430 vec![("cap/x".to_string(), vec!["y".to_string()])]
431 );
432 }
433
434 /// Build a peer with a reachable peerAPI on `ipv4`, owned by `user`.
435 fn peer_with_peerapi(stable: &str, hostname: &str, ipv4: &str, user: UserId) -> Node {
436 let mut n = node(stable, hostname, Some("ts.net"), ipv4);
437 n.user_id = user;
438 n.peerapi_port = Some(8089);
439 n
440 }
441
442 #[test]
443 fn file_targets_includes_same_owner_peer_with_peerapi() {
444 let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
445 let targets = build_file_targets(vec![peer], 42);
446
447 assert_eq!(targets.len(), 1);
448 assert_eq!(targets[0].peerapi_url, "http://100.64.0.5:8089");
449 assert_eq!(targets[0].node.hostname, "host");
450 }
451
452 #[test]
453 fn file_targets_includes_cross_owner_peer_with_target_cap() {
454 // Different owner, but carries the file-sharing-target cap → still a target (Go's OR).
455 let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
456 peer.cap_map
457 .insert("tailscale.com/cap/file-sharing-target".to_string(), vec![]);
458 let targets = build_file_targets(vec![peer], 42);
459
460 assert_eq!(
461 targets.len(),
462 1,
463 "cross-owner peer with the target cap qualifies"
464 );
465 }
466
467 #[test]
468 fn file_targets_excludes_cross_owner_peer_without_cap() {
469 // Different owner and no target cap → excluded.
470 let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
471 let targets = build_file_targets(vec![peer], 42);
472
473 assert!(
474 targets.is_empty(),
475 "a different owner without the cap is not a target"
476 );
477 }
478
479 #[test]
480 fn file_targets_excludes_peer_without_peerapi() {
481 // Same owner, but advertises no peerAPI (no port) → excluded (Go `PeerAPIBase(p) == ""`).
482 let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
483 peer.peerapi_port = None;
484 let targets = build_file_targets(vec![peer], 42);
485
486 assert!(
487 targets.is_empty(),
488 "a peer with no peerAPI cannot be a Taildrop target"
489 );
490 }
491
492 #[test]
493 fn file_targets_sorted_by_magic_dns_name() {
494 // Insert out of order; expect sorted by fqdn ("alpha.ts.net" < "zeta.ts.net").
495 let zeta = peer_with_peerapi("p2", "zeta", "100.64.0.6", 42);
496 let alpha = peer_with_peerapi("p1", "alpha", "100.64.0.5", 42);
497 let targets = build_file_targets(vec![zeta, alpha], 42);
498
499 let names: Vec<_> = targets.iter().map(|t| t.node.hostname.clone()).collect();
500 assert_eq!(names, vec!["alpha", "zeta"]);
501 }
502
503 fn region_result(id: u32, latency_ms: u64) -> ts_netcheck::RegionResult {
504 ts_netcheck::RegionResult {
505 latency: std::time::Duration::from_millis(latency_ms),
506 id: ts_derp::RegionId(std::num::NonZeroU32::new(id).unwrap()),
507 latency_map_key: format!("{id}-v4"),
508 connected_remote: "1.2.3.4:443".parse().unwrap(),
509 }
510 }
511
512 #[test]
513 fn netcheck_report_preferred_is_first_region() {
514 // The measurer hands results sorted by latency ascending, so the first is the preferred
515 // (home) region and every region is surfaced.
516 let results = [
517 region_result(5, 12),
518 region_result(9, 40),
519 region_result(2, 88),
520 ];
521 let report = NetcheckReport::from_region_results(&results);
522 assert_eq!(
523 report.preferred_derp,
524 Some(5),
525 "lowest-latency region is preferred"
526 );
527 assert_eq!(report.region_latencies.len(), 3);
528 assert_eq!(report.region_latencies[0].region_id, 5);
529 assert_eq!(
530 report.region_latencies[0].latency,
531 std::time::Duration::from_millis(12)
532 );
533 // Order is preserved as given (latency-ascending from the measurer).
534 let ids: Vec<u32> = report
535 .region_latencies
536 .iter()
537 .map(|r| r.region_id)
538 .collect();
539 assert_eq!(ids, vec![5, 9, 2]);
540 }
541
542 #[test]
543 fn netcheck_report_empty_when_no_measurements() {
544 // Before any measurement (or when none was reachable): no preferred region, empty list — not
545 // a fabricated value.
546 let report = NetcheckReport::from_region_results(&[]);
547 assert_eq!(report, NetcheckReport::default());
548 assert_eq!(report.preferred_derp, None);
549 assert!(report.region_latencies.is_empty());
550 }
551}