-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathapp.rs
More file actions
2288 lines (2124 loc) · 85.2 KB
/
Copy pathapp.rs
File metadata and controls
2288 lines (2124 loc) · 85.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, VecDeque};
use std::net::IpAddr;
use std::time::{Duration, Instant};
use hickory_resolver::proto::rr::RecordType;
use crate::dns::{self, ClientSubnet, QueryOutcome, QueryResult};
use crate::globe::GlobeView;
use crate::resolvers::{self, Resolver};
use crate::sites::Site;
/// Watch-mode re-poll interval; propagation usually moves on TTL boundaries,
/// so sub-minute polling is plenty.
pub const POLL_INTERVAL: Duration = Duration::from_secs(30);
/// Slack added on top of a reported TTL before calling a cache stale: we only
/// sample once per POLL_INTERVAL, so an answer can be up to one interval old,
/// plus a little headroom for clock skew and in-flight time.
const TTL_GRACE: Duration = Duration::from_secs(POLL_INTERVAL.as_secs() + 5);
/// Watch-mode observations kept per resolver, oldest dropped first.
const HISTORY_CAP: usize = 32;
/// TTL at or above which the footer suggests lowering it before a planned
/// record change (the "drop TTL to 30s a day before migrating" practice).
pub const ADVISORY_TTL: u32 = 3600;
/// How far above the fleet's 90th percentile a reported TTL has to sit before
/// it stops counting as the same record's countdown. Honest countdowns for one
/// record all live in `(0, configured_ttl]`, so a 4× gap can't come from
/// caching timing — it's a resolver reporting a number of its own invention.
const TTL_OUTLIER_FACTOR: u32 = 4;
pub const RECORD_TYPES: &[RecordType] = &[
RecordType::A,
RecordType::AAAA,
RecordType::CNAME,
RecordType::MX,
RecordType::NS,
RecordType::TXT,
RecordType::SOA,
];
pub const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
/// Body width at which auto view switches from globe to flat map. The globe
/// panel is square-ish so it stays useful on narrow terminals; the flat map
/// only earns its 350°-wide canvas once there's real room next to the table.
pub const AUTO_FLAT_WIDTH: u16 = 190;
/// Which map panel to show, from `--view`, the config file, or Ctrl+O.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ViewMode {
/// Globe on narrow terminals, flat map when the window is wide.
#[default]
Auto,
/// Always the flat map.
Map,
/// Always the globe.
Globe,
}
/// Table ordering, cycled with Ctrl+S. Sorts are stable, so ties keep the
/// curated resolver-list order — `Location` therefore doubles as "group by
/// location", and `Answer` groups identical answers together.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortMode {
#[default]
Resolver,
Location,
Time,
Status,
Answer,
}
impl SortMode {
pub const fn label(self) -> &'static str {
match self {
SortMode::Resolver => "resolver",
SortMode::Location => "location",
SortMode::Time => "ping",
SortMode::Status => "status",
SortMode::Answer => "answer",
}
}
pub const fn next(self) -> Self {
match self {
SortMode::Resolver => SortMode::Location,
SortMode::Location => SortMode::Time,
SortMode::Time => SortMode::Status,
SortMode::Status => SortMode::Answer,
SortMode::Answer => SortMode::Resolver,
}
}
}
#[derive(Debug, Clone)]
pub enum RowState {
Idle,
Pending,
Done {
result: QueryResult,
elapsed: Duration,
/// When the answer arrived; anchors the cache-expiry countdown.
at: Instant,
/// Whether the resolver honored the round's ECS option (see
/// `QueryOutcome::ecs_honored`). Always None on ECS-less rounds.
ecs_honored: Option<bool>,
},
}
impl RowState {
/// Time left before this row's reported TTL says the cache entry must be
/// refetched. None for rows without records.
pub fn remaining_ttl(&self, now: Instant) -> Option<Duration> {
let RowState::Done {
result: QueryResult::Records { min_ttl, .. },
at,
..
} = self
else {
return None;
};
let ttl = Duration::from_secs(u64::from(*min_ttl));
Some(ttl.saturating_sub(now.saturating_duration_since(*at)))
}
}
/// One watch-mode answer from a resolver, kept to judge cache behavior over
/// successive polls.
#[derive(Debug, Clone)]
struct Observation {
values: Vec<String>,
min_ttl: u32,
at: Instant,
}
/// One resolver's reported TTL, attributable back to that resolver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TtlReport {
/// Index into `App::resolvers`, so callers can name the resolver.
pub index: usize,
/// The TTL it reported, in seconds.
pub ttl: u32,
}
/// What the fleet's reported TTLs say about the zone's configured TTL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TtlEstimate {
/// Best estimate of the zone's configured TTL, in seconds: the longest
/// countdown reported by a resolver whose number the rest of the fleet
/// corroborates.
pub ttl: u32,
/// How many majority rows reported a TTL at all (`ttl` plus `outliers`
/// were drawn from these).
pub samples: usize,
/// Reports too far above the fleet to be this record's countdown, longest
/// first. Not an error to surface and forget: such a cache keeps serving
/// the old answer well past the zone's stated lifetime.
pub outliers: Vec<TtlReport>,
}
/// Why a resolver is still serving a non-majority answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TtlVerdict {
/// The answer outlived the TTL the resolver itself reported: the cache is
/// serving stale data (a resolver that ignores TTLs).
PastTtl,
/// The TTL jumped back up while the answer stayed the same: the resolver
/// did refetch, and *upstream* (e.g. a lagging secondary authoritative
/// server) still handed out the old data.
Upstream,
}
#[derive(Debug, Default)]
pub struct Summary {
pub done: usize,
pub ok: usize,
pub no_records: usize,
pub servfail: usize,
pub errors: usize,
/// Resolvers that gave a usable answer (records, an authoritative
/// "no records", or a SERVFAIL — the resolver's view of the domain is
/// "broken", a real state during an NS migration). Timeouts and refusals
/// say nothing about propagation, so percentages are computed against
/// this, not the full list.
pub responding: usize,
/// Distinct answer *groups*. Answers sharing any record are grouped
/// together, so round-robin subsets of one pool count as a single group
/// instead of flagging every resolver as divergent.
pub groups: usize,
/// Resolvers in the largest group.
pub agree: usize,
/// Per-row flag: true when that resolver's answer is in the largest group.
pub majority_rows: Vec<bool>,
/// Union of record values across the largest group.
pub majority_values: Vec<String>,
/// Answers from resolvers that ignored the round's ECS option. Shown for
/// reference but excluded from `responding` — they describe the
/// resolver's own vantage point, not the probed client subnet, so they
/// must not drag the propagation percentage (or hold watch mode open)
/// on GeoDNS zones where their answer legitimately differs.
pub ecs_blind: usize,
}
/// Parameters of one query round, handed to the spawner in `main`.
pub struct Round {
pub domain: String,
pub rtype: RecordType,
pub ecs: Option<ClientSubnet>,
pub generation: u64,
/// Resolver indices to (re)query.
pub indices: Vec<usize>,
}
/// The add-resolver dialog (`+`): one text field per resolver attribute,
/// validated as a whole on Enter so a half-typed IP doesn't block editing.
#[derive(Debug, Default)]
pub struct ResolverForm {
/// Field values in `LABELS` order: name, IP, location, lat, lon.
pub fields: [String; 5],
/// Which field has focus.
pub focus: usize,
/// Cursor within the focused field. Input is ASCII-only (like the domain
/// field), so byte index == char index.
pub cursor: usize,
/// Last failed validation, cleared on the next edit.
pub error: Option<String>,
}
impl ResolverForm {
pub const LABELS: [&'static str; 5] = ["Name", "IP", "Location", "Lat", "Lon"];
fn field(&mut self) -> &mut String {
&mut self.fields[self.focus]
}
pub fn insert_char(&mut self, c: char) {
// ASCII-only keeps cursor arithmetic byte==char, like the domain
// input; controls would corrupt the rendered line.
if !c.is_ascii() || c.is_ascii_control() {
return;
}
let at = self.cursor;
self.field().insert(at, c);
self.cursor += 1;
self.error = None;
}
pub fn backspace(&mut self) {
if self.cursor > 0 {
self.cursor -= 1;
let at = self.cursor;
self.field().remove(at);
self.error = None;
}
}
pub fn delete(&mut self) {
let at = self.cursor;
if at < self.field().len() {
self.field().remove(at);
self.error = None;
}
}
pub fn move_cursor_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_cursor_right(&mut self) {
self.cursor = (self.cursor + 1).min(self.fields[self.focus].len());
}
pub fn cursor_home(&mut self) {
self.cursor = 0;
}
pub fn cursor_end(&mut self) {
self.cursor = self.fields[self.focus].len();
}
/// Tab/↓ (or BackTab/↑) between fields; the cursor lands at the end of
/// the newly focused value.
pub fn cycle_focus(&mut self, forward: bool) {
let n = self.fields.len();
self.focus = if forward {
(self.focus + 1) % n
} else {
(self.focus + n - 1) % n
};
self.cursor = self.fields[self.focus].len();
}
/// Validate the form into a resolver. Mirrors the config file's rules
/// (`config::resolver_list`): IP must parse, lat/lon together or not at
/// all, coordinates on the globe.
fn validated(&self) -> Result<Resolver, String> {
let name = self.fields[0].trim();
if name.is_empty() {
return Err("name is required".into());
}
let ip_text = self.fields[1].trim();
let ip: IpAddr = ip_text
.parse()
.map_err(|_| format!("invalid IP address {ip_text:?}"))?;
let parse_coord = |label: &str, text: &str| -> Result<Option<f64>, String> {
let text = text.trim();
if text.is_empty() {
return Ok(None);
}
text.parse::<f64>()
.map(Some)
.map_err(|_| format!("{label} must be a number"))
};
let coords = match (
parse_coord("lat", &self.fields[3])?,
parse_coord("lon", &self.fields[4])?,
) {
(Some(lat), Some(lon)) => {
if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
return Err("lat must be in -90..=90 and lon in -180..=180".into());
}
Some((lat, lon))
}
(None, None) => None,
_ => return Err("lat and lon must be given together".into()),
};
Ok(Resolver {
name: name.to_string(),
location: self.fields[2].trim().to_string(),
ip,
coords,
probe: None,
})
}
}
/// Normalize a typed-or-passed domain and check that it is a name we can put
/// on the wire: trailing whitespace and the root dot go (`example.com.` and
/// `example.com` are the same name), then `dns::parse_name` has the final
/// say. Shared by the CLI and the TUI input field so both modes accept
/// exactly the same set of names, and so a malformed one is reported once
/// rather than as an identical failure on every resolver. An empty input is
/// "nothing to query", not an error — callers treat it as a no-op.
pub fn validate_domain(input: &str) -> Result<String, String> {
let domain = input.trim().trim_end_matches('.').to_string();
if !domain.is_empty() {
dns::parse_name(&domain)?;
}
Ok(domain)
}
pub struct App {
pub domain: String,
/// Cursor position in `domain`. The input only accepts ASCII
/// (alphanumerics, `.`, `-`, `_`), so byte index == char index.
pub cursor: usize,
pub rtype_idx: usize,
pub rows: Vec<RowState>,
pub generation: u64,
pub spinner_frame: usize,
pub should_quit: bool,
pub queried: Option<(String, RecordType, Option<ClientSubnet>)>,
/// Client subnets from --ecs/config, cycled with Ctrl+N. Empty for most
/// runs — every trace of ECS in the UI is gated on this being non-empty.
pub ecs_list: Vec<ClientSubnet>,
/// Index into `ecs_list`; None = ECS off (the plain view of the zone).
pub ecs_sel: Option<usize>,
/// Table scroll offset; clamped against the viewport during draw.
pub scroll: usize,
/// Watch mode: re-poll after each round until propagation reaches 100%.
/// Enabled by starting a query, toggled with Ctrl+R.
pub auto_refresh: bool,
/// When the next poll fires, if one is scheduled.
pub next_poll: Option<Instant>,
/// Active table ordering, cycled with Ctrl+S.
pub sort: SortMode,
/// Flat map ↔ rotating globe morph state.
pub globe: GlobeView,
/// View policy: auto by width, or pinned by --view/config/Ctrl+O.
pub view_mode: ViewMode,
/// False until the first `sync_view`: the first frame snaps to its view
/// instead of replaying the morph on every launch in a narrow terminal.
view_synced: bool,
/// Per-resolver anycast site discovered by that operator's identification
/// query (issue #6): which POP is actually answering us. None = no probe
/// or probe failed. Session-static — the site depends on our network
/// path, not on the queried domain.
pub sites: Vec<Option<Site>>,
/// Per-resolver answers across watch-mode polls (bounded FIFO). Cleared
/// on a fresh query, preserved across re-polls — cache-behavior verdicts
/// only exist while watching one domain/type.
history: Vec<VecDeque<Observation>>,
/// The resolver list for this session: the startup list plus/minus
/// runtime additions and removals. `rows`, `sites` and `history` are
/// parallel to it.
pub resolvers: Vec<Resolver>,
/// Table row highlight, as a *resolver* index (stable across re-sorts);
/// ↑/↓ move it through the display order, Ctrl+X removes it.
pub selected: Option<usize>,
/// Add-resolver dialog; while open it captures all key input.
pub form: Option<ResolverForm>,
/// Why the last Enter didn't start a round: the input isn't a DNS name.
/// Shown in place of the gauge and cleared by the next edit — firing the
/// round anyway would fill the table with 30-odd identical parse errors
/// that read like a network outage.
pub input_error: Option<String>,
}
impl App {
pub fn new(domain: String) -> Self {
let resolvers = resolvers::active().to_vec();
let n = resolvers.len();
Self {
cursor: domain.len(),
domain,
rtype_idx: 0,
rows: vec![RowState::Idle; n],
generation: 0,
spinner_frame: 0,
should_quit: false,
queried: None,
ecs_list: Vec::new(),
ecs_sel: None,
scroll: 0,
auto_refresh: false,
next_poll: None,
sort: SortMode::default(),
globe: GlobeView::new(Instant::now()),
view_mode: ViewMode::default(),
view_synced: false,
sites: vec![None; n],
history: vec![VecDeque::new(); n],
resolvers,
selected: None,
form: None,
input_error: None,
}
}
/// Where this resolver's answers come from, as shown in the Loc column:
/// the discovered anycast site when known, else the configured location.
pub fn effective_location(&self, index: usize) -> &str {
match &self.sites[index] {
Some(site) => &site.code,
None => &self.resolvers[index].location,
}
}
/// Map position for this resolver: the discovered site when we know its
/// coordinates, else the configured (operator home) position.
pub fn effective_coords(&self, index: usize) -> Option<(f64, f64)> {
self.sites[index]
.as_ref()
.and_then(|site| site.coords)
.or(self.resolvers[index].coords)
}
/// Record a discovered anycast site. Keyed by IP, not index: the probe
/// result arrives on a channel and the list may have been edited (rows
/// shifted) while it was in flight.
pub fn set_site(&mut self, ip: IpAddr, site: Site) {
if let Some(index) = self.resolvers.iter().position(|r| r.ip == ip) {
self.sites[index] = Some(site);
}
}
pub fn record_type(&self) -> RecordType {
RECORD_TYPES[self.rtype_idx]
}
/// ↑/↓ (±1) and PageUp/PageDown (±10): step the highlight through the
/// *display* order, so it moves visually even under Time/Status sorts.
/// The first press enters the table at the nearest end.
pub fn move_selection(&mut self, delta: isize) {
if self.rows.is_empty() {
return;
}
let order = self.display_order(&self.summary());
let last = order.len() as isize - 1;
let position = self
.selected
.and_then(|sel| order.iter().position(|&i| i == sel));
let target = match position {
Some(p) => (p as isize).saturating_add(delta).clamp(0, last),
None if delta < 0 => last,
None => 0,
};
self.selected = Some(order[target as usize]);
}
/// `+`: open the add-resolver dialog.
pub fn open_form(&mut self) {
self.form = Some(ResolverForm::default());
}
pub fn cancel_form(&mut self) {
self.form = None;
}
/// Enter in the dialog: validate, then append the resolver. On failure
/// the dialog stays open showing the error. Returns a round for the new
/// row when a domain is being watched, so it fills in right away.
pub fn submit_form(&mut self) -> Option<Round> {
let form = self.form.as_mut()?;
let resolver = match form.validated() {
Ok(resolver) => resolver,
Err(message) => {
form.error = Some(message);
return None;
}
};
if let Some(existing) = self.resolvers.iter().find(|r| r.ip == resolver.ip) {
form.error = Some(format!(
"{} is already listed ({})",
resolver.ip, existing.name
));
return None;
}
self.form = None;
let round = self.add_resolver(resolver);
// Highlight the addition — under a non-default sort the new row can
// land anywhere, and the highlight keeps it visible (draw follows it).
self.selected = Some(self.resolvers.len() - 1);
round
}
/// Append a resolver to the session list. When a query is on screen the
/// new row starts Pending and the returned round queries just it — on
/// the *current* generation: bumping it would orphan the in-flight rows
/// of the active round.
pub fn add_resolver(&mut self, resolver: Resolver) -> Option<Round> {
self.resolvers.push(resolver);
self.sites.push(None);
self.history.push(VecDeque::new());
let Some((domain, rtype, ecs)) = self.queried.clone() else {
self.rows.push(RowState::Idle);
return None;
};
self.rows.push(RowState::Pending);
Some(Round {
domain,
rtype,
ecs,
generation: self.generation,
indices: vec![self.rows.len() - 1],
})
}
/// Ctrl+X: drop the highlighted resolver. Indices shift, so results
/// still in flight would land on the wrong rows (or past the end) — the
/// generation bump discards them, and the returned round restarts the
/// rows that were left waiting. The last resolver can't be removed: an
/// empty table has nothing left to check.
pub fn remove_selected(&mut self) -> Option<Round> {
let index = self.selected?;
if self.resolvers.len() <= 1 {
return None;
}
// Keep the highlight at the same display position, on whichever row
// moves up into it.
let position = self
.display_order(&self.summary())
.iter()
.position(|&i| i == index)
.unwrap_or(0);
self.resolvers.remove(index);
self.rows.remove(index);
self.sites.remove(index);
self.history.remove(index);
self.generation += 1;
let order = self.display_order(&self.summary());
self.selected = order.get(position.min(order.len() - 1)).copied();
let pending: Vec<usize> = (0..self.rows.len())
.filter(|&i| matches!(self.rows[i], RowState::Pending))
.collect();
let (domain, rtype, ecs) = self.queried.clone()?;
if pending.is_empty() {
return None;
}
Some(Round {
domain,
rtype,
ecs,
generation: self.generation,
indices: pending,
})
}
pub fn insert_char(&mut self, c: char) {
self.domain.insert(self.cursor, c);
self.cursor += 1;
self.input_error = None;
}
pub fn backspace(&mut self) {
if self.cursor > 0 {
self.cursor -= 1;
self.domain.remove(self.cursor);
self.input_error = None;
}
}
pub fn delete(&mut self) {
if self.cursor < self.domain.len() {
self.domain.remove(self.cursor);
self.input_error = None;
}
}
pub fn move_cursor_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_cursor_right(&mut self) {
self.cursor = (self.cursor + 1).min(self.domain.len());
}
/// Jump to the start of the current dot-separated label, or of the
/// previous one when already at a label boundary.
pub fn move_cursor_word_left(&mut self) {
let bytes = self.domain.as_bytes();
while self.cursor > 0 && bytes[self.cursor - 1] == b'.' {
self.cursor -= 1;
}
while self.cursor > 0 && bytes[self.cursor - 1] != b'.' {
self.cursor -= 1;
}
}
/// Jump past the end of the current dot-separated label, or of the next
/// one when already at a label boundary.
pub fn move_cursor_word_right(&mut self) {
let bytes = self.domain.as_bytes();
while self.cursor < bytes.len() && bytes[self.cursor] == b'.' {
self.cursor += 1;
}
while self.cursor < bytes.len() && bytes[self.cursor] != b'.' {
self.cursor += 1;
}
}
pub fn clear_domain(&mut self) {
self.domain.clear();
self.cursor = 0;
self.input_error = None;
}
/// The view this width calls for under the active policy.
pub fn desired_globe(&self, body_width: u16) -> bool {
match self.view_mode {
ViewMode::Globe => true,
ViewMode::Map => false,
ViewMode::Auto => body_width < AUTO_FLAT_WIDTH,
}
}
/// Re-assert the view target for the current width; called every frame
/// so resizing across the auto threshold morphs the panel. The first
/// call snaps (no launch animation), later changes animate.
pub fn sync_view(&mut self, body_width: u16) {
let want = self.desired_globe(body_width);
if self.view_synced {
self.globe.set_target(want, Instant::now());
} else {
self.globe.snap(want);
self.view_synced = true;
}
}
/// Ctrl+O: flip the view and pin it — a manual choice shouldn't be
/// overridden by the next resize.
pub fn toggle_globe(&mut self) {
self.view_mode = if self.globe.target() {
ViewMode::Map
} else {
ViewMode::Globe
};
self.globe
.set_target(self.view_mode == ViewMode::Globe, Instant::now());
}
pub fn cycle_record_type(&mut self, forward: bool) {
let n = RECORD_TYPES.len();
self.rtype_idx = if forward {
(self.rtype_idx + 1) % n
} else {
(self.rtype_idx + n - 1) % n
};
}
/// Install the ECS list from config/CLI. Selection starts on the first
/// subnet — passing --ecs means "query with it", not just "have it
/// available".
pub fn set_ecs_list(&mut self, list: Vec<ClientSubnet>) {
self.ecs_sel = (!list.is_empty()).then_some(0);
self.ecs_list = list;
}
/// The subnet the next Enter will query with.
pub fn active_ecs(&self) -> Option<ClientSubnet> {
self.ecs_sel.map(|i| self.ecs_list[i])
}
/// Ctrl+N: step the selection through the configured subnets plus an
/// "off" position. The caller follows up with `begin_reselect` so the
/// table refreshes for the new subnet without waiting for Enter.
pub fn cycle_ecs(&mut self) {
if self.ecs_list.is_empty() {
return;
}
self.ecs_sel = match self.ecs_sel {
Some(i) if i + 1 < self.ecs_list.len() => Some(i + 1),
Some(_) => None, // past the last subnet: ECS off
None => Some(0),
};
}
/// Arm a new query round. Returns what to query (all resolvers), or None
/// if the domain input is empty or isn't a DNS name — the latter leaves
/// `input_error` set for the header to show, and the previous round's
/// rows untouched.
pub fn begin_query(&mut self) -> Option<Round> {
let domain = match validate_domain(&self.domain) {
Ok(domain) => domain,
Err(err) => {
self.input_error = Some(err);
return None;
}
};
self.input_error = None;
if domain.is_empty() {
return None;
}
Some(self.arm_round(domain, self.record_type()))
}
/// Arm a fresh round for the already-queried domain with the current
/// record-type and ECS selections: Tab and Ctrl+N re-query as they
/// cycle. Reads `queried`'s domain, not the (possibly mid-edit) input
/// field, and does nothing before the first query — there's nothing to
/// refresh yet.
pub fn begin_reselect(&mut self) -> Option<Round> {
let (domain, ..) = self.queried.clone()?;
Some(self.arm_round(domain, self.record_type()))
}
/// Reset every row and start a round of all resolvers, capturing the
/// active ECS selection. History clears too: answers under a different
/// subnet aren't comparable across polls.
fn arm_round(&mut self, domain: String, rtype: RecordType) -> Round {
self.generation += 1;
self.rows = vec![RowState::Pending; self.resolvers.len()];
self.history = vec![VecDeque::new(); self.resolvers.len()];
let ecs = self.active_ecs();
self.queried = Some((domain.clone(), rtype, ecs));
Round {
domain,
rtype,
ecs,
generation: self.generation,
indices: (0..self.rows.len()).collect(),
}
}
/// Arm a poll of the last-queried domain/type, ignoring the (possibly
/// mid-edit) input field. Only re-polls rows whose answer can have
/// changed: rows agreeing with the majority are skipped while their TTL
/// countdown still runs (a cache can't legally change before expiry), and
/// picked up again once it hits zero — so an old-value *majority* still
/// gets re-checked and can flip.
pub fn begin_requery(&mut self) -> Option<Round> {
// Re-polls stay on the queried round's ECS subnet (Ctrl+N re-arms
// `queried` via begin_reselect, so the two can't drift) — mixing
// subnets within one table would make the group comparison
// meaningless.
let (domain, rtype, ecs) = self.queried.clone()?;
let summary = self.summary();
let now = Instant::now();
let indices: Vec<usize> = (0..self.rows.len())
.filter(|&i| {
let agreeing = matches!(
&self.rows[i],
RowState::Done {
result: QueryResult::Records { .. },
..
}
) && summary.majority_rows[i];
!(agreeing
&& self.rows[i]
.remaining_ttl(now)
.is_some_and(|r| !r.is_zero()))
})
.collect();
if indices.is_empty() {
return None;
}
self.generation += 1;
for &i in &indices {
self.rows[i] = RowState::Pending;
}
Some(Round {
domain,
rtype,
ecs,
generation: self.generation,
indices,
})
}
pub fn apply(&mut self, outcome: QueryOutcome) {
if outcome.generation != self.generation {
return; // stale result from a superseded query round
}
let now = Instant::now();
if let QueryResult::Records { values, min_ttl } = &outcome.result {
let history = &mut self.history[outcome.resolver_index];
if history.len() == HISTORY_CAP {
history.pop_front();
}
history.push_back(Observation {
values: values.clone(),
min_ttl: *min_ttl,
at: now,
});
}
self.rows[outcome.resolver_index] = RowState::Done {
result: outcome.result,
elapsed: outcome.elapsed,
at: now,
ecs_honored: outcome.ecs_honored,
};
}
/// Judge a resolver's cache behavior from its answer history. Only
/// meaningful for rows currently *disagreeing* with the majority — the
/// caller filters; the same patterns on an agreeing row are normal
/// operation.
pub fn ttl_verdict(&self, index: usize, now: Instant) -> Option<TtlVerdict> {
let history = &self.history[index];
let latest = history.back()?;
// Tail streak of identical answers; one sample proves nothing.
let streak = history
.iter()
.rev()
.take_while(|o| o.values == latest.values)
.count();
if streak < 2 {
return None;
}
let first = &history[history.len() - streak];
// TTL rising within the streak means the resolver refetched and got
// the same old data back: the lag is upstream, not this cache.
let mut prev_ttl = first.min_ttl;
for obs in history.iter().skip(history.len() - streak + 1) {
if obs.min_ttl > prev_ttl {
return Some(TtlVerdict::Upstream);
}
prev_ttl = obs.min_ttl;
}
let deadline = first.at + Duration::from_secs(u64::from(first.min_ttl)) + TTL_GRACE;
(now > deadline).then_some(TtlVerdict::PastTtl)
}
/// Estimate the zone's configured TTL from what the majority rows report.
///
/// A reported TTL is a *countdown*, not the configured value: a resolver
/// that just refetched reports (nearly) the full TTL, one halfway through
/// its cache entry reports half of it. So the longest report is the best
/// estimate — but only among resolvers reporting this record's countdown.
/// Some public resolvers hand back numbers unrelated to the authoritative
/// record (fixed floors, or values of their own invention), and taking a
/// plain max let one of them speak for the zone: a single resolver
/// reporting 8423s turned a 300s zone into "TTL ≈ 2h23m".
///
/// So the max is taken over reports within `TTL_OUTLIER_FACTOR` of the
/// fleet's 90th percentile, and anything above that is returned separately
/// for the caller to attribute. Skipping a tenth of the fleet is what
/// bounds the damage: a handful of liars can't move the percentile, and by
/// construction no more than a tenth of the reports can be rejected. A
/// fleet where *most* resolvers fabricate the same long TTL is beyond what
/// resolver-side data can settle — dnsglobe never talks to the
/// authoritative servers, so there is no ground truth to fall back on.
pub fn estimated_ttl(&self, summary: &Summary) -> Option<TtlEstimate> {
let mut reports: Vec<TtlReport> = self
.rows
.iter()
.enumerate()
.filter(|&(i, _)| summary.majority_rows[i])
.filter_map(|(index, row)| match row {
RowState::Done {
result: QueryResult::Records { min_ttl, .. },
..
} => Some(TtlReport {
index,
ttl: *min_ttl,
}),
_ => None,
})
.collect();
let samples = reports.len();
if samples == 0 {
return None;
}
reports.sort_unstable_by_key(|r| std::cmp::Reverse(r.ttl));
// Longest report left after skipping the top tenth. Under ten samples
// that tenth is empty and this is just the max, which is what we want:
// a percentile over a handful of resolvers is too thin to convict any
// of them of lying.
let bulk = reports[samples / 10].ttl;
let cutoff = bulk.saturating_mul(TTL_OUTLIER_FACTOR);
// A zero cutoff means most of the fleet is at the end of its countdown
// (or reports no TTL at all); every other report would then look like
// an outlier, so fall back to the plain max.
let outliers = if cutoff == 0 {
0
} else {
reports.iter().take_while(|r| r.ttl > cutoff).count()
};
Some(TtlEstimate {
// `bulk` is never above the cutoff, so a non-outlier always
// remains to speak for the zone.
ttl: reports[outliers].ttl,
samples,
outliers: reports[..outliers].to_vec(),
})
}
/// Worst-case wait until every non-majority cache must have refetched:
/// the max remaining TTL across differing rows. None when nothing
/// differs (or differing rows carry no records).
pub fn stale_expiry_bound(&self, summary: &Summary, now: Instant) -> Option<Duration> {
self.rows
.iter()
.enumerate()
.filter(|&(i, row)| {
!summary.majority_rows[i]
&& matches!(
row,
RowState::Done {
result: QueryResult::Records { .. },
..
}
)
})
.filter_map(|(_, row)| row.remaining_ttl(now))
.max()
}
pub fn in_flight(&self) -> bool {
self.rows.iter().any(|r| matches!(r, RowState::Pending))
}
/// Resolver indices in display order under the active sort.
pub fn display_order(&self, summary: &Summary) -> Vec<usize> {
let mut order: Vec<usize> = (0..self.rows.len()).collect();
match self.sort {
SortMode::Resolver => {}
SortMode::Location => order.sort_by_key(|&i| self.effective_location(i)),
// Fastest first; rows without a result sink to the bottom.
SortMode::Time => order.sort_by_key(|&i| match &self.rows[i] {
RowState::Done { elapsed, .. } => *elapsed,
_ => Duration::MAX,
}),
// Problems first: what's blocking propagation is what you scan
// for. Mid-flight every answer counts as majority, matching the
// table's "✓ OK until the round settles" display.
SortMode::Status => {
let in_flight = self.in_flight();
let now = Instant::now();
order.sort_by_key(|&i| match &self.rows[i] {
RowState::Done { result, .. } => match result {
QueryResult::Records { .. } if in_flight || summary.majority_rows[i] => 5,
// Misbehaving caches are the most actionable rows.
QueryResult::Records { .. } if self.ttl_verdict(i, now).is_some() => 0,
QueryResult::Records { .. } => 1, // differs
QueryResult::NoRecords(_) => 2,
QueryResult::ServFail => 3,
QueryResult::Error(_) => 4,
},
RowState::Pending => 6,
RowState::Idle => 7,
});
}
SortMode::Answer => order.sort_by(|&a, &b| {
let values = |i: usize| match &self.rows[i] {
RowState::Done {
result: QueryResult::Records { values, .. },
..
} => Some(values),
_ => None,
};
// Some < None puts answerless rows last.
match (values(a), values(b)) {
(Some(va), Some(vb)) => va.cmp(vb),