marathon-engine 0.1.3

The part of Marathon that runs: keeps the Mac awake, keeps time, answers the command
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::Duration;

use dispatch2::{DispatchQoS, DispatchQueue, DispatchTime, GlobalQueueIdentifier};
use marathon_core::protocol::{Holder, Reply, Request, Status};
use marathon_core::rules::Verdict;
use marathon_core::{Keeper, Mode, Session, Snapshot, TimeZone, Timestamp, format_clock};
use marathon_power::Assertion;

/// Called with the new status after every change, outside the engine lock.
pub type Listener = Box<dyn Fn(&Status) + Send + Sync>;

/// Owns the session and the single assertion that backs it.
#[derive(Clone)]
pub struct Engine {
    inner: Arc<Inner>,
}

struct Inner {
    state: Mutex<State>,
    holder: Holder,
    listener: Listener,
    /// Where to save a snapshot after every change, if anywhere.
    state_file: Option<PathBuf>,
    /// Called when another process changed the saved triggers.
    rules_changed: OnceLock<Box<dyn Fn() + Send + Sync>>,
}

#[derive(Default)]
struct State {
    keeper: Keeper,
    held: Option<Assertion>,
    /// Whether this process owns the state file: only the one serving
    /// writes it, so a CLI helper and the app never write over each other.
    saving: bool,
    /// What this engine last wrote to the state file, so unchanged
    /// snapshots aren't rewritten.
    saved: Option<Snapshot>,
}

impl Engine {
    pub fn new(holder: Holder, listener: Listener) -> Self {
        Self::build(holder, listener, None)
    }

    /// An engine that keeps a snapshot in `state_file`, so it can come back
    /// after a crash. Returns it with the snapshot the file held, for
    /// `restore`. It writes the file once it serves (`start_saving`), and
    /// removes it whenever there is nothing to come back to.
    pub fn with_state_file(
        holder: Holder,
        listener: Listener,
        state_file: PathBuf,
    ) -> (Self, Option<Snapshot>) {
        let saved: Option<Snapshot> = crate::store::load(&state_file);
        (Self::build(holder, listener, Some(state_file)), saved)
    }

    fn build(holder: Holder, listener: Listener, state_file: Option<PathBuf>) -> Self {
        Engine {
            inner: Arc::new(Inner {
                state: Mutex::default(),
                holder,
                listener,
                state_file,
                rules_changed: OnceLock::new(),
            }),
        }
    }

    /// Sets what to do when another process changed the saved triggers.
    pub fn on_rules_changed(&self, f: Box<dyn Fn() + Send + Sync>) {
        let _ = self.inner.rules_changed.set(f);
    }

    /// Makes this engine the state file's owner and writes its state now.
    /// The server calls it once it holds the lock.
    pub fn start_saving(&self) {
        let mut st = self.lock();
        st.saving = true;
        st.saved = None;
        self.save(&mut st);
    }

    /// Writes the snapshot if this engine owns the file and it changed.
    fn save(&self, st: &mut State) {
        let snap = st.keeper.snapshot();
        let Some(path) = &self.inner.state_file else {
            return;
        };
        if !st.saving || st.saved.as_ref() == Some(&snap) {
            return;
        }
        let saved = if snap == Snapshot::default() {
            crate::store::remove(path)
        } else {
            crate::store::save(path, &snap)
        };
        match saved {
            Ok(()) => st.saved = Some(snap),
            Err(e) => eprintln!("Marathon: can't save the state for crash recovery: {e}"),
        }
    }

    /// Stops everything and forgets it, so the next launch starts fresh.
    pub fn discard(&self) -> Status {
        self.update(|k, _| {
            let changed = k.snapshot() != Snapshot::default() || k.wanted().is_some();
            *k = Keeper::default();
            changed
        })
        .unwrap_or_else(|_| self.status())
    }

    /// Comes back to a saved snapshot: the same session with the same end
    /// time, and the same paused triggers.
    pub fn restore(&self, snap: Snapshot) -> io::Result<Status> {
        self.update(|k, now| k.restore(snap, now))
    }

    pub fn status(&self) -> Status {
        self.inner.status(&self.lock())
    }

    /// Starts or replaces the session.
    pub fn start(&self, session: Session) -> io::Result<Status> {
        self.update(|k, now| k.start(session, now))
    }

    pub fn stop(&self) -> Status {
        // Releasing an assertion cannot fail.
        self.update(|k, _| k.stop())
            .unwrap_or_else(|_| self.status())
    }

    /// Timer callback for the deadline `until`: ends the session if it is
    /// due. If the timer fired a little early (timer leeway, or the clock was
    /// set back), it is armed again. Timers of replaced sessions do nothing.
    fn expire(&self, until: Timestamp) {
        let _ = self.update(|k, now| k.tick(now));
        let st = self.lock();
        if st.keeper.session().and_then(|s| s.until) == Some(until) {
            self.arm_deadline(until, Timestamp::now());
        }
    }

    /// Applies the triggers' latest verdict; a trigger holds in `mode`.
    pub fn apply(&self, verdict: Verdict, mode: Mode) -> io::Result<Status> {
        self.update(|k, _| k.apply(verdict, mode))
    }

    /// Answers one IPC request.
    pub fn handle(&self, req: Request) -> Reply {
        match req {
            Request::Status => Ok(self.status()),
            Request::RulesChanged => {
                if let Some(f) = self.inner.rules_changed.get() {
                    f();
                }
                Ok(self.status())
            }
            Request::Off => Ok(self.stop()),
            Request::Release => match self.inner.holder {
                Holder::App => Err("Marathon is already running".into()),
                Holder::Cli => {
                    // Under the lock, so no request can slip in between.
                    let mut before = None;
                    let _ = self.update(|k, _| {
                        before = k.session().cloned();
                        k.end_session()
                    });
                    let mut status = self.status();
                    status.active = before.is_some();
                    status.session = before;
                    Ok(status)
                }
            },
            Request::On {
                mode,
                until,
                source,
            } => self
                .start(Session {
                    mode,
                    started: Timestamp::now(),
                    until,
                    source,
                })
                .map_err(|e| e.to_string()),
        }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.inner.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Applies `change`, makes the held assertion match the session, arms
    /// the deadline and tells the listener.
    fn update(&self, change: impl FnOnce(&mut Keeper, Timestamp) -> bool) -> io::Result<Status> {
        let now = Timestamp::now();
        let mut st = self.lock();
        let before = st.keeper.clone();
        if !change(&mut st.keeper, now) {
            return Ok(self.inner.status(&st));
        }
        // On failure the old assertion is still held: go back to the state
        // it was made for.
        let result = st.sync_assertion();
        if result.is_err() {
            st.keeper = before;
        }
        if let Some(until) = st.keeper.session().and_then(|s| s.until) {
            self.arm_deadline(until, now);
        }
        // Saved under the lock, so the file always ends with the latest.
        self.save(&mut st);
        let status = self.inner.status(&st);
        drop(st);
        (self.inner.listener)(&status);
        result.map(|()| status)
    }

    /// Schedules an expiry check at `until` on a wall-clock dispatch timer.
    /// Unlike a thread wait, it keeps counting while the Mac sleeps, so a
    /// deadline that passes during sleep fires right after wake. Nothing
    /// wakes up in between. A timer left over from a replaced session just
    /// finds nothing to expire.
    fn arm_deadline(&self, until: Timestamp, now: Timestamp) {
        let when = walltime_at(until, now);
        let queue = DispatchQueue::global_queue(GlobalQueueIdentifier::QualityOfService(
            DispatchQoS::Utility,
        ));
        let engine = self.clone();
        let _ = queue.after(when, move || engine.expire(until));
    }
}

/// A wall-clock dispatch time `d` from now; it keeps counting while the
/// Mac sleeps.
pub fn walltime_in(d: Duration) -> DispatchTime {
    DispatchTime::WALLTIME_NOW.time(i64::try_from(d.as_nanos()).unwrap_or(i64::MAX))
}

/// The wall-clock dispatch time for `at` (right away if it has passed).
pub fn walltime_at(at: Timestamp, now: Timestamp) -> DispatchTime {
    walltime_in(Duration::try_from(at.duration_since(now)).unwrap_or(Duration::ZERO))
}

impl Inner {
    fn status(&self, st: &State) -> Status {
        Status::of(&st.keeper, Timestamp::now(), self.holder)
    }
}

impl State {
    /// Holds exactly one assertion matching the session, or none. A new
    /// assertion is created before the old one is dropped, so replacing a
    /// session never leaves a gap.
    fn sync_assertion(&mut self) -> io::Result<()> {
        self.held = match self.keeper.wanted() {
            None => None,
            Some(mode) => Some(Assertion::new(
                mode.assertion_type(),
                &assertion_name(mode, &self.keeper),
            )?),
        };
        Ok(())
    }
}

/// The name shown by `pmset -g assertions`, e.g. "Marathon (cli): Mac
/// stays awake, screen may turn off, until 17:30".
fn assertion_name(mode: Mode, k: &Keeper) -> String {
    let mode = mode.describe();
    let reason = k.rule().map(|r| r.reason());
    let Some(s) = k.session() else {
        let reason = reason.unwrap_or_default();
        return format!("Marathon (trigger): {mode} while {reason}");
    };
    let until = match s.until {
        Some(u) => format!("until {}", format_clock(u, &TimeZone::system())),
        None => "no end time".into(),
    };
    let also = reason.map_or(String::new(), |r| format!(", and while {r}"));
    format!("Marathon ({}): {mode}, {until}{also}", s.source)
}

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

    fn engine() -> (Engine, mpsc::Receiver<Status>) {
        let (tx, rx) = mpsc::channel();
        let e = Engine::new(
            Holder::Cli,
            Box::new(move |s| {
                let _ = tx.send(s.clone());
            }),
        );
        (e, rx)
    }

    fn on(mode: Mode, until: Option<Timestamp>) -> Request {
        Request::On {
            mode,
            until,
            source: "test".into(),
        }
    }

    #[test]
    fn state_file_follows_the_session_and_comes_back() {
        let dir = std::env::temp_dir().join(format!("marathon-state-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("state.json");
        let make = || Engine::with_state_file(Holder::Cli, Box::new(|_| {}), path.clone());

        let (e, saved) = make();
        assert_eq!(saved, None);
        e.start_saving();
        e.handle(on(Mode::System, None)).unwrap();
        assert!(path.exists(), "a session is saved");
        e.handle(Request::Off).unwrap();
        assert!(!path.exists(), "nothing to come back to, no file");

        e.handle(on(Mode::System, None)).unwrap();
        let held = e.status().session;
        drop(e); // a crash: the file stays
        let (e, saved) = make();
        let snap = saved.expect("the session was saved");
        assert_eq!(snap.session, held);
        e.restore(snap).unwrap();
        assert!(path.exists(), "not serving yet, so the file is left alone");
        e.start_saving();
        assert_eq!(e.status().session, held);
        e.discard();
        assert!(!path.exists(), "a quit forgets it");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn on_off_holds_and_releases() {
        let (e, rx) = engine();
        let s = e.handle(on(Mode::System, None)).unwrap();
        assert!(s.active);
        assert_eq!(s.session.unwrap().mode, Mode::System);
        assert!(e.lock().held.is_some());
        assert!(rx.recv().unwrap().active);

        let s = e.handle(Request::Off).unwrap();
        assert!(!s.active);
        assert!(e.lock().held.is_none());
        assert!(!rx.recv().unwrap().active);
    }

    #[test]
    fn deadline_timer_expires_session() {
        let (e, rx) = engine();
        let until = Timestamp::now()
            .checked_add(Duration::from_millis(300))
            .unwrap();
        e.handle(on(Mode::System, Some(until))).unwrap();
        assert!(rx.recv().unwrap().active);
        let ended = rx.recv_timeout(Duration::from_secs(3)).unwrap();
        assert!(!ended.active);
        assert!(e.lock().held.is_none());
    }

    #[test]
    fn stale_timer_does_not_end_a_newer_session() {
        let (e, rx) = engine();
        let soon = Timestamp::now()
            .checked_add(Duration::from_millis(200))
            .unwrap();
        e.handle(on(Mode::System, Some(soon))).unwrap();
        e.handle(on(Mode::System, None)).unwrap();
        std::thread::sleep(Duration::from_millis(500));
        assert!(e.status().active);
        assert_eq!(rx.try_iter().filter(|s| !s.active).count(), 0);
    }

    #[test]
    fn replacing_session_keeps_one_assertion() {
        let (e, _rx) = engine();
        e.handle(on(Mode::Display, None)).unwrap();
        let first = e.lock().held.as_ref().unwrap().id();
        e.handle(on(Mode::System, None)).unwrap();
        let second = e.lock().held.as_ref().unwrap().id();
        assert_ne!(first, second);
        assert_eq!(e.status().session.unwrap().mode, Mode::System);
    }

    #[test]
    fn release_hands_back_the_session_and_stops() {
        let (e, _rx) = engine();
        e.handle(on(Mode::System, None)).unwrap();
        let released = e.handle(Request::Release).unwrap();
        assert!(released.active);
        assert_eq!(released.session.unwrap().mode, Mode::System);
        assert!(!e.status().active);
        assert!(e.lock().held.is_none());
    }

    #[test]
    fn app_refuses_release() {
        let e = Engine::new(Holder::App, Box::new(|_| {}));
        e.handle(on(Mode::System, None)).unwrap();
        assert!(e.handle(Request::Release).is_err());
        assert!(e.status().active);
    }

    #[test]
    fn names_assertions() {
        let mut k = Keeper::default();
        let now = Timestamp::now();
        k.start(
            Session {
                mode: Mode::System,
                started: now,
                until: None,
                source: "cli".into(),
            },
            now,
        );
        assert_eq!(
            assertion_name(k.wanted().unwrap(), &k),
            "Marathon (cli): Mac stays awake, screen may turn off, no end time"
        );
        k.apply(Verdict::Hold(vec!["Xcode is running".into()]), Mode::System);
        assert!(assertion_name(k.wanted().unwrap(), &k).ends_with(", and while Xcode is running"));
        k.stop();
        k.apply(
            Verdict::Hold(vec!["on the power adapter".into()]),
            Mode::Display,
        );
        assert_eq!(
            assertion_name(k.wanted().unwrap(), &k),
            "Marathon (trigger): Mac and screen stay awake while on the power adapter"
        );
    }

    #[test]
    fn trigger_holds_an_assertion_and_off_pauses_it() {
        let (e, _rx) = engine();
        let hold = || e.apply(Verdict::Hold(vec!["Zoom is running".into()]), Mode::System);
        let s = hold().unwrap();
        assert!(s.active);
        assert_eq!(s.trigger.as_deref(), Some("Zoom is running"));
        assert!(e.lock().held.is_some());
        let s = e.handle(Request::Off).unwrap();
        assert!(!s.active);
        assert_eq!(s.paused_trigger.as_deref(), Some("Zoom is running"));
        assert!(e.lock().held.is_none());
        assert!(!hold().unwrap().active);
    }
}