Skip to main content

byob_protocol/
routines.rs

1//! Routines on the wire (13.19+, cap [`CAP_ROUTINES`]): saved instructions byob carries out
2//! by itself (see [`byob_types::routine`]).
3//!
4//! The engine sends [`crate::ServerMsg::Routines`] after the Welcome and whenever a routine
5//! or its state changes, [`crate::ServerMsg::RoutineRuns`] on request, and
6//! [`crate::ServerMsg::RoutineEvent`] when a run reports, waits for a person or fails (the
7//! desktop turns those into notifications). Schedules come described in words by the engine,
8//! since only it reads rules.
9
10use serde::{Deserialize, Serialize};
11
12pub use byob_types::routine::{MAX_ID_CHARS, MAX_ROUTINES, Missed, Report, Routine, RunCause, RunRecord, RunStatus, Tell, Trigger, id_ok};
13
14use crate::ClientMsg;
15
16/// Cap: the peer handles routine messages.
17pub const CAP_ROUTINES: &str = "routines";
18
19/// One routine as clients see it.
20#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21pub struct RoutineView {
22    pub routine: Routine,
23    /// Its schedules in words (`Every day at 8:00 AM`), one per schedule trigger; a schedule
24    /// the engine can't read says why.
25    #[serde(default, skip_serializing_if = "Vec::is_empty")]
26    pub schedule: Vec<String>,
27    /// When it's next due (ms since the epoch), if it's enabled and scheduled.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub next_run: Option<i64>,
30    /// About how many scheduled runs a month.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub runs_per_month: Option<u32>,
33    /// Its latest run.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub last_run: Option<RunRecord>,
36}
37
38/// What a [`crate::ServerMsg::RoutineEvent`] is about.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum RoutineEventKind {
42    /// A run called `report` (or, for `tell: always`, finished).
43    #[default]
44    Reported,
45    /// A run waits for a person to approve a call.
46    Waiting,
47    /// A run failed.
48    Failed,
49    /// A kind a newer engine sends.
50    #[serde(other)]
51    Other,
52}
53
54/// Size checks of the routine messages (the engine checks the rest).
55pub(crate) fn check_sizes(msg: &ClientMsg) -> Result<(), String> {
56    let id = |s: &str| if id_ok(s) { Ok(()) } else { Err(format!("{:?} isn't a routine id", s.chars().take(80).collect::<String>())) };
57    match msg {
58        ClientMsg::SaveRoutine { routine } => routine.clone().validated().map(|_| ()),
59        ClientMsg::DeleteRoutine { id: i }
60        | ClientMsg::RunRoutine { id: i }
61        | ClientMsg::SetRoutineEnabled { id: i, .. }
62        | ClientMsg::ListRoutineRuns { id: i } => id(i),
63        _ => Ok(()),
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use crate::ServerMsg;
71
72    fn loom() -> Routine {
73        Routine {
74            id: "loom".into(),
75            name: "Loom deals".into(),
76            instructions: "Find deals on a new floor loom.".into(),
77            when: vec![Trigger::Schedule { rule: "FREQ=DAILY".into(), at: "08:00".into(), zone: Some("Europe/Berlin".into()), start: None }],
78            ..Routine::default()
79        }
80    }
81
82    #[test]
83    fn routine_messages_round_trip_and_are_checked() {
84        let msgs = vec![
85            ClientMsg::SaveRoutine { routine: loom() },
86            ClientMsg::SaveRoutine { routine: Routine { id: String::new(), ..loom() } },
87            ClientMsg::DeleteRoutine { id: "loom".into() },
88            ClientMsg::RunRoutine { id: "loom".into() },
89            ClientMsg::SetRoutineEnabled { id: "loom".into(), enabled: false },
90            ClientMsg::ListRoutineRuns { id: "loom".into() },
91        ];
92        for m in msgs {
93            assert!(m.check_sizes().is_ok(), "{}", m.to_json());
94            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
95        }
96        assert!(ClientMsg::RunRoutine { id: "../x".into() }.check_sizes().is_err());
97        assert!(ClientMsg::SaveRoutine { routine: Routine { instructions: "x".repeat(9000), ..loom() } }.check_sizes().is_err());
98        let server = vec![
99            ServerMsg::Routines {
100                items: vec![RoutineView {
101                    routine: loom(),
102                    schedule: vec!["Every day at 8:00 AM".into()],
103                    next_run: Some(5),
104                    runs_per_month: Some(30),
105                    last_run: None,
106                }],
107            },
108            ServerMsg::RoutineRuns {
109                routine: "loom".into(),
110                runs: vec![RunRecord { chat: Some("c".into()), status: RunStatus::Reported, ..RunRecord::default() }],
111            },
112            ServerMsg::RoutineEvent {
113                routine: "loom".into(),
114                name: "Loom deals".into(),
115                chat: Some("c".into()),
116                kind: RoutineEventKind::Reported,
117                title: "Schacht Wolf Pup, 20% off".into(),
118                body: "At The Woolery until Sunday.".into(),
119            },
120        ];
121        for m in server {
122            let json = serde_json::to_string(&m).unwrap();
123            assert_eq!(ServerMsg::from_json(&json).unwrap(), m, "{json}");
124        }
125        // a newer engine's event kind still reads
126        let e = ServerMsg::from_json(r#"{"type":"routine_event","routine":"r","name":"R","kind":"exploded","title":"t"}"#).unwrap();
127        assert!(matches!(e, ServerMsg::RoutineEvent { kind: RoutineEventKind::Other, .. }));
128    }
129}