taba-cli 0.1.1-rc.2

The Taba client command line.
Documentation
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
//! The state of the whole interface (doc 34, section 4): everything the screens show, with no input or output.
//! `update` changes it and `view` only reads it, so both are tested without a terminal or a network.

use taba_client::json::Fields;
use taba_client::Error;

use crate::profile::ConfigFile;
use crate::tui::api::{
    ApiCall, Backup, ClusterStatus, Drain, FlushReport, Me, Missing, Nodes, Severity, StopReport,
    Token, Topic, TopicNumbers,
};
use crate::tui::editor::Editor;
use crate::tui::history::History;
use crate::tui::i18n::{self, Lang};
use crate::tui::prom::Metrics;
use crate::tui::theme::Theme;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Cluster,
    Topics,
    Tokens,
    Profiles,
}

/// The messages are not a tab: they are one of the views of a topic (`Topics › name › Messages`).
pub const TABS: [Tab; 4] = [Tab::Cluster, Tab::Topics, Tab::Tokens, Tab::Profiles];

impl Tab {
    pub fn index(self) -> usize {
        TABS.iter().position(|t| *t == self).unwrap_or(0)
    }

    pub fn name_key(self) -> &'static str {
        match self {
            Tab::Cluster => "tab.cluster",
            Tab::Topics => "tab.topics",
            Tab::Tokens => "tab.tokens",
            Tab::Profiles => "tab.profiles",
        }
    }
}

/// What the person set at the start: language, look, profile and history.
#[derive(Debug, Clone)]
pub struct Options {
    pub lang: Lang,
    pub theme: Theme,
    pub profile: String,
    pub url: String,
    pub retention_secs: u64,
    pub interval_secs: u64,
    /// The profiles file as it was read: the Profiles tab and the choice of a profile start from it.
    pub profiles: ConfigFile,
    /// Ask which profile to use before connecting (none was given and there is more than one).
    pub choose_profile: bool,
}

/// A node id for tables and messages: its start and its end, since the ids of nodes made together share the
/// start (they are GUID v7, ordered by time).
pub fn short_id(id: &str) -> String {
    let chars: Vec<char> = id.chars().collect();
    if chars.len() <= 12 {
        return id.to_owned();
    }
    let head: String = chars[..4].iter().collect();
    let tail: String = chars[chars.len() - 6..].iter().collect();
    format!("{head}…{tail}")
}

/// The part of a node id that is safe and distinct in a file name: its last eight letters and digits.
pub fn file_tag(id: &str) -> String {
    let kept: Vec<char> = id.chars().filter(char::is_ascii_alphanumeric).collect();
    kept[kept.len().saturating_sub(8)..].iter().collect()
}

/// A failed call, reduced to what the screens show.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fail {
    pub status: u16,
    pub code: String,
    pub message: String,
    pub request_id: Option<String>,
    pub retry_after: Option<u64>,
    /// `root` or the permission that was missing (`403 auth.forbidden`).
    pub required: Option<String>,
}

impl Fail {
    /// The client could not reach the server (no HTTP status).
    pub fn is_offline(&self) -> bool {
        self.status == 0
    }

    pub fn is_denied(&self) -> bool {
        self.status == 401 || self.status == 403
    }
}

impl From<&Error> for Fail {
    fn from(e: &Error) -> Fail {
        let body = String::from_utf8_lossy(&e.body);
        let required = Fields::parse(&body).ok().and_then(|f| f.string("required"));
        Fail {
            status: e.status,
            code: e.code.clone(),
            message: e.message.clone(),
            request_id: e.request_id.clone(),
            retry_after: e.retry_after,
            required,
        }
    }
}

/// The longest wait between two tries of a read that keeps failing.
const MAX_BACKOFF_MS: u64 = 30_000;

/// A thing read on a schedule: the last good value, the error of the last try, and when to try again.
/// A failure keeps the value (it becomes *stale*) and backs off (×2 up to 30 s; `Retry-After` is obeyed).
#[derive(Debug, Clone, PartialEq)]
pub struct Feed<T> {
    pub data: Option<T>,
    /// When the last good value arrived (ms since the app opened).
    pub fetched_at: Option<u64>,
    pub error: Option<Fail>,
    pub in_flight: Option<u64>,
    pub next_at: u64,
    pub failures: u32,
}

impl<T> Default for Feed<T> {
    fn default() -> Feed<T> {
        Feed {
            data: None,
            fetched_at: None,
            error: None,
            in_flight: None,
            next_at: 0,
            failures: 0,
        }
    }
}

impl<T> Feed<T> {
    pub fn due(&self, now: u64) -> bool {
        self.in_flight.is_none() && now >= self.next_at
    }

    pub fn ok(&mut self, now: u64, data: T, every_ms: u64) {
        self.data = Some(data);
        self.fetched_at = Some(now);
        self.error = None;
        self.in_flight = None;
        self.failures = 0;
        self.next_at = now + every_ms;
    }

    pub fn fail(&mut self, now: u64, fail: Fail, every_ms: u64) {
        self.failures = self.failures.saturating_add(1);
        let backoff = every_ms
            .saturating_mul(1 << self.failures.min(5))
            .min(MAX_BACKOFF_MS);
        self.next_at = now
            + match fail.retry_after {
                Some(secs) => secs.saturating_mul(1000),
                None => backoff,
            };
        self.error = Some(fail);
        self.in_flight = None;
    }

    /// Old data kept after a failure.
    pub fn is_stale(&self) -> bool {
        self.data.is_some() && self.error.is_some()
    }

    /// Seconds until the next try after a failure.
    pub fn retry_in(&self, now: u64) -> Option<u64> {
        self.error.as_ref()?;
        Some(self.next_at.saturating_sub(now).div_ceil(1000))
    }

    /// Asks for a read at the next tick (`r`).
    pub fn refresh_now(&mut self) {
        self.next_at = 0;
    }

    pub fn reset(&mut self) {
        *self = Feed::default();
    }
}

/// An action of a node or the cluster that asks for confirmation first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pending {
    Drain(String),
    Return(String),
    FlushNode(String),
    FlushAll,
    Stop,
    /// The id and the name of the token.
    RevokeToken(String, String),
    RemoveProfile(String),
    /// The name of the topic.
    DeleteTopic(String),
    /// Throws away every message of the topic, on every node.
    Prune(String),
}

impl Pending {
    /// The API call the action makes; removing a profile only touches the file, so it has none.
    pub fn call(&self) -> Option<ApiCall> {
        Some(match self {
            Pending::Drain(id) => ApiCall::DrainStart(id.clone()),
            Pending::Return(id) => ApiCall::DrainCancel(id.clone()),
            Pending::FlushNode(id) => ApiCall::FlushNode(id.clone()),
            Pending::FlushAll => ApiCall::FlushCluster,
            Pending::Stop => ApiCall::StopCluster,
            Pending::RevokeToken(id, _) => ApiCall::TokenRevoke(id.clone()),
            Pending::DeleteTopic(name) => ApiCall::TopicDelete(name.clone()),
            Pending::Prune(name) => ApiCall::Prune(name.clone()),
            Pending::RemoveProfile(_) => return None,
        })
    }
}

/// A popup that asks to be typed to proceed (stopping the cluster).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Typed {
    pub expected: String,
    pub input: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Confirm {
    pub pending: Pending,
    pub typed: Option<Typed>,
    /// The default is always **Cancel** (TUI-FRM-07).
    pub ok_focused: bool,
}

/// The result of an action, shown in a popup.
#[derive(Debug, Clone, PartialEq)]
pub enum Report {
    Flush(FlushReport),
    Stop(StopReport),
    Failure { call: ApiCall, fail: Fail },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputPurpose {
    ExportCsv {
        node: String,
        series: usize,
    },
    /// The part of a token name the Tokens tab filters by.
    TokenFilter,
    /// The part of a topic name the Topics tab filters by.
    TopicFilter,
    /// The file the charts of a queue are written to (every line of the three charts).
    ExportTopicCsv,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Input {
    pub purpose: InputPurpose,
    pub value: String,
}

/// What `Enter` opens on an item of a list: the title names the item, and each entry is an action of the screen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Menu {
    pub title: String,
    pub items: Vec<crate::tui::keymap::Action>,
    pub selected: usize,
}

/// One popup at a time (TUI-FRM-07); `Esc` closes it.
#[derive(Debug, Clone, PartialEq)]
pub enum Modal {
    /// The actions of the selected item (`Enter` on a list).
    Menu(Menu),
    /// The summary of the selected topic: its numbers, limits and tags.
    TopicSummary,
    /// The selected message of the Messages view, open: its body and what can still be done to it.
    Message,
    Help {
        scroll: u16,
    },
    Palette {
        query: String,
        selected: usize,
    },
    Language {
        selected: usize,
    },
    Confirm(Confirm),
    Report(Report),
    Input(Input),
    /// What a condition means and what to do (`Enter` on a condition).
    Condition(String),
    /// Which profile to connect with.
    Profiles {
        selected: usize,
    },
    /// A form: a token or a profile.
    Editor(Editor),
    /// The secret of a token that was just created.
    Secret(Secret),
}

/// The secret of a new token, shown once (TUI-TOK-03). It lives only in this popup: never in a notice, a log or an error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Secret {
    pub id: String,
    pub name: String,
    pub token: String,
    /// When it was shown (ms since the app opened); after 30 s it is masked.
    pub shown_at: u64,
    pub copied: bool,
    pub saved: bool,
    /// The person tried to close it without copying or saving it.
    pub warned: bool,
    /// The token this one replaces (a clone), and whether it is to be revoked on closing (default: no).
    pub replaces: Option<(String, String)>,
    pub revoke_old: bool,
}

/// A short message in the footer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notice {
    pub severity: Severity,
    pub text: String,
    pub until: u64,
}

/// What the drain watch is waiting for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Goal {
    Drained,
    Active,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DrainWatch {
    pub node: String,
    pub goal: Goal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClusterView {
    List,
    Detail,
    Monitor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    Conditions,
    Nodes,
}

/// The windows of a chart, in minutes (TUI-MON-03).
pub const WINDOWS_MIN: [u64; 5] = [1, 5, 15, 30, 60];

#[derive(Debug, Clone, PartialEq)]
pub struct Monitor {
    /// The chart being shown, an index of `screens::cluster::MON_CHARTS`.
    pub chart: usize,
    pub window: usize,
    /// The instant the chart was frozen at (`Space`).
    pub frozen: Option<u64>,
    /// `true`: the scale starts at zero and ends at the largest value ever seen; `false`: it follows the window.
    pub fixed_scale: bool,
    /// The chart fills the whole screen (`Enter`) instead of sitting next to the list of charts.
    pub full: bool,
}

impl Default for Monitor {
    fn default() -> Monitor {
        Monitor {
            chart: 0,
            window: 1,
            frozen: None,
            fixed_scale: false,
            full: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ClusterScreen {
    pub view: ClusterView,
    pub pane: Pane,
    pub condition: usize,
    /// The selected node; kept by id so a reordering does not move the selection.
    pub node: Option<String>,
    pub scroll: u16,
    pub monitor: Monitor,
    pub nodes: Feed<Nodes>,
    pub metrics: Feed<Metrics>,
    pub backup: Feed<Option<Backup>>,
    pub drain: Feed<Drain>,
    pub watch: Option<DrainWatch>,
}

impl Default for ClusterScreen {
    fn default() -> ClusterScreen {
        ClusterScreen {
            view: ClusterView::List,
            pane: Pane::Nodes,
            condition: 0,
            node: None,
            scroll: 0,
            monitor: Monitor::default(),
            nodes: Feed::default(),
            metrics: Feed::default(),
            backup: Feed::default(),
            drain: Feed::default(),
            watch: None,
        }
    }
}

/// How the tokens are ordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenSort {
    NewestFirst,
    OldestFirst,
    Name,
    Id,
}

impl TokenSort {
    pub fn next(self) -> TokenSort {
        match self {
            TokenSort::NewestFirst => TokenSort::OldestFirst,
            TokenSort::OldestFirst => TokenSort::Name,
            TokenSort::Name => TokenSort::Id,
            TokenSort::Id => TokenSort::NewestFirst,
        }
    }

    pub fn key(self) -> &'static str {
        match self {
            TokenSort::NewestFirst => "sort.newest",
            TokenSort::OldestFirst => "sort.oldest",
            TokenSort::Name => "sort.name",
            TokenSort::Id => "sort.id",
        }
    }
}

/// The Tokens tab (doc 34, section 6.5).
#[derive(Debug, Clone, PartialEq)]
pub struct TokensScreen {
    /// Every token the server has, read page by page.
    pub list: Feed<Vec<Token>>,
    /// The tokens of the pages read so far while a read still goes on.
    pub reading: Vec<Token>,
    pub pages: u32,
    /// The selected token, by id.
    pub selected: Option<String>,
    pub filter: String,
    pub sort: TokenSort,
}

impl Default for TokensScreen {
    fn default() -> TokensScreen {
        TokensScreen {
            list: Feed::default(),
            reading: Vec::new(),
            pages: 0,
            selected: None,
            filter: String::new(),
            sort: TokenSort::NewestFirst,
        }
    }
}

/// How the topics are ordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TopicSort {
    Name,
    Newest,
    Oldest,
    Depth,
}

impl TopicSort {
    pub fn next(self) -> TopicSort {
        match self {
            TopicSort::Name => TopicSort::Newest,
            TopicSort::Newest => TopicSort::Oldest,
            TopicSort::Oldest => TopicSort::Depth,
            TopicSort::Depth => TopicSort::Name,
        }
    }

    pub fn key(self) -> &'static str {
        match self {
            TopicSort::Name => "sort.name",
            TopicSort::Newest => "sort.newest",
            TopicSort::Oldest => "sort.oldest",
            TopicSort::Depth => "sort.depth",
        }
    }
}

/// The numbers of the topics, by name, and whether the read was incomplete.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TopicStats {
    pub by_name: std::collections::HashMap<String, TopicNumbers>,
    pub partial: bool,
    pub missing: Vec<Missing>,
}

/// The views of an open topic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TopicTab {
    Charts,
    Messages,
}

/// A message this session received (TUI-MSG-04): the API does not list a queue, so these rows are what was read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Received {
    pub id: String,
    pub group: Option<String>,
    pub deliveries: u64,
    pub size: usize,
    pub content_type: String,
    /// The body as text (lossy for bytes that are not UTF-8).
    pub body: String,
    /// The first bytes of the body as they came, for the formatted and the base64 views.
    pub raw: Vec<u8>,
    pub receipt: String,
    /// When it was received (ms since the app opened).
    pub at: u64,
    /// When it turns visible again (ms since the app opened), while it is held.
    pub held_until: Option<u64>,
    /// Acknowledged: it is gone from the queue.
    pub acked: bool,
}

/// The most received messages kept.
pub const MAX_RECEIVED: usize = 1000;

/// How the body of an open message is shown: as sent (the default), formatted, or as base64.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BodyView {
    #[default]
    Sent,
    Formatted,
    Base64,
}

/// What the Messages view of a topic holds.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Messages {
    /// Newest first.
    pub rows: Vec<Received>,
    pub selected: usize,
    /// How the body of an open message is shown.
    pub view: BodyView,
    /// What the last publish, receive or prune said (severity, text).
    pub last: Option<(Severity, String)>,
}

/// The charts of one queue (TUI-MSG-11, TUI-MON-*): what was sampled since they were opened.
#[derive(Debug, Clone, PartialEq)]
pub struct TopicMonitor {
    pub name: String,
    pub tab: TopicTab,
    /// A distributor has no queue: no numbers, no charts, nothing to receive.
    pub distributor: bool,
    pub dead_letter: bool,
    pub messages: Messages,
    /// The window, the freeze and the scale, as in the charts of a node.
    pub monitor: Monitor,
    /// The reading on a schedule; its data is unused, the samples go to `series`.
    pub feed: Feed<()>,
    /// One ring per line: `visible`, `invisible`, `published`, `consumed`, `acked`, `oldest` and `g:<group>`.
    pub series: std::collections::HashMap<String, crate::tui::history::Ring>,
    /// The groups charted, in the order they first showed up (at most three), so their colors stay.
    pub groups: Vec<String>,
}

impl TopicMonitor {
    /// A monitor with nothing sampled yet.
    pub fn new(name: String, tab: TopicTab, distributor: bool, dead_letter: bool) -> TopicMonitor {
        TopicMonitor {
            name,
            tab,
            distributor,
            dead_letter,
            messages: Messages::default(),
            monitor: Monitor::default(),
            feed: Feed::default(),
            series: std::collections::HashMap::new(),
            groups: Vec::new(),
        }
    }
}

/// The Topics tab (doc 34, section 6.4).
#[derive(Debug, Clone, PartialEq)]
pub struct TopicsScreen {
    /// The strip of charts under the list: what was sampled of the topics that were selected lately (the most
    /// recent last), so going back to one does not start its charts over.
    pub previews: Vec<TopicMonitor>,
    /// Show the dead-letter queues too; off by default (they follow their source queue).
    pub show_dead: bool,
    /// The charts of the queue being looked at (`Enter`), or none while the list is shown.
    pub monitor: Option<TopicMonitor>,
    /// Every topic the server lists, read page by page.
    pub list: Feed<Vec<Topic>>,
    pub reading: Vec<Topic>,
    pub pages: u32,
    /// Their numbers (depth, rates, age, condition), read the same way; a failure leaves the table without them.
    pub stats: Feed<TopicStats>,
    pub stats_reading: TopicStats,
    pub stats_pages: u32,
    /// The selected topic, by name.
    pub selected: Option<String>,
    pub filter: String,
    pub sort: TopicSort,
}

impl Default for TopicsScreen {
    fn default() -> TopicsScreen {
        TopicsScreen {
            show_dead: false,
            previews: Vec::new(),
            monitor: None,
            list: Feed::default(),
            reading: Vec::new(),
            pages: 0,
            stats: Feed::default(),
            stats_reading: TopicStats::default(),
            stats_pages: 0,
            selected: None,
            filter: String::new(),
            sort: TopicSort::Name,
        }
    }
}

/// The Profiles tab (doc 34, section 6.7): the profiles file and the selected profile.
#[derive(Debug, Clone, PartialEq)]
pub struct ProfilesScreen {
    pub file: ConfigFile,
    pub selected: Option<String>,
}

pub struct Model {
    pub lang: Lang,
    pub theme: Theme,
    pub profile: String,
    pub url: String,
    pub tab: Tab,
    pub size: (u16, u16),
    /// Milliseconds since the app opened, from the last tick.
    pub now: u64,
    /// The wall clock at the last tick (ms since the epoch, UTC).
    pub wall_ms: i64,
    pub paused: bool,
    /// `false` while the terminal does not have the focus.
    pub focused: bool,
    pub quit: bool,
    pub modal: Option<Modal>,
    pub notice: Option<Notice>,
    /// An action that is running (its reply has not come).
    pub busy: Option<ApiCall>,
    pub me: Feed<Me>,
    pub status: Feed<ClusterStatus>,
    /// `GET /cluster/status` answered `401`/`403` for this token: the screen falls back to `GET /nodes`.
    pub status_denied: Option<Fail>,
    pub cluster: ClusterScreen,
    pub tokens: TokensScreen,
    pub topics: TopicsScreen,
    pub profiles: ProfilesScreen,
    /// Waiting for the person to choose a profile: nothing is read until then.
    pub awaiting_profile: bool,
    pub history: History,
    pub next_id: u64,
    /// Bumped when the screens are reset; a reply of an older generation is dropped.
    pub generation: u64,
}

impl Model {
    pub fn new(options: Options) -> Model {
        // With one profile (or none) there is nothing to choose.
        let choose = options.choose_profile && options.profiles.profiles.len() > 1;
        // With none, the form for the first one opens at once.
        let create = options.choose_profile && options.profiles.profiles.is_empty();
        let first = choose.then(|| {
            let file = &options.profiles;
            let selected = file
                .default
                .as_ref()
                .and_then(|name| file.profiles.iter().position(|(n, _)| n == name))
                .unwrap_or(0);
            Modal::Profiles { selected }
        });
        let mut model = Model {
            lang: options.lang,
            theme: options.theme,
            profile: options.profile,
            url: options.url,
            tab: Tab::Cluster,
            size: (80, 24),
            now: 0,
            wall_ms: 0,
            paused: false,
            focused: true,
            quit: false,
            modal: first,
            notice: None,
            busy: None,
            me: Feed::default(),
            status: Feed::default(),
            status_denied: None,
            cluster: ClusterScreen::default(),
            tokens: TokensScreen::default(),
            topics: TopicsScreen::default(),
            profiles: ProfilesScreen {
                selected: options.profiles.default.clone(),
                file: options.profiles,
            },
            awaiting_profile: choose || create,
            history: History::new(options.retention_secs, options.interval_secs),
            next_id: 1,
            generation: 0,
        };
        if create {
            crate::tui::screens::profiles::open_form(&mut model, None);
        }
        model
    }

    /// Starts over with another profile: what was read from the old server is dropped, and so is any reply still
    /// on its way (its generation is old).
    pub fn reconnect(&mut self, profile: String, url: String) {
        self.profile = profile;
        self.url = url;
        self.generation += 1;
        self.awaiting_profile = false;
        self.busy = None;
        self.me = Feed::default();
        self.status = Feed::default();
        self.status_denied = None;
        self.cluster = ClusterScreen::default();
        self.tokens = TokensScreen::default();
        self.topics = TopicsScreen::default();
        let retention = self.history.retention_ms() / 1000;
        let interval = self.history.interval_ms() / 1000;
        self.history = History::new(retention, interval);
    }

    pub fn id(&mut self) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    pub fn tx(&self) -> Tx {
        Tx(self.lang)
    }

    /// `true` when this token may read the cluster's detail and manage the tokens (root, no authentication, or the
    /// `admin` permission).
    pub fn is_admin(&self) -> bool {
        self.me.data.as_ref().is_some_and(Me::is_admin)
    }

    /// `true` for the root token (or no authentication): stopping the cluster and the `admin` tokens are its alone.
    pub fn is_root(&self) -> bool {
        self.me.data.as_ref().is_some_and(Me::is_root)
    }

    /// The cluster-wide status is read with this token.
    pub fn uses_status(&self) -> bool {
        self.is_admin() && self.status_denied.is_none()
    }

    /// Any feed that ended in a connection failure: the server cannot be reached.
    pub fn is_offline(&self) -> bool {
        let feeds = [
            self.me.error.as_ref(),
            self.status.error.as_ref(),
            self.cluster.nodes.error.as_ref(),
        ];
        feeds.into_iter().flatten().any(Fail::is_offline)
    }

    /// The worst condition for the status line: its severity and the word (a condition name, or a state key).
    pub fn health(&self) -> (Severity, String) {
        if self.is_offline() {
            return (Severity::Critical, "offline".to_owned());
        }
        if let Some(status) = &self.status.data {
            let severity = status
                .conditions
                .iter()
                .map(|c| c.severity)
                .max()
                .unwrap_or(Severity::Ok);
            let word = if status.worst.is_empty() {
                "ok"
            } else {
                &status.worst
            };
            return (severity, word.to_owned());
        }
        if let Some(nodes) = &self.cluster.nodes.data {
            let bad = nodes
                .items
                .iter()
                .any(|n| !n.reachable || !matches!(n.state.as_str(), "active" | ""));
            if bad || nodes.partial {
                return (Severity::Warning, "degraded".to_owned());
            }
            return (Severity::Ok, "ok".to_owned());
        }
        (Severity::Ok, "unknown".to_owned())
    }

    pub fn notify(&mut self, severity: Severity, text: String) {
        self.notice = Some(Notice {
            severity,
            text,
            until: self.now + 5000,
        });
    }
}

/// The catalog in a language: the views and the update ask it for their texts.
#[derive(Debug, Clone, Copy)]
pub struct Tx(pub Lang);

impl Tx {
    pub fn t(self, key: &str) -> String {
        i18n::tr(self.0, key)
    }

    pub fn tw(self, key: &str, args: &[(&str, &dyn std::fmt::Display)]) -> String {
        i18n::tr_with(self.0, key, args)
    }

    pub fn tn(self, key: &str, n: u64) -> String {
        i18n::tr_n(self.0, key, n)
    }
}

#[cfg(test)]
mod tests;