1use std::fmt;
6
7use serde::Deserialize;
8use time::OffsetDateTime;
9
10#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12pub struct KeyInfo {
13 pub id: String,
15 pub tenant: Option<String>,
17 pub scopes: Vec<String>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
23pub struct Row {
24 pub uuid: String,
26 pub stored_at: String,
28 pub updated_at: String,
30 pub version: String,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
36pub struct Page {
37 pub vcons: Vec<Row>,
39 pub next: Option<String>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum ApiError {
46 Unreachable(String),
48 Untrusted(String),
51 Status(u16, Option<String>),
54 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#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum Connection {
82 Connecting,
84 Connected(KeyInfo),
86 Failed(String),
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Listing {
93 Loading,
95 Ready,
97 Failed(String),
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum View {
104 List,
106 Detail,
108 Help,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Action {
115 Up,
117 Down,
119 Top,
121 Bottom,
123 PageUp,
125 PageDown,
127 Open,
129 Back,
131 Refresh,
133 More,
135 Help,
137 Quit,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum Event {
144 Action(Action),
146 Resize(u16, u16),
148 KeyInfo(Result<KeyInfo, ApiError>),
150 Page(Result<Page, ApiError>),
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Effect {
157 FetchKey,
159 FetchPage(Option<String>),
161}
162
163const FRAME_LINES: u16 = 5;
166
167#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct State {
170 pub server: String,
172 pub connection: Connection,
174 pub listing: Listing,
176 pub rows: Vec<Row>,
178 pub next: Option<String>,
180 pub selected: usize,
182 pub view: View,
184 pub behind_help: View,
186 pub detail: Option<String>,
188 pub more: bool,
190 pub as_of: Option<OffsetDateTime>,
192 pub notice: Option<String>,
194 pub size: (u16, u16),
196 pub quit: bool,
198}
199
200impl State {
201 #[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 #[must_use]
226 pub fn list_rows(lines: u16) -> u16 {
227 lines.saturating_sub(FRAME_LINES).max(1)
228 }
229
230 #[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 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 #[must_use]
248 pub fn acts(&self, action: Action) -> bool {
249 match (self.view, action) {
250 (_, Action::Quit | Action::Help) | (View::Help | View::Detail, Action::Back) => true,
251 (View::Help, _) | (View::List, Action::Back) | (View::Detail, Action::Open) => false,
252 (_, Action::Refresh) => !self.busy() && self.key_refusal().is_none(),
253 (_, Action::More) => {
254 !self.busy() && self.listing == Listing::Ready && self.next.is_some()
255 }
256 (View::List, Action::Open) => self.rows_shown() && !self.rows.is_empty(),
257 (
258 view,
259 Action::Up
260 | Action::Down
261 | Action::Top
262 | Action::Bottom
263 | Action::PageUp
264 | Action::PageDown,
265 ) => {
266 let reselects =
269 view == View::Detail && !self.rows.is_empty() && self.detail_row().is_none();
270 self.rows_shown() && (self.rows.len() > 1 || reselects)
271 }
272 }
273 }
274
275 #[must_use]
280 pub fn rows_shown(&self) -> bool {
281 self.listing == Listing::Ready
282 }
283
284 #[must_use]
287 pub fn key_refusal(&self) -> Option<&'static str> {
288 match &self.connection {
289 Connection::Connected(info) => refusal(info),
290 Connection::Connecting | Connection::Failed(_) => None,
291 }
292 }
293
294 pub fn step(&mut self, event: Event, now: OffsetDateTime) -> Vec<Effect> {
297 match event {
298 Event::Action(action) => {
299 self.notice = None;
300 self.act(action)
301 }
302 Event::Resize(columns, lines) => {
303 self.size = (columns, lines);
304 Vec::new()
305 }
306 Event::KeyInfo(Ok(info)) => self.connected(info),
307 Event::KeyInfo(Err(error)) => {
308 self.connection = Connection::Failed(error.to_string());
309 self.listing = Listing::Failed(error.to_string());
310 Vec::new()
311 }
312 Event::Page(Ok(page)) => {
313 self.page(page, now);
314 Vec::new()
315 }
316 Event::Page(Err(error)) => {
317 self.page_failed(&error);
318 Vec::new()
319 }
320 }
321 }
322
323 fn connected(&mut self, info: KeyInfo) -> Vec<Effect> {
325 let refusal = refusal(&info);
326 self.connection = Connection::Connected(info);
327 match refusal {
328 Some(why) => {
329 self.listing = Listing::Failed(why.to_owned());
330 Vec::new()
331 }
332 None => {
333 self.listing = Listing::Loading;
334 vec![Effect::FetchPage(None)]
335 }
336 }
337 }
338
339 fn page(&mut self, page: Page, now: OffsetDateTime) {
342 if self.more {
343 self.rows.extend(page.vcons);
344 } else {
345 let on = self
346 .detail
347 .clone()
348 .or_else(|| self.rows.get(self.selected).map(|row| row.uuid.clone()));
349 self.rows = page.vcons;
350 if let Some(index) =
351 on.and_then(|uuid| self.rows.iter().position(|row| row.uuid == uuid))
352 {
353 self.selected = index;
354 }
355 }
356 self.selected = self.selected.min(self.rows.len().saturating_sub(1));
357 self.next = page.next;
358 self.more = false;
359 self.listing = Listing::Ready;
360 self.as_of = Some(now);
361 }
362
363 fn page_failed(&mut self, error: &ApiError) {
369 if matches!(
370 error,
371 ApiError::Unreachable(_) | ApiError::Untrusted(_) | ApiError::Status(401, _)
372 ) {
373 self.connection = Connection::Failed(error.to_string());
374 }
375 if self.more {
376 self.more = false;
377 self.notice = Some(format!("The next page was not read: {error}."));
378 } else {
379 self.rows.clear();
380 self.next = None;
381 self.selected = 0;
382 self.as_of = None;
383 self.listing = Listing::Failed(error.to_string());
384 }
385 }
386
387 fn act(&mut self, action: Action) -> Vec<Effect> {
389 match (self.view, action) {
390 (_, Action::Quit) => self.quit = true,
391 (View::Help, Action::Help | Action::Back) => self.view = self.behind_help,
392 (View::Help, _) | (View::List, Action::Back) | (View::Detail, Action::Open) => {}
393 (view, Action::Help) => {
394 self.behind_help = view;
395 self.view = View::Help;
396 }
397 (View::Detail, Action::Back) => self.view = View::List,
398 (_, Action::Refresh) => return self.refresh(),
399 (_, Action::More) => return self.more(),
400 (
403 _,
404 Action::Open
405 | Action::Up
406 | Action::Down
407 | Action::Top
408 | Action::Bottom
409 | Action::PageUp
410 | Action::PageDown,
411 ) if !self.rows_shown() => {}
412 (View::List, Action::Open) => {
413 if let Some(row) = self.rows.get(self.selected) {
414 self.detail = Some(row.uuid.clone());
415 self.view = View::Detail;
416 }
417 }
418 (
419 view,
420 Action::Up
421 | Action::Down
422 | Action::Top
423 | Action::Bottom
424 | Action::PageUp
425 | Action::PageDown,
426 ) => {
427 self.travel(action);
428 if view == View::Detail
429 && let Some(row) = self.rows.get(self.selected)
430 {
431 self.detail = Some(row.uuid.clone());
432 }
433 }
434 }
435 Vec::new()
436 }
437
438 fn travel(&mut self, action: Action) {
440 let last = self.rows.len().saturating_sub(1);
441 let page = usize::from(Self::list_rows(self.size.1));
442 self.selected = match action {
443 Action::Up => self.selected.saturating_sub(1),
444 Action::Down => self.selected.saturating_add(1),
445 Action::Top => 0,
446 Action::Bottom => last,
447 Action::PageUp => self.selected.saturating_sub(page),
448 Action::PageDown => self.selected.saturating_add(page),
449 _ => self.selected,
450 }
451 .min(last);
452 }
453
454 fn refresh(&mut self) -> Vec<Effect> {
457 if self.busy() {
458 return Vec::new();
459 }
460 if let Connection::Connected(info) = &self.connection {
461 return self.connected(info.clone());
462 }
463 self.connection = Connection::Connecting;
464 self.listing = Listing::Loading;
465 vec![Effect::FetchKey]
466 }
467
468 fn more(&mut self) -> Vec<Effect> {
470 if self.busy() || self.listing != Listing::Ready {
471 return Vec::new();
472 }
473 let Some(cursor) = self.next.clone() else {
474 return Vec::new();
475 };
476 self.more = true;
477 vec![Effect::FetchPage(Some(cursor))]
478 }
479}
480
481fn refusal(info: &KeyInfo) -> Option<&'static str> {
484 if info.tenant.is_none() {
485 Some("this is an operator key, which reaches no vCon: use a tenant key with the read scope")
486 } else if info.scopes.iter().all(|scope| scope != "read") {
487 Some("this key lacks the read scope: use a tenant key that holds it")
488 } else {
489 None
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use time::OffsetDateTime;
496 use time::macros::datetime;
497
498 use super::{
499 Action, ApiError, Connection, Effect, Event, KeyInfo, Listing, Page, Row, State, View,
500 };
501
502 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
503
504 fn row(n: u8) -> Row {
505 Row {
506 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
507 stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
508 updated_at: "2026-10-25T12:30:00Z".to_owned(),
509 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
510 }
511 }
512
513 fn reader() -> KeyInfo {
514 KeyInfo {
515 id: "0123456789abcdef".to_owned(),
516 tenant: Some("t_example".to_owned()),
517 scopes: vec!["read".to_owned()],
518 }
519 }
520
521 fn page(rows: std::ops::Range<u8>, next: Option<&str>) -> Page {
522 Page {
523 vcons: rows.map(row).collect(),
524 next: next.map(str::to_owned),
525 }
526 }
527
528 fn listed(rows: u8, next: Option<&str>) -> State {
530 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
531 state.step(Event::KeyInfo(Ok(reader())), NOW);
532 state.step(Event::Page(Ok(page(0..rows, next))), NOW);
533 state
534 }
535
536 fn press(state: &mut State, action: Action) -> Vec<Effect> {
537 state.step(Event::Action(action), NOW)
538 }
539
540 #[test]
543 fn a_new_state_is_connecting_and_asks_for_the_key() {
544 let (state, effects) = State::new("https://vcon.example.com:8443", (80, 24));
545 assert_eq!(
546 state.connection,
547 Connection::Connecting,
548 "nothing has answered yet"
549 );
550 assert_eq!(
551 effects,
552 [Effect::FetchKey],
553 "the key's tenant and scopes come first"
554 );
555 }
556
557 #[test]
558 fn a_reader_key_connects_and_asks_for_the_first_page() {
559 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
560 let effects = state.step(Event::KeyInfo(Ok(reader())), NOW);
561 assert_eq!(
562 state.connection,
563 Connection::Connected(reader()),
564 "the key answered"
565 );
566 assert_eq!(state.listing, Listing::Loading, "the page is on its way");
567 assert_eq!(
568 effects,
569 [Effect::FetchPage(None)],
570 "the first page has no cursor"
571 );
572 }
573
574 #[test]
575 fn a_page_fills_the_list_and_records_when() {
576 let state = listed(3, Some("cursor-1"));
577 assert_eq!(state.listing, Listing::Ready, "the page arrived");
578 assert_eq!(state.rows.len(), 3, "every row of the page is kept");
579 assert_eq!(
580 state.next.as_deref(),
581 Some("cursor-1"),
582 "the cursor is kept for more"
583 );
584 assert_eq!(
585 state.as_of,
586 Some(NOW),
587 "the clock passed in is when it was read"
588 );
589 }
590
591 #[test]
592 fn down_and_up_move_the_selection() {
593 let mut state = listed(3, None);
594 press(&mut state, Action::Down);
595 press(&mut state, Action::Down);
596 assert_eq!(state.selected, 2, "two rows down");
597 press(&mut state, Action::Up);
598 assert_eq!(state.selected, 1, "one row back up");
599 }
600
601 #[test]
602 fn bottom_and_top_jump_to_the_ends() {
603 let mut state = listed(5, None);
604 press(&mut state, Action::Bottom);
605 assert_eq!(state.selected, 4, "the last row");
606 press(&mut state, Action::Top);
607 assert_eq!(state.selected, 0, "the first row");
608 }
609
610 #[test]
611 fn open_shows_the_selected_vcon_and_back_returns() {
612 let mut state = listed(3, None);
613 press(&mut state, Action::Down);
614 let effects = press(&mut state, Action::Open);
615 assert_eq!(state.view, View::Detail, "the detail view is open");
616 assert_eq!(
617 state.detail,
618 Some(row(1).uuid),
619 "on the row that was selected"
620 );
621 assert_eq!(
622 effects,
623 [],
624 "the detail is drawn from the list row: no request"
625 );
626 press(&mut state, Action::Back);
627 assert_eq!(state.view, View::List, "back at the list");
628 }
629
630 #[test]
631 fn more_asks_for_the_next_page_and_appends_it() {
632 let mut state = listed(2, Some("cursor-1"));
633 let effects = press(&mut state, Action::More);
634 assert_eq!(
635 effects,
636 [Effect::FetchPage(Some("cursor-1".to_owned()))],
637 "the cursor goes back unchanged"
638 );
639 state.step(Event::Page(Ok(page(2..4, None))), NOW);
640 assert_eq!(state.rows.len(), 4, "the second page follows the first");
641 assert_eq!(state.next, None, "the last page has no cursor");
642 }
643
644 #[test]
645 fn refresh_asks_for_the_first_page_again_and_replaces_the_rows() {
646 let mut state = listed(3, None);
647 let effects = press(&mut state, Action::Refresh);
648 assert_eq!(effects, [Effect::FetchPage(None)], "from the start");
649 assert_eq!(
650 state.listing,
651 Listing::Loading,
652 "loading is shown meanwhile"
653 );
654 state.step(Event::Page(Ok(page(0..1, None))), NOW);
655 assert_eq!(state.rows.len(), 1, "the new page replaces the old rows");
656 }
657
658 #[test]
659 fn help_opens_over_a_view_and_returns_to_it() {
660 let mut state = listed(3, None);
661 press(&mut state, Action::Open);
662 press(&mut state, Action::Help);
663 assert_eq!(state.view, View::Help, "help is open");
664 press(&mut state, Action::Back);
665 assert_eq!(
666 state.view,
667 View::Detail,
668 "back at the view help was opened from"
669 );
670 }
671
672 #[test]
673 fn quit_ends_from_every_view() {
674 for open in [None, Some(Action::Open), Some(Action::Help)] {
675 let mut state = listed(1, None);
676 if let Some(open) = open {
677 press(&mut state, open);
678 }
679 press(&mut state, Action::Quit);
680 assert!(state.quit, "quit ends from {:?}", state.view);
681 }
682 }
683
684 #[test]
685 fn page_down_moves_by_the_rows_the_terminal_shows() {
686 let mut state = listed(60, None);
687 press(&mut state, Action::PageDown);
688 assert_eq!(
689 state.selected,
690 usize::from(State::list_rows(24)),
691 "a 24-line terminal pages by its list rows"
692 );
693 press(&mut state, Action::PageUp);
694 assert_eq!(state.selected, 0, "and back");
695 }
696
697 #[test]
698 fn down_in_the_detail_view_shows_the_next_vcon() {
699 let mut state = listed(3, None);
700 press(&mut state, Action::Open);
701 press(&mut state, Action::Down);
702 assert_eq!(
703 state.detail,
704 Some(row(1).uuid),
705 "the detail follows the selection"
706 );
707 }
708
709 #[test]
710 fn a_refresh_keeps_the_selection_on_the_same_vcon() {
711 let mut state = listed(3, None);
712 press(&mut state, Action::Bottom);
713 press(&mut state, Action::Open);
714 press(&mut state, Action::Refresh);
715 state.step(Event::Page(Ok(page(1..3, None))), NOW);
716 assert_eq!(
717 state.selected, 1,
718 "the vCon moved up one row and the selection with it"
719 );
720 assert_eq!(
721 state.detail,
722 Some(row(2).uuid),
723 "the detail is still that vCon"
724 );
725 }
726
727 #[test]
730 fn an_unreachable_server_fails_the_connection_and_the_list() {
731 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
732 let effects = state.step(
733 Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
734 NOW,
735 );
736 assert_eq!(
737 effects,
738 [],
739 "nothing more is asked of a server that did not answer"
740 );
741 assert!(
742 matches!(&state.connection, Connection::Failed(why) if why.contains("connection refused")),
743 "the status line says why: {:?}",
744 state.connection
745 );
746 assert!(
747 matches!(state.listing, Listing::Failed(_)),
748 "the list says so too"
749 );
750 }
751
752 #[test]
753 fn a_refused_key_says_the_status() {
754 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
755 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
756 assert!(
757 matches!(&state.connection, Connection::Failed(why) if why.contains("401")),
758 "the refusal's status is shown: {:?}",
759 state.connection
760 );
761 }
762
763 #[test]
764 fn an_operator_key_connects_but_lists_nothing() {
765 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
766 let operator = KeyInfo {
767 id: "0123456789abcdef".to_owned(),
768 tenant: None,
769 scopes: vec!["admin".to_owned()],
770 };
771 let effects = state.step(Event::KeyInfo(Ok(operator)), NOW);
772 assert_eq!(
773 effects,
774 [],
775 "an operator key reaches no vCon, so none is asked for"
776 );
777 assert!(
778 matches!(&state.listing, Listing::Failed(why) if why.contains("operator key")),
779 "the list says which key to use: {:?}",
780 state.listing
781 );
782 }
783
784 #[test]
785 fn a_key_without_read_lists_nothing() {
786 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
787 let writer = KeyInfo {
788 scopes: vec!["write".to_owned()],
789 ..reader()
790 };
791 let effects = state.step(Event::KeyInfo(Ok(writer)), NOW);
792 assert_eq!(effects, [], "the list needs read, so it is not asked for");
793 assert!(
794 matches!(&state.listing, Listing::Failed(why) if why.contains("read scope")),
795 "the list names the scope: {:?}",
796 state.listing
797 );
798 }
799
800 #[test]
801 fn a_failed_first_page_is_an_error_state() {
802 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
803 state.step(Event::KeyInfo(Ok(reader())), NOW);
804 state.step(
805 Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
806 NOW,
807 );
808 assert!(
809 matches!(&state.listing, Listing::Failed(why) if why.contains("503") && why.contains("unavailable")),
810 "the status and the problem's title are shown: {:?}",
811 state.listing
812 );
813 assert_eq!(state.as_of, None, "nothing was read, so no time is claimed");
814 }
815
816 #[test]
817 fn a_failed_next_page_keeps_the_rows_and_leaves_a_notice() {
818 let mut state = listed(2, Some("cursor-1"));
819 press(&mut state, Action::More);
820 state.step(
821 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
822 NOW,
823 );
824 assert_eq!(state.rows.len(), 2, "the rows already read stay");
825 assert_eq!(state.listing, Listing::Ready, "the list is still usable");
826 assert_eq!(
827 state.next.as_deref(),
828 Some("cursor-1"),
829 "the cursor is kept to try again"
830 );
831 assert!(
832 state
833 .notice
834 .as_deref()
835 .is_some_and(|n| n.contains("timed out")),
836 "a notice says why: {:?}",
837 state.notice
838 );
839 }
840
841 #[test]
842 fn a_failed_refresh_drops_the_old_rows() {
843 let mut state = listed(2, None);
844 press(&mut state, Action::Refresh);
845 state.step(Event::Page(Err(ApiError::Status(500, None))), NOW);
846 assert!(
847 matches!(state.listing, Listing::Failed(_)),
848 "the error is shown"
849 );
850 assert_eq!(
851 state.rows,
852 [],
853 "rows that may be out of date are not shown as current"
854 );
855 }
856
857 #[test]
858 fn a_malformed_answer_is_an_error_state() {
859 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
860 state.step(Event::KeyInfo(Ok(reader())), NOW);
861 state.step(
862 Event::Page(Err(ApiError::Malformed("expected value".to_owned()))),
863 NOW,
864 );
865 assert!(
866 matches!(&state.listing, Listing::Failed(why) if why.contains("expected value")),
867 "what could not be read is shown: {:?}",
868 state.listing
869 );
870 }
871
872 #[test]
873 fn refresh_after_a_failed_connection_asks_for_the_key_again() {
874 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
875 state.step(
876 Event::KeyInfo(Err(ApiError::Unreachable("refused".to_owned()))),
877 NOW,
878 );
879 let effects = press(&mut state, Action::Refresh);
880 assert_eq!(
881 effects,
882 [Effect::FetchKey],
883 "the connection is made again from the start"
884 );
885 assert_eq!(
886 state.connection,
887 Connection::Connecting,
888 "and shown as such"
889 );
890 }
891
892 #[test]
893 fn a_server_that_stops_answering_is_shown_as_not_connected() {
894 let mut state = listed(2, None);
895 press(&mut state, Action::Refresh);
896 state.step(
897 Event::Page(Err(ApiError::Unreachable("connection reset".to_owned()))),
898 NOW,
899 );
900 assert!(
901 matches!(state.connection, Connection::Failed(_)),
902 "the status line no longer says connected"
903 );
904 }
905
906 #[test]
907 fn a_vcon_gone_after_a_refresh_leaves_the_detail_without_a_row() {
908 let mut state = listed(2, None);
909 press(&mut state, Action::Open);
910 press(&mut state, Action::Refresh);
911 state.step(Event::Page(Ok(page(1..2, None))), NOW);
912 assert_eq!(
913 state.detail,
914 Some(row(0).uuid),
915 "the detail still names what was open"
916 );
917 assert_eq!(state.detail_row(), None, "and has no row to draw");
918 }
919
920 #[test]
921 fn each_api_error_says_what_failed() {
922 for (error, text) in [
923 (
924 ApiError::Unreachable("refused".to_owned()),
925 "the server did not answer: refused",
926 ),
927 (
928 ApiError::Status(401, None),
929 "the server refused the key (401)",
930 ),
931 (
932 ApiError::Status(403, Some("forbidden".to_owned())),
933 "the server answered 403 (forbidden)",
934 ),
935 (ApiError::Status(500, None), "the server answered 500"),
936 (
937 ApiError::Malformed("eof".to_owned()),
938 "the server's answer could not be read: eof",
939 ),
940 ] {
941 assert_eq!(error.to_string(), text, "{error:?}");
942 }
943 }
944
945 #[test]
948 fn up_at_the_top_and_down_at_the_bottom_stay() {
949 let mut state = listed(2, None);
950 press(&mut state, Action::Up);
951 assert_eq!(state.selected, 0, "no row above the first");
952 press(&mut state, Action::Bottom);
953 press(&mut state, Action::Down);
954 assert_eq!(state.selected, 1, "no row below the last");
955 }
956
957 #[test]
958 fn open_on_an_empty_list_does_nothing() {
959 let mut state = listed(0, None);
960 press(&mut state, Action::Open);
961 assert_eq!(state.view, View::List, "there is nothing to open");
962 assert_eq!(state.detail, None, "and no vCon is named");
963 }
964
965 #[test]
966 fn movement_on_an_empty_list_stays_at_zero() {
967 let mut state = listed(0, None);
968 for action in [Action::Down, Action::Bottom, Action::PageDown, Action::Up] {
969 press(&mut state, action);
970 assert_eq!(state.selected, 0, "{action:?} on no rows");
971 }
972 }
973
974 #[test]
975 fn more_on_the_last_page_asks_for_nothing() {
976 let mut state = listed(2, None);
977 assert_eq!(press(&mut state, Action::More), [], "there is no next page");
978 }
979
980 #[test]
981 fn a_second_refresh_while_loading_asks_for_nothing() {
982 let mut state = listed(2, None);
983 press(&mut state, Action::Refresh);
984 assert_eq!(
985 press(&mut state, Action::Refresh),
986 [],
987 "one request is in flight; a second would race it"
988 );
989 }
990
991 #[test]
992 fn more_while_more_is_loading_asks_for_nothing() {
993 let mut state = listed(2, Some("cursor-1"));
994 press(&mut state, Action::More);
995 assert_eq!(
996 press(&mut state, Action::More),
997 [],
998 "the page is already on its way"
999 );
1000 assert_eq!(
1001 press(&mut state, Action::Refresh),
1002 [],
1003 "and a refresh would race it"
1004 );
1005 }
1006
1007 #[test]
1008 fn refresh_while_connecting_asks_for_nothing() {
1009 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
1010 assert_eq!(
1011 press(&mut state, Action::Refresh),
1012 [],
1013 "the key request is in flight"
1014 );
1015 }
1016
1017 #[test]
1018 fn a_resize_changes_only_the_size() {
1019 let mut state = listed(3, None);
1020 press(&mut state, Action::Down);
1021 let before = state.clone();
1022 let effects = state.step(Event::Resize(132, 43), NOW);
1023 assert_eq!(effects, [], "a resize asks the server nothing");
1024 assert_eq!(state.size, (132, 43), "the new size is kept");
1025 assert_eq!(
1026 State {
1027 size: before.size,
1028 ..state
1029 },
1030 before,
1031 "nothing else changed"
1032 );
1033 }
1034
1035 #[test]
1036 fn a_shorter_page_after_refresh_clamps_the_selection() {
1037 let mut state = listed(5, None);
1038 press(&mut state, Action::Bottom);
1039 press(&mut state, Action::Refresh);
1040 state.step(Event::Page(Ok(page(10..12, None))), NOW);
1041 assert_eq!(
1042 state.selected, 1,
1043 "the selection is the last row that exists"
1044 );
1045 }
1046
1047 #[test]
1048 fn page_down_past_the_end_stops_at_the_last_row() {
1049 let mut state = listed(3, None);
1050 press(&mut state, Action::PageDown);
1051 assert_eq!(state.selected, 2, "the last row, not past it");
1052 }
1053
1054 #[test]
1055 fn a_terminal_too_short_for_a_list_still_pages_by_one() {
1056 assert_eq!(State::list_rows(0), 1, "never zero: paging would not move");
1057 assert_eq!(State::list_rows(5), 1, "the frame takes five lines");
1058 assert_eq!(State::list_rows(24), 19, "24 lines leave 19 for rows");
1059 }
1060
1061 #[test]
1062 fn help_from_help_closes_it() {
1063 let mut state = listed(1, None);
1064 press(&mut state, Action::Help);
1065 press(&mut state, Action::Help);
1066 assert_eq!(state.view, View::List, "the same key closes help");
1067 }
1068
1069 #[test]
1070 fn a_key_press_clears_the_notice() {
1071 let mut state = listed(2, Some("cursor-1"));
1072 press(&mut state, Action::More);
1073 state.step(
1074 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1075 NOW,
1076 );
1077 press(&mut state, Action::Down);
1078 assert_eq!(
1079 state.notice, None,
1080 "the notice is about the last request only"
1081 );
1082 }
1083
1084 #[test]
1085 fn back_in_the_list_view_does_not_quit() {
1086 let mut state = listed(1, None);
1087 press(&mut state, Action::Back);
1088 assert!(!state.quit, "only the quit keys end the program");
1089 assert_eq!(state.view, View::List, "and the view stays");
1090 }
1091
1092 #[test]
1095 fn a_key_refused_at_a_refresh_is_not_connected_as_at_start() {
1096 let mut state = listed(3, None);
1097 press(&mut state, Action::Refresh);
1098 state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1099 assert_eq!(
1100 state.connection,
1101 Connection::Failed("the server refused the key (401)".to_owned()),
1102 "a revoked key is shown as it is when the UI starts with one"
1103 );
1104 assert_eq!(
1105 state.listing,
1106 Listing::Failed("the server refused the key (401)".to_owned()),
1107 "and the list says why"
1108 );
1109 }
1110
1111 #[test]
1112 fn a_refresh_after_a_refused_key_asks_for_the_key_again() {
1113 let mut state = listed(3, None);
1114 press(&mut state, Action::Refresh);
1115 state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1116 assert_eq!(
1117 press(&mut state, Action::Refresh),
1118 vec![Effect::FetchKey],
1119 "the tenant and scopes are read again, not taken from before the refusal"
1120 );
1121 }
1122
1123 #[test]
1124 fn a_key_refused_at_a_next_page_is_not_connected_and_the_rows_stay() {
1125 let mut state = listed(3, Some("cursor-1"));
1126 press(&mut state, Action::More);
1127 state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1128 assert_eq!(
1129 state.connection,
1130 Connection::Failed("the server refused the key (401)".to_owned()),
1131 "the status line stops saying connected"
1132 );
1133 assert_eq!(state.rows.len(), 3, "the rows read before stay");
1134 assert_eq!(
1135 state.notice.as_deref(),
1136 Some("The next page was not read: the server refused the key (401)."),
1137 "and the notice says why"
1138 );
1139 }
1140
1141 #[test]
1142 fn a_503_at_a_refresh_leaves_the_connection_as_it_was() {
1143 let mut state = listed(3, None);
1144 press(&mut state, Action::Refresh);
1145 state.step(
1146 Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
1147 NOW,
1148 );
1149 assert!(
1150 matches!(state.connection, Connection::Connected(_)),
1151 "the server answered for the key, and may answer the next request"
1152 );
1153 assert_eq!(
1154 press(&mut state, Action::Refresh),
1155 vec![Effect::FetchPage(None)],
1156 "so r reads the first page, not the key"
1157 );
1158 }
1159
1160 const ACTIONS: [Action; 12] = [
1163 Action::Up,
1164 Action::Down,
1165 Action::Top,
1166 Action::Bottom,
1167 Action::PageUp,
1168 Action::PageDown,
1169 Action::Open,
1170 Action::Back,
1171 Action::Refresh,
1172 Action::More,
1173 Action::Help,
1174 Action::Quit,
1175 ];
1176
1177 const TRAVEL: [Action; 6] = [
1178 Action::Up,
1179 Action::Down,
1180 Action::Top,
1181 Action::Bottom,
1182 Action::PageUp,
1183 Action::PageDown,
1184 ];
1185
1186 fn after(mut state: State, events: Vec<Event>) -> State {
1187 for event in events {
1188 state.step(event, NOW);
1189 }
1190 state
1191 }
1192
1193 fn new() -> State {
1194 State::new("https://vcon.example.com:8443", (80, 24)).0
1195 }
1196
1197 fn key(tenant: Option<&str>, scope: &str) -> Event {
1198 Event::KeyInfo(Ok(KeyInfo {
1199 id: "0123456789abcdef".to_owned(),
1200 tenant: tenant.map(str::to_owned),
1201 scopes: vec![scope.to_owned()],
1202 }))
1203 }
1204
1205 fn no_answer() -> ApiError {
1206 ApiError::Unreachable("no answer within 15 seconds".to_owned())
1207 }
1208
1209 fn states() -> Vec<(String, State)> {
1212 let act = Event::Action;
1213 let mut base: Vec<(&str, State)> = vec![
1214 ("connecting", new()),
1215 ("loading", after(new(), vec![Event::KeyInfo(Ok(reader()))])),
1216 (
1217 "no answer",
1218 after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
1219 ),
1220 (
1221 "refused key",
1222 after(
1223 new(),
1224 vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
1225 ),
1226 ),
1227 ("operator key", after(new(), vec![key(None, "admin")])),
1228 (
1229 "write key",
1230 after(new(), vec![key(Some("t_example"), "write")]),
1231 ),
1232 (
1233 "first page failed",
1234 after(
1235 new(),
1236 vec![
1237 Event::KeyInfo(Ok(reader())),
1238 Event::Page(Err(ApiError::Status(503, None))),
1239 ],
1240 ),
1241 ),
1242 ("empty", listed(0, None)),
1243 ("one row", listed(1, None)),
1244 ("one row, more", listed(1, Some("c"))),
1245 ("three rows", listed(3, None)),
1246 ("three rows, more", listed(3, Some("c"))),
1247 (
1248 "three rows, second",
1249 after(listed(3, None), vec![act(Action::Down)]),
1250 ),
1251 (
1252 "three rows, last",
1253 after(listed(3, Some("c")), vec![act(Action::Bottom)]),
1254 ),
1255 (
1256 "next page out",
1257 after(listed(3, Some("c")), vec![act(Action::More)]),
1258 ),
1259 (
1260 "next page failed",
1261 after(
1262 listed(3, Some("c")),
1263 vec![act(Action::More), Event::Page(Err(no_answer()))],
1264 ),
1265 ),
1266 (
1267 "refresh out",
1268 after(listed(3, Some("c")), vec![act(Action::Refresh)]),
1269 ),
1270 (
1271 "refresh failed",
1272 after(
1273 listed(3, None),
1274 vec![
1275 act(Action::Refresh),
1276 Event::Page(Err(ApiError::Status(503, None))),
1277 ],
1278 ),
1279 ),
1280 (
1281 "reconnecting",
1282 after(
1283 listed(3, None),
1284 vec![
1285 act(Action::Refresh),
1286 Event::Page(Err(no_answer())),
1287 act(Action::Refresh),
1288 ],
1289 ),
1290 ),
1291 ];
1292 for (name, left) in [
1295 ("gone, three left", 3),
1296 ("gone, one left", 1),
1297 ("gone, none left", 0),
1298 ] {
1299 let mut state = after(
1300 listed(5, None),
1301 vec![act(Action::Bottom), act(Action::Open), act(Action::Refresh)],
1302 );
1303 state.step(Event::Page(Ok(page(0..left, None))), NOW);
1304 assert_eq!(
1305 state.view,
1306 View::Detail,
1307 "{name}: the detail view stays open"
1308 );
1309 assert!(
1310 state.detail_row().is_none(),
1311 "{name}: its vCon is not listed"
1312 );
1313 base.push((name, state));
1314 }
1315 let mut all = Vec::new();
1316 for (name, state) in base {
1317 let opened = after(state.clone(), vec![act(Action::Open)]);
1318 if opened.view == View::Detail && state.view != View::Detail {
1319 let refreshing = after(opened.clone(), vec![act(Action::Refresh)]);
1320 all.push((
1321 format!("{name}, detail, help"),
1322 after(opened.clone(), vec![act(Action::Help)]),
1323 ));
1324 all.push((format!("{name}, detail, r pressed"), refreshing));
1325 all.push((format!("{name}, detail"), opened));
1326 }
1327 all.push((
1328 format!("{name}, help"),
1329 after(state.clone(), vec![act(Action::Help)]),
1330 ));
1331 all.push((name.to_owned(), state));
1332 }
1333 all
1334 }
1335
1336 fn acted(state: &State, action: Action) -> (State, Vec<Effect>) {
1338 let mut next = state.clone();
1339 let effects = next.act(action);
1340 (next, effects)
1341 }
1342
1343 #[test]
1344 fn the_states_tried_cover_every_view_and_kind() {
1345 let all = states();
1346 assert!(all.len() >= 50, "{} states are tried", all.len());
1347 for view in [View::List, View::Detail, View::Help] {
1348 assert!(
1349 all.iter().any(|(_, state)| state.view == view),
1350 "a state in {view:?} is tried"
1351 );
1352 }
1353 let mut names: Vec<&String> = all.iter().map(|(name, _)| name).collect();
1354 names.sort();
1355 names.dedup();
1356 assert_eq!(names.len(), all.len(), "each state has its own name");
1357 }
1358
1359 #[test]
1360 fn a_key_that_does_not_act_changes_nothing() {
1361 for (name, state) in states() {
1362 for action in ACTIONS {
1363 if state.acts(action) {
1364 continue;
1365 }
1366 let (next, effects) = acted(&state, action);
1367 assert!(
1368 next == state && effects.is_empty(),
1369 "{name}: {action:?} is said not to act, and a press changed the state or asked the server"
1370 );
1371 }
1372 }
1373 }
1374
1375 #[test]
1376 fn a_key_that_acts_changes_the_state_or_asks_the_server() {
1377 for (name, state) in states() {
1378 for action in ACTIONS {
1379 if !state.acts(action) || TRAVEL.contains(&action) {
1380 continue;
1381 }
1382 let (next, effects) = acted(&state, action);
1383 assert!(
1384 next != state || !effects.is_empty(),
1385 "{name}: {action:?} is said to act, and a press did nothing"
1386 );
1387 }
1388 }
1389 }
1390
1391 #[test]
1392 fn the_keys_that_move_act_when_one_of_them_can_move() {
1393 for (name, state) in states() {
1394 let moves = TRAVEL
1395 .iter()
1396 .any(|action| acted(&state, *action).0 != state);
1397 for action in TRAVEL {
1398 assert_eq!(
1399 state.acts(action),
1400 moves,
1401 "{name}: {action:?} acts when the selection can move ({moves})"
1402 );
1403 }
1404 }
1405 }
1406
1407 #[test]
1408 fn quit_and_help_act_in_every_state() {
1409 for (name, state) in states() {
1410 assert!(state.acts(Action::Quit), "{name}: q quits");
1411 assert!(state.acts(Action::Help), "{name}: ? opens or closes help");
1412 }
1413 }
1414
1415 #[test]
1416 fn nothing_but_help_back_and_quit_acts_in_the_help_view() {
1417 for (name, state) in states() {
1418 if state.view != View::Help {
1419 continue;
1420 }
1421 for action in ACTIONS {
1422 assert_eq!(
1423 state.acts(action),
1424 matches!(action, Action::Help | Action::Back | Action::Quit),
1425 "{name}: {action:?}"
1426 );
1427 }
1428 }
1429 }
1430
1431 #[test]
1432 fn refresh_does_not_act_while_a_request_is_out() {
1433 for state in [
1434 new(),
1435 after(new(), vec![Event::KeyInfo(Ok(reader()))]),
1436 after(listed(3, Some("c")), vec![Event::Action(Action::More)]),
1437 after(listed(3, None), vec![Event::Action(Action::Refresh)]),
1438 ] {
1439 assert!(
1440 !state.acts(Action::Refresh),
1441 "a second request would race the first: {:?} {:?}",
1442 state.connection,
1443 state.listing
1444 );
1445 }
1446 }
1447
1448 #[test]
1449 fn refresh_acts_after_a_failure_the_server_made() {
1450 for state in [
1451 after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
1452 after(
1453 new(),
1454 vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
1455 ),
1456 after(
1457 new(),
1458 vec![
1459 Event::KeyInfo(Ok(reader())),
1460 Event::Page(Err(ApiError::Status(503, None))),
1461 ],
1462 ),
1463 ] {
1464 assert!(
1465 state.acts(Action::Refresh),
1466 "the server may answer the next request: {:?}",
1467 state.listing
1468 );
1469 }
1470 }
1471
1472 #[test]
1473 fn refresh_does_not_act_for_a_key_that_may_not_list() {
1474 for event in [key(None, "admin"), key(Some("t_example"), "write")] {
1475 let mut state = after(new(), vec![event]);
1476 assert!(
1477 !state.acts(Action::Refresh),
1478 "the key is read once, at start: {:?}",
1479 state.listing
1480 );
1481 let before = state.clone();
1482 assert_eq!(
1483 press(&mut state, Action::Refresh),
1484 Vec::new(),
1485 "nothing is asked of the server"
1486 );
1487 assert_eq!(state, before, "and the refusal stays on the screen");
1488 }
1489 }
1490
1491 #[test]
1492 fn more_acts_only_when_the_server_holds_more_and_nothing_is_out() {
1493 assert!(listed(3, Some("c")).acts(Action::More), "a cursor is held");
1494 assert!(!listed(3, None).acts(Action::More), "every vCon is read");
1495 assert!(
1496 !after(listed(3, Some("c")), vec![Event::Action(Action::More)]).acts(Action::More),
1497 "the next page is on its way"
1498 );
1499 assert!(
1500 !after(listed(3, Some("c")), vec![Event::Action(Action::Refresh)]).acts(Action::More),
1501 "the list is being read again"
1502 );
1503 assert!(!new().acts(Action::More), "nothing is read yet");
1504 }
1505
1506 #[test]
1507 fn open_acts_only_in_a_list_that_shows_a_row() {
1508 assert!(listed(1, None).acts(Action::Open), "one row can be opened");
1509 assert!(
1510 !listed(0, None).acts(Action::Open),
1511 "an empty tenant has none"
1512 );
1513 assert!(!new().acts(Action::Open), "nothing is listed yet");
1514 let detail = after(listed(2, None), vec![Event::Action(Action::Open)]);
1515 assert!(
1516 !detail.acts(Action::Open),
1517 "the detail view is open already"
1518 );
1519 }
1520
1521 #[test]
1522 fn a_list_of_one_row_has_nowhere_to_move() {
1523 let state = listed(1, None);
1524 for action in TRAVEL {
1525 assert!(!state.acts(action), "{action:?} has no other row to select");
1526 }
1527 }
1528
1529 #[test]
1530 fn the_selection_does_not_move_while_the_list_is_not_shown() {
1531 let mut state = after(listed(3, None), vec![Event::Action(Action::Refresh)]);
1532 assert_eq!(state.listing, Listing::Loading, "the list is being read");
1533 press(&mut state, Action::Down);
1534 assert_eq!(state.selected, 0, "the screen shows no row to move from");
1535 press(&mut state, Action::Open);
1536 assert_eq!(state.view, View::List, "and none to open");
1537 }
1538
1539 #[test]
1540 fn back_acts_in_the_detail_and_help_views_only() {
1541 let list = listed(2, None);
1542 assert!(!list.acts(Action::Back), "the list is the first view");
1543 let detail = after(list.clone(), vec![Event::Action(Action::Open)]);
1544 assert!(detail.acts(Action::Back), "Esc returns to the list");
1545 let help = after(list, vec![Event::Action(Action::Help)]);
1546 assert!(help.acts(Action::Back), "Esc closes help");
1547 }
1548
1549 #[test]
1550 fn in_a_detail_view_whose_vcon_is_gone_the_keys_that_move_select_a_listed_one() {
1551 let mut state = after(
1552 listed(5, None),
1553 vec![
1554 Event::Action(Action::Bottom),
1555 Event::Action(Action::Open),
1556 Event::Action(Action::Refresh),
1557 ],
1558 );
1559 state.step(Event::Page(Ok(page(0..1, None))), NOW);
1560 assert!(
1561 state.acts(Action::Down),
1562 "one row is left, and j shows it in place of the message"
1563 );
1564 press(&mut state, Action::Down);
1565 assert_eq!(
1566 state.detail_row().map(|row| row.uuid.clone()),
1567 Some(row(0).uuid),
1568 "the detail view shows the row that is left"
1569 );
1570 assert!(!state.acts(Action::Down), "then there is nowhere to move");
1571 }
1572}