marathon-core 0.1.3

Marathon's rules: sessions, timers, triggers and time parsing
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
//! The session state machine. It never reads the clock itself: callers pass
//! `now`, so expiry (including after the Mac slept past a deadline) is
//! fully testable.

use std::time::Duration;

use jiff::Timestamp;
use serde::{Deserialize, Serialize};

use crate::rules::Verdict;

/// What to keep awake.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
    /// Keep the screen on, which also keeps the Mac awake.
    #[default]
    Display,
    /// Keep the Mac awake but let the screen turn off (`-s`).
    System,
}

impl Mode {
    /// Plain words for what this mode keeps awake.
    pub fn describe(self) -> &'static str {
        match self {
            Mode::Display => "Mac and screen stay awake",
            Mode::System => "Mac stays awake, screen may turn off",
        }
    }

    /// The IOKit assertion type that implements this mode.
    pub fn assertion_type(self) -> &'static str {
        match self {
            Mode::Display => "PreventUserIdleDisplaySleep",
            Mode::System => "PreventUserIdleSystemSleep",
        }
    }
}

/// One keep-awake request: from when, until when, and who asked.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Session {
    pub mode: Mode,
    pub started: Timestamp,
    /// Wall-clock end, or `None` for no end time.
    pub until: Option<Timestamp>,
    /// Who asked, e.g. "menu" or "cli"; shown in the assertion name.
    pub source: String,
}

impl Session {
    pub fn remaining(&self, now: Timestamp) -> Option<Duration> {
        self.until
            .map(|u| Duration::try_from(u.duration_since(now)).unwrap_or(Duration::ZERO))
    }

    pub fn is_expired(&self, now: Timestamp) -> bool {
        self.until.is_some_and(|u| u <= now)
    }
}

/// Triggers currently keeping the Mac awake.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuleHold {
    pub mode: Mode,
    /// Why, e.g. "Xcode is running". Never empty.
    pub reasons: Vec<String>,
}

impl RuleHold {
    /// "Xcode is running and on the power adapter".
    pub fn reason(&self) -> String {
        self.reasons.join(" and ")
    }
}

/// What Marathon must remember to come back exactly as it was after a
/// crash or restart. Trigger holds are not kept: they are worked out again
/// from the world.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Snapshot {
    pub session: Option<Session>,
    /// Triggers the user turned off that still applied.
    pub paused: Vec<String>,
    pub battery_low: Option<u8>,
}

/// Holds at most one session plus at most one trigger hold. Every method
/// that may change state returns whether it did, so the caller knows when
/// to update the assertion and UI.
///
/// Turning off while triggers hold pauses each of them until it stops
/// applying, so "off" always means off.
#[derive(Debug, Clone, Default)]
pub struct Keeper {
    session: Option<Session>,
    rule: Option<RuleHold>,
    paused: Vec<String>,
    battery_low: Option<u8>,
}

impl Keeper {
    pub fn session(&self) -> Option<&Session> {
        self.session.as_ref()
    }

    pub fn rule(&self) -> Option<&RuleHold> {
        self.rule.as_ref()
    }

    /// Triggers the user turned off that still apply.
    pub fn paused(&self) -> Option<String> {
        (!self.paused.is_empty()).then(|| self.paused.join(" and "))
    }

    /// The battery level Marathon turned off at, while it stays below the
    /// line.
    pub fn battery_low(&self) -> Option<u8> {
        self.battery_low
    }

    /// The mode to hold an assertion for, if any. The screen stays on if
    /// either the session or the trigger asks for it.
    pub fn wanted(&self) -> Option<Mode> {
        match (self.session.as_ref(), self.rule.as_ref()) {
            (Some(s), Some(r)) if s.mode != r.mode => Some(Mode::Display),
            (s, r) => s.map(|s| s.mode).or(r.map(|r| r.mode)),
        }
    }

    /// Applies the triggers' latest verdict, holding in `mode`. The first
    /// low-battery verdict ends everything; later ones change nothing, so
    /// the user can still turn on by hand.
    pub fn apply(&mut self, verdict: Verdict, mode: Mode) -> bool {
        let rule = match verdict {
            Verdict::BatteryLow(pct) => {
                if self.battery_low.is_some() {
                    return false;
                }
                self.battery_low = Some(pct);
                self.paused.clear();
                self.rule = None;
                self.session = None;
                return true;
            }
            Verdict::Hold(reasons) => reasons,
            Verdict::Idle => Vec::new(),
        };
        // A paused trigger is forgotten once it stops applying; the rest
        // hold.
        let was_low = self.battery_low.take().is_some();
        let before = self.paused.len();
        self.paused.retain(|p| rule.contains(p));
        let reasons: Vec<String> = rule
            .into_iter()
            .filter(|r| !self.paused.contains(r))
            .collect();
        let rule = (!reasons.is_empty()).then_some(RuleHold { mode, reasons });
        let changed = self.rule != rule || self.paused.len() != before || was_low;
        self.rule = rule;
        changed
    }

    /// Starts or replaces the session. A session already expired at `now`
    /// is ignored and leaves the current one running.
    pub fn start(&mut self, session: Session, now: Timestamp) -> bool {
        if session.is_expired(now) {
            return false;
        }
        let changed = self.session.as_ref() != Some(&session);
        self.session = Some(session);
        changed
    }

    /// The user turned off: ends the session and pauses any trigger hold.
    pub fn stop(&mut self) -> bool {
        let had_rule = self.rule.take().map(|r| self.paused.extend(r.reasons));
        self.end_session() | had_rule.is_some()
    }

    /// Ends the session only, leaving triggers alone.
    pub fn end_session(&mut self) -> bool {
        self.session.take().is_some()
    }

    pub fn snapshot(&self) -> Snapshot {
        Snapshot {
            session: self.session.clone(),
            paused: self.paused.clone(),
            battery_low: self.battery_low,
        }
    }

    /// Comes back to a snapshot. A session whose deadline passed while
    /// Marathon was down ends, as it would have had Marathon kept running.
    pub fn restore(&mut self, snap: Snapshot, now: Timestamp) -> bool {
        let snap = Snapshot {
            session: snap.session.filter(|s| !s.is_expired(now)),
            ..snap
        };
        let changed = self.snapshot() != snap;
        self.session = snap.session;
        self.paused = snap.paused;
        self.battery_low = snap.battery_low;
        changed
    }

    /// Ends the session if its deadline has passed.
    pub fn tick(&mut self, now: Timestamp) -> bool {
        if self.session.as_ref().is_some_and(|s| s.is_expired(now)) {
            self.session = None;
            true
        } else {
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ts(s: &str) -> Timestamp {
        s.parse().unwrap()
    }

    fn session(until: Option<&str>) -> Session {
        Session {
            mode: Mode::Display,
            started: ts("2026-12-03T10:00:00Z"),
            until: until.map(ts),
            source: "test".into(),
        }
    }

    #[test]
    fn start_stop() {
        let now = ts("2026-12-03T10:00:00Z");
        let mut k = Keeper::default();
        assert_eq!(k.wanted(), None);
        assert!(k.start(session(None), now));
        assert!(!k.start(session(None), now), "same session is no change");
        assert_eq!(k.wanted(), Some(Mode::Display));
        assert!(k.stop());
        assert!(!k.stop());
        assert_eq!(k.wanted(), None);
    }

    #[test]
    fn expires_at_deadline() {
        let mut k = Keeper::default();
        k.start(
            session(Some("2026-12-03T11:00:00Z")),
            ts("2026-12-03T10:00:00Z"),
        );
        assert_eq!(
            k.session().unwrap().remaining(ts("2026-12-03T10:30:00Z")),
            Some(Duration::from_secs(1800))
        );
        assert!(!k.tick(ts("2026-12-03T10:59:59Z")));
        assert!(k.tick(ts("2026-12-03T11:00:00Z")));
        assert_eq!(k.wanted(), None);
    }

    #[test]
    fn sleeping_past_deadline_expires_on_first_tick() {
        let mut k = Keeper::default();
        k.start(
            session(Some("2026-12-03T11:00:00Z")),
            ts("2026-12-03T10:00:00Z"),
        );
        // The Mac slept from 10:30 to 14:00; the first check after waking ends it.
        assert!(k.tick(ts("2026-12-03T14:00:00Z")));
        assert_eq!(k.session(), None);
    }

    fn hold(reason: &str) -> Verdict {
        Verdict::Hold(vec![reason.into()])
    }

    #[test]
    fn off_pauses_every_trigger_that_applied() {
        let mut k = Keeper::default();
        let both = Verdict::Hold(vec![
            "Zoom is running".into(),
            "on the power adapter".into(),
        ]);
        k.apply(both, Mode::System);
        assert_eq!(
            k.rule().unwrap().reason(),
            "Zoom is running and on the power adapter"
        );
        k.stop();
        // Zoom quits; the adapter was connected all along and stays paused.
        assert!(k.apply(hold("on the power adapter"), Mode::System));
        assert_eq!(k.wanted(), None);
        assert_eq!(k.paused().as_deref(), Some("on the power adapter"));
        // A trigger that starts applying after Off is not paused.
        let more = Verdict::Hold(vec![
            "on the power adapter".into(),
            "Xcode is running".into(),
        ]);
        assert!(k.apply(more, Mode::System));
        assert_eq!(k.rule().unwrap().reason(), "Xcode is running");
    }

    #[test]
    fn trigger_holds_and_releases() {
        let mut k = Keeper::default();
        assert!(k.apply(hold("Xcode is running"), Mode::System));
        assert_eq!(k.wanted(), Some(Mode::System));
        assert!(!k.apply(hold("Xcode is running"), Mode::System));
        assert!(k.apply(Verdict::Idle, Mode::System));
        assert_eq!(k.wanted(), None);
    }

    #[test]
    fn display_wins_when_session_and_trigger_differ() {
        let mut k = Keeper::default();
        k.apply(hold("on the power adapter"), Mode::System);
        k.start(session(None), ts("2026-12-03T10:00:00Z"));
        assert_eq!(k.wanted(), Some(Mode::Display));
    }

    #[test]
    fn off_pauses_trigger_until_its_reason_changes() {
        let mut k = Keeper::default();
        k.apply(hold("Xcode is running"), Mode::System);
        assert!(k.stop());
        assert_eq!(k.wanted(), None);
        assert_eq!(k.paused().as_deref(), Some("Xcode is running"));
        // The same trigger reported again stays paused.
        assert!(!k.apply(hold("Xcode is running"), Mode::System));
        assert_eq!(k.wanted(), None);
        // Once it stops applying, the pause is forgotten...
        k.apply(Verdict::Idle, Mode::System);
        assert_eq!(k.paused(), None);
        // ...so next time it holds again.
        assert!(k.apply(hold("Xcode is running"), Mode::System));
        // A different trigger is not paused.
        k.stop();
        assert!(k.apply(hold("on the power adapter"), Mode::System));
    }

    #[test]
    fn low_battery_stops_once_then_lets_the_user_turn_on() {
        let now = ts("2026-12-03T10:00:00Z");
        let mut k = Keeper::default();
        k.start(session(None), now);
        k.apply(hold("on the power adapter"), Mode::System);
        assert!(k.apply(Verdict::BatteryLow(15), Mode::System));
        assert_eq!(
            (k.wanted(), k.paused(), k.battery_low()),
            (None, None, Some(15))
        );
        // Turned on by hand while still low: stays on.
        k.start(session(None), now);
        assert!(!k.apply(Verdict::BatteryLow(14), Mode::System));
        assert_eq!(k.wanted(), Some(Mode::Display));
        // Charging again clears the notice and triggers work again.
        assert!(k.apply(hold("on the power adapter"), Mode::System));
        assert_eq!(k.battery_low(), None);
    }

    #[test]
    fn end_session_leaves_triggers() {
        let mut k = Keeper::default();
        k.apply(hold("Xcode is running"), Mode::System);
        k.start(session(None), ts("2026-12-03T10:00:00Z"));
        assert!(k.end_session());
        assert_eq!((k.wanted(), k.paused()), (Some(Mode::System), None));
    }

    #[test]
    fn snapshot_round_trip_keeps_deadline_and_pauses() {
        let now = ts("2026-12-03T10:00:00Z");
        let mut k = Keeper::default();
        k.start(session(Some("2026-12-03T12:00:00Z")), now);
        k.apply(hold("Xcode is running"), Mode::System);
        k.stop();
        k.start(session(Some("2026-12-03T12:00:00Z")), now);
        let snap = k.snapshot();
        let json = serde_json::to_string(&snap).unwrap();
        // Back after a crash at 11:00: same session, same end time, same pause.
        let mut back = Keeper::default();
        let restored: Snapshot = serde_json::from_str(&json).unwrap();
        assert!(back.restore(restored, ts("2026-12-03T11:00:00Z")));
        assert_eq!(back.session(), k.session());
        assert_eq!(back.paused().as_deref(), Some("Xcode is running"));
        // The paused trigger stays paused when it is reported again.
        assert!(!back.apply(hold("Xcode is running"), Mode::System));
    }

    #[test]
    fn restore_after_the_deadline_ends_the_session() {
        let mut k = Keeper::default();
        let snap = Snapshot {
            session: Some(session(Some("2026-12-03T12:00:00Z"))),
            ..Snapshot::default()
        };
        k.restore(snap, ts("2026-12-03T13:00:00Z"));
        assert_eq!(k.wanted(), None);
    }

    #[test]
    fn expired_request_leaves_current_session() {
        let now = ts("2026-12-03T10:00:00Z");
        let mut k = Keeper::default();
        k.start(session(None), now);
        assert!(!k.start(session(Some("2026-12-03T09:00:00Z")), now));
        assert_eq!(k.session(), Some(&session(None)));
    }

    #[test]
    fn expired_session_never_starts() {
        let mut k = Keeper::default();
        assert!(!k.start(
            session(Some("2026-12-03T09:00:00Z")),
            ts("2026-12-03T10:00:00Z")
        ));
        assert_eq!(k.wanted(), None);
    }

    #[test]
    fn remaining_never_negative() {
        let s = session(Some("2026-12-03T11:00:00Z"));
        assert_eq!(
            s.remaining(ts("2026-12-03T12:00:00Z")),
            Some(Duration::ZERO)
        );
        assert_eq!(session(None).remaining(ts("2026-12-03T12:00:00Z")), None);
    }
}