Skip to main content

vcon_server/tui/
state.rs

1//! The terminal UI's state machine: a state and an event give the next
2//! state and the requests to make. It draws nothing, reads no clock and
3//! calls no server, so every transition can be tested as a value.
4
5use std::fmt;
6
7use serde::Deserialize;
8use time::OffsetDateTime;
9
10/// What `GET /key` answers: the key in use.
11#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12pub struct KeyInfo {
13    /// The key's id. Not the token: an id opens nothing.
14    pub id: String,
15    /// The key's tenant; `None` for an operator key.
16    pub tenant: Option<String>,
17    /// The scopes the key holds.
18    pub scopes: Vec<String>,
19}
20
21/// One vCon of a `GET /vcons` page: the metadata the API lists.
22#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
23pub struct Row {
24    /// The vCon's uuid.
25    pub uuid: String,
26    /// When the uuid was first stored, RFC 3339 in UTC.
27    pub stored_at: String,
28    /// When the current version was stored, RFC 3339 in UTC.
29    pub updated_at: String,
30    /// The current version: the `ETag` without quotes.
31    pub version: String,
32}
33
34/// One page of `GET /vcons`.
35#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
36pub struct Page {
37    /// The page's vCons, newest first.
38    pub vcons: Vec<Row>,
39    /// The cursor of the next page; `None` on the last.
40    pub next: Option<String>,
41}
42
43/// Why a request gave no answer to show. None of these holds the token.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum ApiError {
46    /// No answer arrived: the address, TLS or the network.
47    Unreachable(String),
48    /// The client refused the server's certificate, so no request was
49    /// sent: what is wrong with it and what to do.
50    Untrusted(String),
51    /// The server answered this status, with the problem's title if it
52    /// sent one.
53    Status(u16, Option<String>),
54    /// The answer was not the JSON the API describes.
55    Malformed(String),
56}
57
58impl std::error::Error for ApiError {}
59
60impl fmt::Display for ApiError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            ApiError::Unreachable(why) => write!(f, "the server did not answer: {why}"),
64            ApiError::Untrusted(why) => {
65                write!(f, "the server's certificate was refused: {why}")
66            }
67            ApiError::Status(401, _) => f.write_str("the server refused the key (401)"),
68            ApiError::Status(status, Some(title)) => {
69                write!(f, "the server answered {status} ({title})")
70            }
71            ApiError::Status(status, None) => write!(f, "the server answered {status}"),
72            ApiError::Malformed(why) => {
73                write!(f, "the server's answer could not be read: {why}")
74            }
75        }
76    }
77}
78
79/// Whether the server has answered for the key.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum Connection {
82    /// `GET /key` is in flight.
83    Connecting,
84    /// The server answered for this key.
85    Connected(KeyInfo),
86    /// The server did not answer, or refused the key; why.
87    Failed(String),
88}
89
90/// The state of the list of vCons.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Listing {
93    /// The first page is in flight.
94    Loading,
95    /// The rows are what the server last answered.
96    Ready,
97    /// There is no list to show; why.
98    Failed(String),
99}
100
101/// Which view is drawn.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum View {
104    /// The tenant's vCons.
105    List,
106    /// One vCon's metadata.
107    Detail,
108    /// The key bindings.
109    Help,
110}
111
112/// What a key press asks for.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Action {
115    /// Select the row above.
116    Up,
117    /// Select the row below.
118    Down,
119    /// Select the first row.
120    Top,
121    /// Select the last row.
122    Bottom,
123    /// Move up by the rows on screen.
124    PageUp,
125    /// Move down by the rows on screen.
126    PageDown,
127    /// Open the selected vCon.
128    Open,
129    /// Leave the detail or help view.
130    Back,
131    /// Read the list again from the server.
132    Refresh,
133    /// Read the next page.
134    More,
135    /// Open or close help.
136    Help,
137    /// End the program.
138    Quit,
139}
140
141/// What happened.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum Event {
144    /// A key press, as its action.
145    Action(Action),
146    /// The terminal is now this many columns and lines.
147    Resize(u16, u16),
148    /// `GET /key` finished.
149    KeyInfo(Result<KeyInfo, ApiError>),
150    /// `GET /vcons` finished.
151    Page(Result<Page, ApiError>),
152}
153
154/// A request for the caller to make; its answer comes back as an [`Event`].
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Effect {
157    /// `GET /key`.
158    FetchKey,
159    /// `GET /vcons`, from this cursor or from the start.
160    FetchPage(Option<String>),
161}
162
163/// The lines a frame takes around the list's rows: the status line, the
164/// column header, a blank line, the notice line and the key hints.
165const FRAME_LINES: u16 = 5;
166
167/// Everything the UI shows. It never holds the token.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct State {
170    /// The server's address, as the client file gives it.
171    pub server: String,
172    /// Whether the server has answered for the key.
173    pub connection: Connection,
174    /// The state of the list.
175    pub listing: Listing,
176    /// The vCons read so far, newest first.
177    pub rows: Vec<Row>,
178    /// The cursor of the next page, if there is one.
179    pub next: Option<String>,
180    /// The selected row's index in `rows`.
181    pub selected: usize,
182    /// The view drawn.
183    pub view: View,
184    /// The view help was opened from.
185    pub behind_help: View,
186    /// The uuid the detail view shows.
187    pub detail: Option<String>,
188    /// Whether a next page is in flight.
189    pub more: bool,
190    /// When the rows were last read from the server.
191    pub as_of: Option<OffsetDateTime>,
192    /// What went wrong with the last request, when the list is still shown.
193    pub notice: Option<String>,
194    /// The terminal's columns and lines.
195    pub size: (u16, u16),
196    /// Whether the program should end.
197    pub quit: bool,
198}
199
200impl State {
201    /// The state at start for the server at `server` in a terminal of
202    /// `size` columns and lines, and the first request.
203    #[must_use]
204    pub fn new(server: &str, size: (u16, u16)) -> (Self, Vec<Effect>) {
205        let state = Self {
206            server: server.to_owned(),
207            connection: Connection::Connecting,
208            listing: Listing::Loading,
209            rows: Vec::new(),
210            next: None,
211            selected: 0,
212            view: View::List,
213            behind_help: View::List,
214            detail: None,
215            more: false,
216            as_of: None,
217            notice: None,
218            size,
219            quit: false,
220        };
221        (state, vec![Effect::FetchKey])
222    }
223
224    /// The rows of the list a terminal of `lines` lines shows: at least 1.
225    #[must_use]
226    pub fn list_rows(lines: u16) -> u16 {
227        lines.saturating_sub(FRAME_LINES).max(1)
228    }
229
230    /// The row the detail view shows, if the list still holds it.
231    #[must_use]
232    pub fn detail_row(&self) -> Option<&Row> {
233        let uuid = self.detail.as_deref()?;
234        self.rows.iter().find(|row| row.uuid == uuid)
235    }
236
237    /// Whether a request is in flight, so another would race it.
238    fn busy(&self) -> bool {
239        self.more
240            || self.connection == Connection::Connecting
241            || (self.listing == Listing::Loading
242                && matches!(self.connection, Connection::Connected(_)))
243    }
244
245    /// Applies `event`, which happened at `now`, and returns the requests
246    /// to make.
247    pub fn step(&mut self, event: Event, now: OffsetDateTime) -> Vec<Effect> {
248        match event {
249            Event::Action(action) => {
250                self.notice = None;
251                self.act(action)
252            }
253            Event::Resize(columns, lines) => {
254                self.size = (columns, lines);
255                Vec::new()
256            }
257            Event::KeyInfo(Ok(info)) => self.connected(info),
258            Event::KeyInfo(Err(error)) => {
259                self.connection = Connection::Failed(error.to_string());
260                self.listing = Listing::Failed(error.to_string());
261                Vec::new()
262            }
263            Event::Page(Ok(page)) => {
264                self.page(page, now);
265                Vec::new()
266            }
267            Event::Page(Err(error)) => {
268                self.page_failed(&error);
269                Vec::new()
270            }
271        }
272    }
273
274    /// The key answered: asks for the first page if the key may list.
275    fn connected(&mut self, info: KeyInfo) -> Vec<Effect> {
276        let refusal = if info.tenant.is_none() {
277            Some(
278                "this is an operator key, which reaches no vCon: use a tenant key with the read scope",
279            )
280        } else if info.scopes.iter().all(|scope| scope != "read") {
281            Some("this key lacks the read scope: use a tenant key that holds it")
282        } else {
283            None
284        };
285        self.connection = Connection::Connected(info);
286        match refusal {
287            Some(why) => {
288                self.listing = Listing::Failed(why.to_owned());
289                Vec::new()
290            }
291            None => {
292                self.listing = Listing::Loading;
293                vec![Effect::FetchPage(None)]
294            }
295        }
296    }
297
298    /// A page arrived: a next page is appended, a first page replaces the
299    /// rows and the selection follows the vCon it was on.
300    fn page(&mut self, page: Page, now: OffsetDateTime) {
301        if self.more {
302            self.rows.extend(page.vcons);
303        } else {
304            let on = self
305                .detail
306                .clone()
307                .or_else(|| self.rows.get(self.selected).map(|row| row.uuid.clone()));
308            self.rows = page.vcons;
309            if let Some(index) =
310                on.and_then(|uuid| self.rows.iter().position(|row| row.uuid == uuid))
311            {
312                self.selected = index;
313            }
314        }
315        self.selected = self.selected.min(self.rows.len().saturating_sub(1));
316        self.next = page.next;
317        self.more = false;
318        self.listing = Listing::Ready;
319        self.as_of = Some(now);
320    }
321
322    /// A page did not arrive: a next page leaves the rows and a notice, a
323    /// first page leaves an error in place of rows that may be out of date.
324    /// A server that did not answer, or that no longer takes the key (401),
325    /// is not connected, as at start, so the next refresh asks for the key
326    /// again.
327    fn page_failed(&mut self, error: &ApiError) {
328        if matches!(
329            error,
330            ApiError::Unreachable(_) | ApiError::Untrusted(_) | ApiError::Status(401, _)
331        ) {
332            self.connection = Connection::Failed(error.to_string());
333        }
334        if self.more {
335            self.more = false;
336            self.notice = Some(format!("The next page was not read: {error}."));
337        } else {
338            self.rows.clear();
339            self.next = None;
340            self.selected = 0;
341            self.as_of = None;
342            self.listing = Listing::Failed(error.to_string());
343        }
344    }
345
346    /// Applies a key press.
347    fn act(&mut self, action: Action) -> Vec<Effect> {
348        match (self.view, action) {
349            (_, Action::Quit) => self.quit = true,
350            (View::Help, Action::Help | Action::Back) => self.view = self.behind_help,
351            (View::Help, _) | (View::List, Action::Back) | (View::Detail, Action::Open) => {}
352            (view, Action::Help) => {
353                self.behind_help = view;
354                self.view = View::Help;
355            }
356            (View::Detail, Action::Back) => self.view = View::List,
357            (_, Action::Refresh) => return self.refresh(),
358            (_, Action::More) => return self.more(),
359            (View::List, Action::Open) => {
360                if let Some(row) = self.rows.get(self.selected) {
361                    self.detail = Some(row.uuid.clone());
362                    self.view = View::Detail;
363                }
364            }
365            (
366                view,
367                Action::Up
368                | Action::Down
369                | Action::Top
370                | Action::Bottom
371                | Action::PageUp
372                | Action::PageDown,
373            ) => {
374                self.travel(action);
375                if view == View::Detail
376                    && let Some(row) = self.rows.get(self.selected)
377                {
378                    self.detail = Some(row.uuid.clone());
379                }
380            }
381        }
382        Vec::new()
383    }
384
385    /// Moves the selection, staying within the rows.
386    fn travel(&mut self, action: Action) {
387        let last = self.rows.len().saturating_sub(1);
388        let page = usize::from(Self::list_rows(self.size.1));
389        self.selected = match action {
390            Action::Up => self.selected.saturating_sub(1),
391            Action::Down => self.selected.saturating_add(1),
392            Action::Top => 0,
393            Action::Bottom => last,
394            Action::PageUp => self.selected.saturating_sub(page),
395            Action::PageDown => self.selected.saturating_add(page),
396            _ => self.selected,
397        }
398        .min(last);
399    }
400
401    /// Reads from the start again: the key first if the server had not
402    /// answered for it, the first page otherwise.
403    fn refresh(&mut self) -> Vec<Effect> {
404        if self.busy() {
405            return Vec::new();
406        }
407        if let Connection::Connected(info) = &self.connection {
408            return self.connected(info.clone());
409        }
410        self.connection = Connection::Connecting;
411        self.listing = Listing::Loading;
412        vec![Effect::FetchKey]
413    }
414
415    /// Reads the next page, if there is one and nothing is in flight.
416    fn more(&mut self) -> Vec<Effect> {
417        if self.busy() || self.listing != Listing::Ready {
418            return Vec::new();
419        }
420        let Some(cursor) = self.next.clone() else {
421            return Vec::new();
422        };
423        self.more = true;
424        vec![Effect::FetchPage(Some(cursor))]
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use time::OffsetDateTime;
431    use time::macros::datetime;
432
433    use super::{
434        Action, ApiError, Connection, Effect, Event, KeyInfo, Listing, Page, Row, State, View,
435    };
436
437    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
438
439    fn row(n: u8) -> Row {
440        Row {
441            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
442            stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
443            updated_at: "2026-10-25T12:30:00Z".to_owned(),
444            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
445        }
446    }
447
448    fn reader() -> KeyInfo {
449        KeyInfo {
450            id: "0123456789abcdef".to_owned(),
451            tenant: Some("t_example".to_owned()),
452            scopes: vec!["read".to_owned()],
453        }
454    }
455
456    fn page(rows: std::ops::Range<u8>, next: Option<&str>) -> Page {
457        Page {
458            vcons: rows.map(row).collect(),
459            next: next.map(str::to_owned),
460        }
461    }
462
463    /// A state that is connected and holds `rows` rows of one page.
464    fn listed(rows: u8, next: Option<&str>) -> State {
465        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
466        state.step(Event::KeyInfo(Ok(reader())), NOW);
467        state.step(Event::Page(Ok(page(0..rows, next))), NOW);
468        state
469    }
470
471    fn press(state: &mut State, action: Action) -> Vec<Effect> {
472        state.step(Event::Action(action), NOW)
473    }
474
475    // Success.
476
477    #[test]
478    fn a_new_state_is_connecting_and_asks_for_the_key() {
479        let (state, effects) = State::new("https://vcon.example.com:8443", (80, 24));
480        assert_eq!(
481            state.connection,
482            Connection::Connecting,
483            "nothing has answered yet"
484        );
485        assert_eq!(
486            effects,
487            [Effect::FetchKey],
488            "the key's tenant and scopes come first"
489        );
490    }
491
492    #[test]
493    fn a_reader_key_connects_and_asks_for_the_first_page() {
494        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
495        let effects = state.step(Event::KeyInfo(Ok(reader())), NOW);
496        assert_eq!(
497            state.connection,
498            Connection::Connected(reader()),
499            "the key answered"
500        );
501        assert_eq!(state.listing, Listing::Loading, "the page is on its way");
502        assert_eq!(
503            effects,
504            [Effect::FetchPage(None)],
505            "the first page has no cursor"
506        );
507    }
508
509    #[test]
510    fn a_page_fills_the_list_and_records_when() {
511        let state = listed(3, Some("cursor-1"));
512        assert_eq!(state.listing, Listing::Ready, "the page arrived");
513        assert_eq!(state.rows.len(), 3, "every row of the page is kept");
514        assert_eq!(
515            state.next.as_deref(),
516            Some("cursor-1"),
517            "the cursor is kept for more"
518        );
519        assert_eq!(
520            state.as_of,
521            Some(NOW),
522            "the clock passed in is when it was read"
523        );
524    }
525
526    #[test]
527    fn down_and_up_move_the_selection() {
528        let mut state = listed(3, None);
529        press(&mut state, Action::Down);
530        press(&mut state, Action::Down);
531        assert_eq!(state.selected, 2, "two rows down");
532        press(&mut state, Action::Up);
533        assert_eq!(state.selected, 1, "one row back up");
534    }
535
536    #[test]
537    fn bottom_and_top_jump_to_the_ends() {
538        let mut state = listed(5, None);
539        press(&mut state, Action::Bottom);
540        assert_eq!(state.selected, 4, "the last row");
541        press(&mut state, Action::Top);
542        assert_eq!(state.selected, 0, "the first row");
543    }
544
545    #[test]
546    fn open_shows_the_selected_vcon_and_back_returns() {
547        let mut state = listed(3, None);
548        press(&mut state, Action::Down);
549        let effects = press(&mut state, Action::Open);
550        assert_eq!(state.view, View::Detail, "the detail view is open");
551        assert_eq!(
552            state.detail,
553            Some(row(1).uuid),
554            "on the row that was selected"
555        );
556        assert_eq!(
557            effects,
558            [],
559            "the detail is drawn from the list row: no request"
560        );
561        press(&mut state, Action::Back);
562        assert_eq!(state.view, View::List, "back at the list");
563    }
564
565    #[test]
566    fn more_asks_for_the_next_page_and_appends_it() {
567        let mut state = listed(2, Some("cursor-1"));
568        let effects = press(&mut state, Action::More);
569        assert_eq!(
570            effects,
571            [Effect::FetchPage(Some("cursor-1".to_owned()))],
572            "the cursor goes back unchanged"
573        );
574        state.step(Event::Page(Ok(page(2..4, None))), NOW);
575        assert_eq!(state.rows.len(), 4, "the second page follows the first");
576        assert_eq!(state.next, None, "the last page has no cursor");
577    }
578
579    #[test]
580    fn refresh_asks_for_the_first_page_again_and_replaces_the_rows() {
581        let mut state = listed(3, None);
582        let effects = press(&mut state, Action::Refresh);
583        assert_eq!(effects, [Effect::FetchPage(None)], "from the start");
584        assert_eq!(
585            state.listing,
586            Listing::Loading,
587            "loading is shown meanwhile"
588        );
589        state.step(Event::Page(Ok(page(0..1, None))), NOW);
590        assert_eq!(state.rows.len(), 1, "the new page replaces the old rows");
591    }
592
593    #[test]
594    fn help_opens_over_a_view_and_returns_to_it() {
595        let mut state = listed(3, None);
596        press(&mut state, Action::Open);
597        press(&mut state, Action::Help);
598        assert_eq!(state.view, View::Help, "help is open");
599        press(&mut state, Action::Back);
600        assert_eq!(
601            state.view,
602            View::Detail,
603            "back at the view help was opened from"
604        );
605    }
606
607    #[test]
608    fn quit_ends_from_every_view() {
609        for open in [None, Some(Action::Open), Some(Action::Help)] {
610            let mut state = listed(1, None);
611            if let Some(open) = open {
612                press(&mut state, open);
613            }
614            press(&mut state, Action::Quit);
615            assert!(state.quit, "quit ends from {:?}", state.view);
616        }
617    }
618
619    #[test]
620    fn page_down_moves_by_the_rows_the_terminal_shows() {
621        let mut state = listed(60, None);
622        press(&mut state, Action::PageDown);
623        assert_eq!(
624            state.selected,
625            usize::from(State::list_rows(24)),
626            "a 24-line terminal pages by its list rows"
627        );
628        press(&mut state, Action::PageUp);
629        assert_eq!(state.selected, 0, "and back");
630    }
631
632    #[test]
633    fn down_in_the_detail_view_shows_the_next_vcon() {
634        let mut state = listed(3, None);
635        press(&mut state, Action::Open);
636        press(&mut state, Action::Down);
637        assert_eq!(
638            state.detail,
639            Some(row(1).uuid),
640            "the detail follows the selection"
641        );
642    }
643
644    #[test]
645    fn a_refresh_keeps_the_selection_on_the_same_vcon() {
646        let mut state = listed(3, None);
647        press(&mut state, Action::Bottom);
648        press(&mut state, Action::Open);
649        press(&mut state, Action::Refresh);
650        state.step(Event::Page(Ok(page(1..3, None))), NOW);
651        assert_eq!(
652            state.selected, 1,
653            "the vCon moved up one row and the selection with it"
654        );
655        assert_eq!(
656            state.detail,
657            Some(row(2).uuid),
658            "the detail is still that vCon"
659        );
660    }
661
662    // Failure.
663
664    #[test]
665    fn an_unreachable_server_fails_the_connection_and_the_list() {
666        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
667        let effects = state.step(
668            Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
669            NOW,
670        );
671        assert_eq!(
672            effects,
673            [],
674            "nothing more is asked of a server that did not answer"
675        );
676        assert!(
677            matches!(&state.connection, Connection::Failed(why) if why.contains("connection refused")),
678            "the status line says why: {:?}",
679            state.connection
680        );
681        assert!(
682            matches!(state.listing, Listing::Failed(_)),
683            "the list says so too"
684        );
685    }
686
687    #[test]
688    fn a_refused_key_says_the_status() {
689        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
690        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
691        assert!(
692            matches!(&state.connection, Connection::Failed(why) if why.contains("401")),
693            "the refusal's status is shown: {:?}",
694            state.connection
695        );
696    }
697
698    #[test]
699    fn an_operator_key_connects_but_lists_nothing() {
700        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
701        let operator = KeyInfo {
702            id: "0123456789abcdef".to_owned(),
703            tenant: None,
704            scopes: vec!["admin".to_owned()],
705        };
706        let effects = state.step(Event::KeyInfo(Ok(operator)), NOW);
707        assert_eq!(
708            effects,
709            [],
710            "an operator key reaches no vCon, so none is asked for"
711        );
712        assert!(
713            matches!(&state.listing, Listing::Failed(why) if why.contains("operator key")),
714            "the list says which key to use: {:?}",
715            state.listing
716        );
717    }
718
719    #[test]
720    fn a_key_without_read_lists_nothing() {
721        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
722        let writer = KeyInfo {
723            scopes: vec!["write".to_owned()],
724            ..reader()
725        };
726        let effects = state.step(Event::KeyInfo(Ok(writer)), NOW);
727        assert_eq!(effects, [], "the list needs read, so it is not asked for");
728        assert!(
729            matches!(&state.listing, Listing::Failed(why) if why.contains("read scope")),
730            "the list names the scope: {:?}",
731            state.listing
732        );
733    }
734
735    #[test]
736    fn a_failed_first_page_is_an_error_state() {
737        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
738        state.step(Event::KeyInfo(Ok(reader())), NOW);
739        state.step(
740            Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
741            NOW,
742        );
743        assert!(
744            matches!(&state.listing, Listing::Failed(why) if why.contains("503") && why.contains("unavailable")),
745            "the status and the problem's title are shown: {:?}",
746            state.listing
747        );
748        assert_eq!(state.as_of, None, "nothing was read, so no time is claimed");
749    }
750
751    #[test]
752    fn a_failed_next_page_keeps_the_rows_and_leaves_a_notice() {
753        let mut state = listed(2, Some("cursor-1"));
754        press(&mut state, Action::More);
755        state.step(
756            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
757            NOW,
758        );
759        assert_eq!(state.rows.len(), 2, "the rows already read stay");
760        assert_eq!(state.listing, Listing::Ready, "the list is still usable");
761        assert_eq!(
762            state.next.as_deref(),
763            Some("cursor-1"),
764            "the cursor is kept to try again"
765        );
766        assert!(
767            state
768                .notice
769                .as_deref()
770                .is_some_and(|n| n.contains("timed out")),
771            "a notice says why: {:?}",
772            state.notice
773        );
774    }
775
776    #[test]
777    fn a_failed_refresh_drops_the_old_rows() {
778        let mut state = listed(2, None);
779        press(&mut state, Action::Refresh);
780        state.step(Event::Page(Err(ApiError::Status(500, None))), NOW);
781        assert!(
782            matches!(state.listing, Listing::Failed(_)),
783            "the error is shown"
784        );
785        assert_eq!(
786            state.rows,
787            [],
788            "rows that may be out of date are not shown as current"
789        );
790    }
791
792    #[test]
793    fn a_malformed_answer_is_an_error_state() {
794        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
795        state.step(Event::KeyInfo(Ok(reader())), NOW);
796        state.step(
797            Event::Page(Err(ApiError::Malformed("expected value".to_owned()))),
798            NOW,
799        );
800        assert!(
801            matches!(&state.listing, Listing::Failed(why) if why.contains("expected value")),
802            "what could not be read is shown: {:?}",
803            state.listing
804        );
805    }
806
807    #[test]
808    fn refresh_after_a_failed_connection_asks_for_the_key_again() {
809        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
810        state.step(
811            Event::KeyInfo(Err(ApiError::Unreachable("refused".to_owned()))),
812            NOW,
813        );
814        let effects = press(&mut state, Action::Refresh);
815        assert_eq!(
816            effects,
817            [Effect::FetchKey],
818            "the connection is made again from the start"
819        );
820        assert_eq!(
821            state.connection,
822            Connection::Connecting,
823            "and shown as such"
824        );
825    }
826
827    #[test]
828    fn a_server_that_stops_answering_is_shown_as_not_connected() {
829        let mut state = listed(2, None);
830        press(&mut state, Action::Refresh);
831        state.step(
832            Event::Page(Err(ApiError::Unreachable("connection reset".to_owned()))),
833            NOW,
834        );
835        assert!(
836            matches!(state.connection, Connection::Failed(_)),
837            "the status line no longer says connected"
838        );
839    }
840
841    #[test]
842    fn a_vcon_gone_after_a_refresh_leaves_the_detail_without_a_row() {
843        let mut state = listed(2, None);
844        press(&mut state, Action::Open);
845        press(&mut state, Action::Refresh);
846        state.step(Event::Page(Ok(page(1..2, None))), NOW);
847        assert_eq!(
848            state.detail,
849            Some(row(0).uuid),
850            "the detail still names what was open"
851        );
852        assert_eq!(state.detail_row(), None, "and has no row to draw");
853    }
854
855    #[test]
856    fn each_api_error_says_what_failed() {
857        for (error, text) in [
858            (
859                ApiError::Unreachable("refused".to_owned()),
860                "the server did not answer: refused",
861            ),
862            (
863                ApiError::Status(401, None),
864                "the server refused the key (401)",
865            ),
866            (
867                ApiError::Status(403, Some("forbidden".to_owned())),
868                "the server answered 403 (forbidden)",
869            ),
870            (ApiError::Status(500, None), "the server answered 500"),
871            (
872                ApiError::Malformed("eof".to_owned()),
873                "the server's answer could not be read: eof",
874            ),
875        ] {
876            assert_eq!(error.to_string(), text, "{error:?}");
877        }
878    }
879
880    // Edge.
881
882    #[test]
883    fn up_at_the_top_and_down_at_the_bottom_stay() {
884        let mut state = listed(2, None);
885        press(&mut state, Action::Up);
886        assert_eq!(state.selected, 0, "no row above the first");
887        press(&mut state, Action::Bottom);
888        press(&mut state, Action::Down);
889        assert_eq!(state.selected, 1, "no row below the last");
890    }
891
892    #[test]
893    fn open_on_an_empty_list_does_nothing() {
894        let mut state = listed(0, None);
895        press(&mut state, Action::Open);
896        assert_eq!(state.view, View::List, "there is nothing to open");
897        assert_eq!(state.detail, None, "and no vCon is named");
898    }
899
900    #[test]
901    fn movement_on_an_empty_list_stays_at_zero() {
902        let mut state = listed(0, None);
903        for action in [Action::Down, Action::Bottom, Action::PageDown, Action::Up] {
904            press(&mut state, action);
905            assert_eq!(state.selected, 0, "{action:?} on no rows");
906        }
907    }
908
909    #[test]
910    fn more_on_the_last_page_asks_for_nothing() {
911        let mut state = listed(2, None);
912        assert_eq!(press(&mut state, Action::More), [], "there is no next page");
913    }
914
915    #[test]
916    fn a_second_refresh_while_loading_asks_for_nothing() {
917        let mut state = listed(2, None);
918        press(&mut state, Action::Refresh);
919        assert_eq!(
920            press(&mut state, Action::Refresh),
921            [],
922            "one request is in flight; a second would race it"
923        );
924    }
925
926    #[test]
927    fn more_while_more_is_loading_asks_for_nothing() {
928        let mut state = listed(2, Some("cursor-1"));
929        press(&mut state, Action::More);
930        assert_eq!(
931            press(&mut state, Action::More),
932            [],
933            "the page is already on its way"
934        );
935        assert_eq!(
936            press(&mut state, Action::Refresh),
937            [],
938            "and a refresh would race it"
939        );
940    }
941
942    #[test]
943    fn refresh_while_connecting_asks_for_nothing() {
944        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
945        assert_eq!(
946            press(&mut state, Action::Refresh),
947            [],
948            "the key request is in flight"
949        );
950    }
951
952    #[test]
953    fn a_resize_changes_only_the_size() {
954        let mut state = listed(3, None);
955        press(&mut state, Action::Down);
956        let before = state.clone();
957        let effects = state.step(Event::Resize(132, 43), NOW);
958        assert_eq!(effects, [], "a resize asks the server nothing");
959        assert_eq!(state.size, (132, 43), "the new size is kept");
960        assert_eq!(
961            State {
962                size: before.size,
963                ..state
964            },
965            before,
966            "nothing else changed"
967        );
968    }
969
970    #[test]
971    fn a_shorter_page_after_refresh_clamps_the_selection() {
972        let mut state = listed(5, None);
973        press(&mut state, Action::Bottom);
974        press(&mut state, Action::Refresh);
975        state.step(Event::Page(Ok(page(10..12, None))), NOW);
976        assert_eq!(
977            state.selected, 1,
978            "the selection is the last row that exists"
979        );
980    }
981
982    #[test]
983    fn page_down_past_the_end_stops_at_the_last_row() {
984        let mut state = listed(3, None);
985        press(&mut state, Action::PageDown);
986        assert_eq!(state.selected, 2, "the last row, not past it");
987    }
988
989    #[test]
990    fn a_terminal_too_short_for_a_list_still_pages_by_one() {
991        assert_eq!(State::list_rows(0), 1, "never zero: paging would not move");
992        assert_eq!(State::list_rows(5), 1, "the frame takes five lines");
993        assert_eq!(State::list_rows(24), 19, "24 lines leave 19 for rows");
994    }
995
996    #[test]
997    fn help_from_help_closes_it() {
998        let mut state = listed(1, None);
999        press(&mut state, Action::Help);
1000        press(&mut state, Action::Help);
1001        assert_eq!(state.view, View::List, "the same key closes help");
1002    }
1003
1004    #[test]
1005    fn a_key_press_clears_the_notice() {
1006        let mut state = listed(2, Some("cursor-1"));
1007        press(&mut state, Action::More);
1008        state.step(
1009            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1010            NOW,
1011        );
1012        press(&mut state, Action::Down);
1013        assert_eq!(
1014            state.notice, None,
1015            "the notice is about the last request only"
1016        );
1017    }
1018
1019    #[test]
1020    fn back_in_the_list_view_does_not_quit() {
1021        let mut state = listed(1, None);
1022        press(&mut state, Action::Back);
1023        assert!(!state.quit, "only the quit keys end the program");
1024        assert_eq!(state.view, View::List, "and the view stays");
1025    }
1026
1027    // A key the server stops accepting while the UI runs.
1028
1029    #[test]
1030    fn a_key_refused_at_a_refresh_is_not_connected_as_at_start() {
1031        let mut state = listed(3, None);
1032        press(&mut state, Action::Refresh);
1033        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1034        assert_eq!(
1035            state.connection,
1036            Connection::Failed("the server refused the key (401)".to_owned()),
1037            "a revoked key is shown as it is when the UI starts with one"
1038        );
1039        assert_eq!(
1040            state.listing,
1041            Listing::Failed("the server refused the key (401)".to_owned()),
1042            "and the list says why"
1043        );
1044    }
1045
1046    #[test]
1047    fn a_refresh_after_a_refused_key_asks_for_the_key_again() {
1048        let mut state = listed(3, None);
1049        press(&mut state, Action::Refresh);
1050        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1051        assert_eq!(
1052            press(&mut state, Action::Refresh),
1053            vec![Effect::FetchKey],
1054            "the tenant and scopes are read again, not taken from before the refusal"
1055        );
1056    }
1057
1058    #[test]
1059    fn a_key_refused_at_a_next_page_is_not_connected_and_the_rows_stay() {
1060        let mut state = listed(3, Some("cursor-1"));
1061        press(&mut state, Action::More);
1062        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1063        assert_eq!(
1064            state.connection,
1065            Connection::Failed("the server refused the key (401)".to_owned()),
1066            "the status line stops saying connected"
1067        );
1068        assert_eq!(state.rows.len(), 3, "the rows read before stay");
1069        assert_eq!(
1070            state.notice.as_deref(),
1071            Some("The next page was not read: the server refused the key (401)."),
1072            "and the notice says why"
1073        );
1074    }
1075
1076    #[test]
1077    fn a_503_at_a_refresh_leaves_the_connection_as_it_was() {
1078        let mut state = listed(3, None);
1079        press(&mut state, Action::Refresh);
1080        state.step(
1081            Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
1082            NOW,
1083        );
1084        assert!(
1085            matches!(state.connection, Connection::Connected(_)),
1086            "the server answered for the key, and may answer the next request"
1087        );
1088        assert_eq!(
1089            press(&mut state, Action::Refresh),
1090            vec![Effect::FetchPage(None)],
1091            "so r reads the first page, not the key"
1092        );
1093    }
1094}