blubat 0.4.0

Bluetooth battery monitor for macOS: one-shot CLI readings, JSON output and a live TUI
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! blubat's impure half: the event engine, the state file, the banners and the
//! hooks.
//!
//! Everything a reading sets off beyond drawing it happens here, which is what
//! makes the daemon the dashboard minus its view rather than a second
//! implementation: both drive this chain over the same engine and the same
//! state file, and only the poll interval and the presence of a terminal
//! differ. Both sinks are traits and both paths are handed in, so a test drives
//! the whole chain from a reading to a started hook with no notification centre
//! and no shell.

use std::path::PathBuf;

use blubat_core::{AdvertisedThresholds, Config, Engine, Paths, Raised, Snapshot};

use crate::config;
use crate::hooks::{self, Hooks, Outcome, Runner};
use crate::notify::{self, Desktop, Notifier};

/// Whether another blubat owns the side effects at this moment.
type Deferring = Box<dyn Fn() -> bool + Send + Sync>;

/// What one reading came to, for whoever is driving the chain.
///
/// The events travel back rather than only the problems because a frontend has
/// its own use for them: the dashboard's detail view lists what each device has
/// raised, which nothing in this chain keeps.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Observed {
    pub raised: Vec<Raised>,
    /// What went wrong, for the caller to place: stderr would land on top of
    /// whatever the dashboard is drawing.
    pub problems: Vec<String>,
}

/// Everything one reading sets off outside the reducer.
pub struct Effects {
    /// The file `r` re-reads.
    config_file: PathBuf,
    /// Where the arm flags and the debounce clocks are kept between runs.
    state_file: PathBuf,
    engine: Engine,
    /// The engine as the state file last held it, so a reading that moved
    /// nothing costs no write. Most of them move nothing.
    saved: Engine,
    /// What each device's own IOKit node publishes, read once: it describes the
    /// hardware rather than the config, so a reload says nothing about it, and
    /// a device paired mid session contributes its own thresholds next run.
    advertised: AdvertisedThresholds,
    notifier: Box<dyn Notifier>,
    hooks: Box<dyn Hooks>,
    deferring: Deferring,
    /// Whether the last reading belonged to another blubat, so this engine has
    /// been standing still while the state file moved on without it.
    deferred: bool,
}

impl Effects {
    /// The live set: desktop banners and shell hooks, over the state blubat
    /// last wrote about itself.
    ///
    /// Hands back what was wrong with that state rather than failing on it. A
    /// fresh engine only means the next reading records the devices it finds
    /// instead of announcing them, which is a quiet first tick, not an error.
    pub fn live(
        paths: &Paths,
        report: impl Fn(Outcome) + Send + Sync + 'static,
    ) -> (Self, Option<String>) {
        let (engine, problem) = Engine::load(&paths.state_file());

        (
            Self::new(
                paths,
                engine,
                blubat_core::advertised(),
                Box::new(Desktop),
                Box::new(Runner::reporting(report)),
            ),
            problem,
        )
    }

    /// The same wiring over whichever engine, notifier and hook sink are given.
    pub fn new(
        paths: &Paths,
        engine: Engine,
        advertised: AdvertisedThresholds,
        notifier: Box<dyn Notifier>,
        hooks: Box<dyn Hooks>,
    ) -> Self {
        Self {
            config_file: paths.config_file().to_path_buf(),
            state_file: paths.state_file(),
            saved: engine.clone(),
            engine,
            advertised,
            notifier,
            hooks,
            deferring: Box::new(|| false),
            deferred: false,
        }
    }

    /// Hands the side effects to whoever `owner` says is holding them.
    ///
    /// The daemon defers to a dashboard, which owns notifications and hooks for
    /// as long as it is open. Asked again before each one rather than once at
    /// startup, so a dashboard opened or quit mid run is honoured on the next
    /// event rather than the next restart.
    pub fn deferring_to(self, owner: impl Fn() -> bool + Send + Sync + 'static) -> Self {
        Self {
            deferring: Box::new(owner),
            ..self
        }
    }

    /// What each device advertises, which the dashboard judges levels by too.
    pub fn advertised(&self) -> &AdvertisedThresholds {
        &self.advertised
    }

    /// Steps the engine over one reading, announces and dispatches what that
    /// raised, and persists what it moved.
    ///
    /// The reading's own moment is the clock, so what the engine makes of a
    /// reading does not depend on how long it took to arrive.
    ///
    /// Ownership is asked once and honoured for the whole reading, so one
    /// reading is either announced and dispatched or neither. While the side
    /// effects belong to another blubat the engine still steps, so what it
    /// raised still travels back to a frontend, but the state file is left to
    /// the owner: it is the one recording what it announced and when its hooks
    /// last ran, and two writers would each erase the other's.
    pub fn observe(&mut self, reading: &Snapshot, config: &Config) -> Observed {
        let now = reading.read_at;
        let mine = self.mine();
        let mut problems: Vec<String> = self.resumed(mine).into_iter().collect();

        // `step` consumes the engine and hands the next one back, which is what
        // keeps it a pure function of the state it was given.
        let (engine, raised) =
            std::mem::take(&mut self.engine).step(reading, config, &self.advertised, now);
        self.engine = engine;

        problems.extend(raised.iter().filter(|_| mine).filter_map(|raised| {
            notify::announce(raised, &config.notifications, self.notifier.as_ref())
                .and_then(Result::err)
        }));

        for raised in raised.iter().filter(|_| mine) {
            hooks::dispatch(
                raised,
                reading,
                config,
                &mut self.engine,
                self.hooks.as_ref(),
                now,
            );
        }

        // After dispatch, since allowing a hook to run is what records it.
        if mine {
            problems.extend(self.persist());
        }

        Observed { raised, problems }
    }

    /// Whether this blubat is the one that acts on what a reading raised.
    fn mine(&self) -> bool {
        !(self.deferring)()
    }

    /// Picks the state file back up on the first reading after the owner goes.
    ///
    /// What the owner announced and ran is in that file rather than in this
    /// engine, which stopped where it last acted. Reading it back is what stops
    /// an event the owner already announced being announced again, and a hook
    /// it already ran being run inside its debounce window.
    fn resumed(&mut self, mine: bool) -> Option<String> {
        let returned = mine && self.deferred;
        self.deferred = !mine;

        if !returned {
            return None;
        }

        let (engine, problem) = Engine::load(&self.state_file);
        self.saved = engine.clone();
        self.engine = engine;

        problem
    }

    /// Reads the config file again, which is what `r` asks for.
    ///
    /// A file that cannot be read comes back as its message for the caller to
    /// keep the config already in force over: a dashboard that exited on a typo
    /// would be worse than one running on yesterday's thresholds.
    pub fn reload(&self) -> Result<Config, String> {
        Config::load(&self.config_file).map_err(|error| error.to_string())
    }

    /// Writes the dashboard's hidden devices back, which `h` asks for.
    ///
    /// The only write blubat makes to that file, and the reason the reload above
    /// and this sit together: they are the two ends of the one file blubat both
    /// reads and, in this one table, maintains.
    pub fn save_hidden(&self, hidden: &[String]) -> Result<(), String> {
        config::save_hidden(&self.config_file, hidden)
    }

    /// Writes the state file, and only when the last reading moved anything.
    ///
    /// A dashboard tick that raised nothing has nothing new to say about
    /// itself, and at one reading every few seconds those are almost all of
    /// them. A write that failed leaves the last saved state where it was, so
    /// the next reading tries again rather than treating the file as current.
    fn persist(&mut self) -> Option<String> {
        if self.engine == self.saved {
            return None;
        }

        match self.engine.save(&self.state_file) {
            Ok(()) => {
                self.saved = self.engine.clone();

                None
            }
            Err(error) => Some(error.to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

    use blubat_core::{
        Address, ChargeState, Device, Event, Levels, Notifications, Source, Timestamp,
    };

    use crate::hooks::fake::Recorder as StartedHooks;
    use crate::notify::fake::Recorder as PostedBanners;
    use crate::scratch::Scratch;

    use super::*;

    const TRACKPAD: &str = "30-82-16-f2-24-90";
    const READ_AT: i64 = 1_785_643_199;

    fn device(level: Option<u8>, second: i64) -> Device {
        Device {
            address: Address::parse(TRACKPAD).expect("valid address"),
            name: "Paul\u{2019}s Magic Trackpad".to_string(),
            kind: None,
            transport: None,
            levels: Levels {
                main: level,
                ..Levels::default()
            },
            charge: ChargeState::Discharging,
            source: Source::IoKit,
            connected: true,
            read_at: Timestamp::from_unix(READ_AT + second),
        }
    }

    fn reading(level: Option<u8>, second: i64) -> Snapshot {
        Snapshot {
            read_at: Timestamp::from_unix(READ_AT + second),
            devices: vec![device(level, second)],
            degraded: false,
            warnings: Vec::new(),
        }
    }

    /// The same device with the link down, which is what raises `disconnected`.
    fn away(second: i64) -> Snapshot {
        Snapshot {
            devices: vec![Device {
                connected: false,
                ..device(Some(50), second)
            }],
            ..reading(Some(50), second)
        }
    }

    /// The effects under test, with both sinks recording instead of acting.
    fn effects(scratch: &Scratch) -> (Effects, Arc<PostedBanners>, Arc<StartedHooks>) {
        recording(scratch, PostedBanners::new())
    }

    /// The same, over whichever notifier the test wants to give it.
    fn recording(
        scratch: &Scratch,
        banners: PostedBanners,
    ) -> (Effects, Arc<PostedBanners>, Arc<StartedHooks>) {
        let banners = Arc::new(banners);
        let hooks = Arc::new(StartedHooks::new());
        let effects = Effects::new(
            &scratch.paths(),
            Engine::default(),
            AdvertisedThresholds::new(),
            Box::new(Arc::clone(&banners)),
            Box::new(Arc::clone(&hooks)),
        );

        (effects, banners, hooks)
    }

    /// Runs the levels a device reports over successive ticks through the whole
    /// chain, the first of which only records the device.
    fn observe(effects: &mut Effects, config: &Config, levels: &[u8]) -> Vec<String> {
        levels
            .iter()
            .enumerate()
            .flat_map(|(tick, level)| {
                effects
                    .observe(&reading(Some(*level), tick as i64), config)
                    .problems
            })
            .collect()
    }

    #[test]
    fn a_crossing_reaches_the_banner_and_the_hook_it_was_configured_for() {
        let scratch = Scratch::new();
        let config = Config::parse(
            "[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n\n\
             [[hook]]\nevent = \"charged\"\ncommand = \"unplug\"\n",
        )
        .expect("parses");
        let (mut effects, banners, hooks) = effects(&scratch);

        let problems = observe(&mut effects, &config, &[50, 19]);

        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(banners.posted().len(), 1);
        assert_eq!(banners.posted()[0].body, "Battery low at 19%");
        assert_eq!(banners.posted()[0].sound.as_deref(), Some("Glass"));
        assert_eq!(hooks.commands(), ["nag"], "the charged hook waits its turn");
    }

    /// The events come back as well as being acted on, since a frontend has its
    /// own use for them and nothing in this chain keeps them.
    #[test]
    fn what_a_reading_raised_travels_back_beside_what_went_wrong() {
        let scratch = Scratch::new();
        let (mut effects, _, _) = effects(&scratch);

        effects.observe(&reading(Some(50), 0), &Config::default());
        let observed = effects.observe(&reading(Some(19), 1), &Config::default());

        assert!(observed.problems.is_empty(), "{:?}", observed.problems);
        assert_eq!(
            observed
                .raised
                .iter()
                .map(|raised| (raised.event, raised.level))
                .collect::<Vec<_>>(),
            [(Event::LowBattery, Some(19))]
        );
    }

    #[test]
    fn what_was_raised_while_deferring_still_travels_back() {
        let scratch = Scratch::new();
        let (effects, banners, _) = effects(&scratch);
        let mut effects = effects.deferring_to(|| true);

        effects.observe(&reading(Some(50), 0), &Config::default());
        let observed = effects.observe(&reading(Some(19), 1), &Config::default());

        assert_eq!(observed.raised.len(), 1, "the dashboard still lists it");
        assert!(banners.posted().is_empty(), "without announcing it");
    }

    #[test]
    fn an_event_the_notification_toggles_silence_still_runs_its_hook() {
        let scratch = Scratch::new();
        let config = Config::parse(
            "[notifications]\nlow = false\n\n\
             [[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n",
        )
        .expect("parses");
        let (mut effects, banners, hooks) = effects(&scratch);

        observe(&mut effects, &config, &[50, 19]);

        assert!(
            banners.posted().is_empty(),
            "the toggle is honoured: {:?}",
            banners.posted()
        );
        assert_eq!(hooks.commands(), ["nag"], "which says nothing about hooks");
    }

    #[test]
    fn the_sound_and_the_toggles_are_the_ones_the_config_carries() {
        let scratch = Scratch::new();
        let config =
            Config::parse("[notifications]\nconnect = true\nsound = \"Ping\"\n").expect("parses");
        let (mut effects, banners, _) = effects(&scratch);

        effects.observe(&reading(Some(50), 0), &config);
        // Twice, since a link change is announced only once it has held past
        // the coalesce window rather than on sight.
        for second in [60, 120] {
            effects.observe(&away(second), &config);
        }

        assert_eq!(banners.posted().len(), 1, "a link event, on by request");
        assert_eq!(banners.posted()[0].body, "Disconnected");
        assert_eq!(banners.posted()[0].sound.as_deref(), Some("Ping"));
        assert!(
            !Notifications::default().enabled(Event::Disconnected),
            "which the built-in default would not have posted"
        );
    }

    #[test]
    fn the_thresholds_a_device_is_judged_by_are_the_configured_ones() {
        let scratch = Scratch::new();
        let config = Config::parse("[[device]]\nmatch = \"trackpad\"\nlow = 40\n").expect("parses");
        let (mut effects, banners, _) = effects(&scratch);

        observe(&mut effects, &config, &[50, 39]);

        assert_eq!(banners.posted().len(), 1);
        assert_eq!(banners.posted()[0].body, "Battery low at 39%");
    }

    #[test]
    fn what_was_already_raised_survives_into_the_next_run() {
        let scratch = Scratch::new();
        let config = Config::default();
        let (mut effects, first, _) = effects(&scratch);
        observe(&mut effects, &config, &[50, 19]);

        let (engine, problem) = Engine::load(&scratch.paths().state_file());
        let banners = Arc::new(PostedBanners::new());
        let mut restarted = Effects::new(
            &scratch.paths(),
            engine,
            AdvertisedThresholds::new(),
            Box::new(Arc::clone(&banners)),
            Box::new(StartedHooks::new()),
        );

        restarted.observe(&reading(Some(19), 2), &config);

        assert_eq!(problem, None, "the state file read back cleanly");
        assert_eq!(first.posted().len(), 1, "the crossing was announced once");
        assert!(
            banners.posted().is_empty(),
            "and a restart at the same level says nothing: {:?}",
            banners.posted()
        );
    }

    #[test]
    fn a_banner_that_could_not_be_posted_comes_back_while_the_hook_still_runs() {
        let scratch = Scratch::new();
        let config = Config::parse("[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n")
            .expect("parses");
        let (mut effects, _, hooks) =
            recording(&scratch, PostedBanners::failing("no notification centre"));

        let problems = observe(&mut effects, &config, &[50, 19]);

        assert_eq!(problems, ["no notification centre"]);
        assert_eq!(
            hooks.commands(),
            ["nag"],
            "a banner nobody saw says nothing about the hooks"
        );
    }

    #[test]
    fn state_that_cannot_be_written_comes_back_rather_than_being_printed() {
        let scratch = Scratch::new();
        let (mut effects, _, _) = effects(&scratch);
        // A directory where the state file belongs, which is the shape of every
        // unwritable path a test can arrange without changing permissions.
        fs::create_dir_all(scratch.paths().state_file()).expect("a directory in the way");

        let problems = observe(&mut effects, &Config::default(), &[50, 19]);

        assert_eq!(
            problems.len(),
            2,
            "one per reading: a failed write is retried rather than assumed done"
        );
        assert!(
            problems
                .iter()
                .all(|problem| problem.contains("state.toml")),
            "each names the file: {problems:?}"
        );
    }

    #[test]
    fn a_reading_that_moved_nothing_leaves_the_state_file_alone() {
        let scratch = Scratch::new();
        let config = Config::default();
        let (mut effects, _, _) = effects(&scratch);
        observe(&mut effects, &config, &[50, 19]);

        let written = fs::metadata(scratch.paths().state_file()).expect("a written state file");
        effects.observe(&reading(Some(19), 2), &config);

        assert_eq!(
            fs::metadata(scratch.paths().state_file())
                .expect("still there")
                .modified()
                .ok(),
            written.modified().ok(),
            "the level was already fired, so there was nothing to write"
        );
    }

    #[test]
    fn a_hooks_debounce_clock_is_in_the_state_the_reading_wrote() {
        let scratch = Scratch::new();
        let config = Config::parse(
            "[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\ndebounce = \"30m\"\n",
        )
        .expect("parses");
        let (mut effects, _, _) = effects(&scratch);

        observe(&mut effects, &config, &[50, 19]);

        let written =
            fs::read_to_string(scratch.paths().state_file()).expect("a written state file");
        assert!(
            written.contains("hook.nag"),
            "the state was saved after dispatch, so the clock is in it: {written}"
        );
    }

    #[test]
    fn nothing_is_announced_run_or_written_while_another_blubat_owns_the_effects() {
        let scratch = Scratch::new();
        let config = Config::parse("[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n")
            .expect("parses");
        let (effects, banners, hooks) = effects(&scratch);
        let mut effects = effects.deferring_to(|| true);

        observe(&mut effects, &config, &[50, 19]);

        assert!(banners.posted().is_empty(), "{:?}", banners.posted());
        assert!(hooks.commands().is_empty(), "{:?}", hooks.commands());
        assert!(
            !scratch.paths().state_file().exists(),
            "the state file belongs to whichever blubat is acting"
        );
    }

    #[test]
    fn a_crossing_the_owner_announced_is_not_announced_again_when_it_goes() {
        let scratch = Scratch::new();
        let config = Config::default();
        let (mut owner, announced, _) = effects(&scratch);
        let owned = Arc::new(AtomicBool::new(true));
        let (deferring, banners, _) = effects(&scratch);
        let elsewhere = Arc::clone(&owned);
        let mut deferring = deferring.deferring_to(move || elsewhere.load(Ordering::SeqCst));

        for (tick, level) in [50, 19].into_iter().enumerate() {
            let reading = reading(Some(level), tick as i64);
            owner.observe(&reading, &config);
            deferring.observe(&reading, &config);
        }
        owned.store(false, Ordering::SeqCst);
        deferring.observe(&reading(Some(19), 2), &config);

        assert_eq!(announced.posted().len(), 1, "the owner announced it");
        assert!(
            banners.posted().is_empty(),
            "so this one reads its state back and stays quiet: {:?}",
            banners.posted()
        );
    }

    #[test]
    fn the_owner_going_away_restores_the_side_effects() {
        let scratch = Scratch::new();
        let config = Config::default();
        let (mut owner, _, _) = effects(&scratch);
        let owned = Arc::new(AtomicBool::new(true));
        let (deferring, banners, _) = effects(&scratch);
        let elsewhere = Arc::clone(&owned);
        let mut deferring = deferring.deferring_to(move || elsewhere.load(Ordering::SeqCst));

        owner.observe(&reading(Some(50), 0), &config);
        deferring.observe(&reading(Some(50), 0), &config);
        owned.store(false, Ordering::SeqCst);
        deferring.observe(&reading(Some(19), 1), &config);

        assert_eq!(banners.posted().len(), 1);
        assert_eq!(banners.posted()[0].body, "Battery low at 19%");
    }

    /// The owner records a hook run and its debounce clock in the state file.
    /// A deferring blubat that wrote its own copy over the top would erase that
    /// clock and let the hook run again well inside its window.
    #[test]
    fn a_debounce_clock_the_owner_recorded_survives_the_handover() {
        let scratch = Scratch::new();
        let config = Config::parse(
            "[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\ndebounce = \"30m\"\n",
        )
        .expect("parses");
        let (mut owner, _, ran) = effects(&scratch);
        let (deferring, _, never_ran) = effects(&scratch);
        let mut deferring = deferring.deferring_to(|| true);

        for (tick, level) in [50, 19].into_iter().enumerate() {
            let reading = reading(Some(level), tick as i64);
            owner.observe(&reading, &config);
            deferring.observe(&reading, &config);
        }

        assert_eq!(ran.commands(), ["nag"]);
        assert!(never_ran.commands().is_empty());
        assert!(
            fs::read_to_string(scratch.paths().state_file())
                .expect("a written state file")
                .contains("hook.nag"),
            "the owner's clock is the one on disk"
        );
    }

    #[test]
    fn one_reading_is_wholly_acted_on_or_wholly_deferred() {
        let scratch = Scratch::new();
        let config = Config::parse("[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n")
            .expect("parses");
        let (effects, banners, hooks) = effects(&scratch);
        let asks = Arc::new(AtomicU32::new(0));
        let counted = Arc::clone(&asks);
        // Taken from the second answer on, so a chain asking once per event
        // would announce this crossing and then skip the hook that goes with it.
        let mut effects = effects.deferring_to(move || counted.fetch_add(1, Ordering::SeqCst) >= 1);

        observe(&mut effects, &config, &[50, 19]);

        assert_eq!(
            banners.posted().len(),
            hooks.commands().len(),
            "a banner without its hook means the answer moved mid reading"
        );
        assert_eq!(asks.load(Ordering::SeqCst), 2, "one answer per reading");
    }

    #[test]
    fn a_reload_hands_back_the_file_or_the_reason_it_could_not() {
        let scratch = Scratch::new();
        let (effects, _, _) = effects(&scratch);

        assert_eq!(
            effects.reload(),
            Ok(Config::default()),
            "no file is the built-in defaults rather than a problem"
        );

        scratch.write_config("[defaults]\nlow = 30\n");
        assert_eq!(
            effects.reload().expect("parses").defaults.low,
            Some(30),
            "and the file once there is one"
        );

        scratch.write_config("[defaults]\nlow = 20\ncritical = \"ten\"\n");
        let problem = effects
            .reload()
            .expect_err("a string threshold is not a number");
        assert!(problem.contains("line 3"), "{problem}");
    }
}