eclipse-cli 0.13.4

Command-line interface for eclipse
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! `/gateway` and `/platforms`: what the long-lived process is doing.
//!
//! `eclipse gateway status` answers "is the unit up", which is the beginning of an investigation
//! rather than an answer to it. When a scheduled job did not run, the next questions are when the
//! gateway started, which port it serves, whether that port answers, and what the last run of each
//! job did — and none of that was visible from inside a session.
//!
//! **Read-only, deliberately.** Starting, stopping and restarting stay `eclipse gateway
//! start|stop|restart`: run from inside a session they would take the store this turn is writing
//! to out from under it, and `restart` is not stop-then-start. Nothing here writes a file, opens a
//! store or sends a request the dashboard would have to answer — a report that writes is not a
//! report.
//!
//! Every answer is read from the thing that owns it: the unit file for the profile it was
//! installed for, systemd for the state and the age, the loader for the port, and `cron::views` for
//! the jobs. The verb does not derive any of them a second time.

use crate::gateway_cli::SERVICE_NAME;
use eclipse_core::config::{self, Config, EnvFn, Where};
use eclipse_core::cron;
use std::net::{TcpStream, ToSocketAddrs};
use std::path::PathBuf;
use std::time::Duration;

/// How long the port gets before "down" is the answer.
///
/// The composer draws a frame per key and a report is not worth a stall: a refused connect on
/// loopback comes back in microseconds, and this is the ceiling for the case that does not (a
/// firewall that drops, a host that is not there).
const PORT_TIMEOUT: Duration = Duration::from_millis(400);

/// One row of the platform table.
///
/// There are none: the gateway carries the dashboard API and the scheduler, and no messaging front
/// end has been written. The list exists anyway so the alias prints the shape it will have, rather
/// than an alias that pretends — and the day one lands it is a row here and nothing else.
pub struct Platform {
    pub name: &'static str,
    /// How requests arrive: the transport, not the product.
    pub transport: &'static str,
    /// Connected, disconnected, refused — whatever the transport says.
    pub state: &'static str,
    /// How many requests it has carried since the gateway started.
    pub carried: u64,
}

pub const PLATFORMS: &[Platform] = &[];

// ---------------------------------------------------------------------------------------------
// What the host can say
// ---------------------------------------------------------------------------------------------

/// What this verb is allowed to ask the machine.
///
/// A trait rather than three free functions so a test can drive a gateway that is up, one that is
/// down, and one installed for another profile — none of which needs a systemd user bus or a
/// listening socket.
pub trait Host {
    /// `systemctl --user show` for the unit, or `None` when systemctl did not run.
    fn show(&self) -> Option<String>;
    /// Seconds since boot, for turning a monotonic start time into an age.
    fn uptime_secs(&self) -> Option<f64>;
    /// Whether anything accepts a connection on `host:port`.
    fn answers(&self, host: &str, port: u16) -> bool;
}

/// The real machine.
pub struct System;

impl Host for System {
    fn show(&self) -> Option<String> {
        let out = std::process::Command::new("systemctl")
            .args([
                "--user",
                "show",
                SERVICE_NAME,
                "--no-pager",
                "--property=ActiveState",
                "--property=ActiveEnterTimestampMonotonic",
                "--property=ExecMainPID",
            ])
            .output()
            .ok()?;
        // The exit status is not consulted: `show` on a unit that is not loaded still prints
        // `ActiveState=inactive`, and the unit file is what tells "not installed" from "down".
        Some(String::from_utf8_lossy(&out.stdout).into_owned())
    }

    fn uptime_secs(&self) -> Option<f64> {
        let text = std::fs::read_to_string("/proc/uptime").ok()?;
        text.split_whitespace().next()?.parse().ok()
    }

    fn answers(&self, host: &str, port: u16) -> bool {
        connect(host, port, PORT_TIMEOUT)
    }
}

/// Whether something accepts a connection on `host:port`, within `budget`.
///
/// A TCP connect and not a `GET`: the question is whether the port answers, and a request would
/// have to get past the dashboard's login and its origin guard to say the same thing — two
/// answers that could disagree with the one line this prints.
fn connect(host: &str, port: u16, budget: Duration) -> bool {
    let Ok(mut found) = (host, port).to_socket_addrs() else {
        return false;
    };
    match found.next() {
        Some(addr) => TcpStream::connect_timeout(&addr, budget).is_ok(),
        None => false,
    }
}

/// One `systemctl show` answer, parsed.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Shown {
    /// systemd's own word: `active`, `inactive`, `failed`, `activating`.
    pub state: String,
    pub pid: Option<u32>,
    /// Microseconds on the boot clock at which the unit entered `active`.
    pub entered_us: Option<u64>,
}

pub fn parse_show(text: &str) -> Shown {
    let mut shown = Shown::default();
    for line in text.lines() {
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let value = value.trim();
        match key.trim() {
            "ActiveState" => shown.state = value.to_string(),
            // 0 is what systemd prints for "never"; a job that has never started has no age.
            "ActiveEnterTimestampMonotonic" => {
                shown.entered_us = value.parse::<u64>().ok().filter(|us| *us > 0)
            }
            "ExecMainPID" => shown.pid = value.parse::<u32>().ok().filter(|pid| *pid > 0),
            _ => {}
        }
    }
    shown
}

/// The `ECLIPSE_*` settings a unit carries, as `(profile, config)`.
///
/// systemd spells them `Environment="ECLIPSE_PROFILE=work"`, one per line, and that is the only
/// record of what an unprivileged install was pinned to — a user unit inherits nothing from the
/// shell that wrote it.
pub fn unit_env(text: &str) -> (Option<String>, Option<PathBuf>) {
    let (mut profile, mut config) = (None, None);
    for line in text.lines() {
        let Some(rest) = line.trim().strip_prefix("Environment=") else {
            continue;
        };
        let word = rest.trim().trim_matches('"');
        let Some((key, value)) = word.split_once('=') else {
            continue;
        };
        match key {
            "ECLIPSE_PROFILE" if !value.is_empty() => profile = Some(value.to_string()),
            "ECLIPSE_CONFIG" if !value.is_empty() => config = Some(PathBuf::from(value)),
            _ => {}
        }
    }
    (profile, config)
}

// ---------------------------------------------------------------------------------------------
// What the verb reports
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unit {
    Active {
        age: Option<Duration>,
        pid: Option<u32>,
    },
    /// Installed, and systemd's word for why it is not running.
    Inactive(String),
    /// No unit file: nothing was installed, so nothing is scheduled to bring it back.
    NotInstalled(PathBuf),
    /// systemctl did not run at all.
    Unknown(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoint {
    pub host: String,
    pub port: u16,
    pub answers: bool,
}

/// The newest run across every job — the answer to "did the thing that was supposed to run run".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Newest {
    pub job: String,
    pub outcome: String,
    pub at_ms: i64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Jobs {
    pub total: usize,
    pub enabled: usize,
    pub newest: Option<Newest>,
    /// The jobs file is there but could not be read: say so, because "0 jobs" is a lie a scheduler
    /// with a broken `jobs.toml` would tell very convincingly.
    pub trouble: Option<String>,
}

/// Which profile and config the unit was installed for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Serves {
    pub profile: Option<String>,
    /// `ECLIPSE_CONFIG` from the unit, when it names one.
    pub config: Option<PathBuf>,
    /// The file the unit actually reads: its own, else the default path.
    pub reads: Option<PathBuf>,
    pub unit: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Snapshot {
    pub unit: Unit,
    /// Where it is configured to serve, and whether that port answers. `None` when the config the
    /// unit names did not load — reported as such rather than guessed at.
    pub endpoint: Option<Endpoint>,
    pub endpoint_trouble: Option<String>,
    pub jobs: Jobs,
    pub serves: Serves,
}

/// Everything the verb reports, read from the host and the install.
///
/// `here` is this session's profile, and it is used for one thing: with no unit installed there is
/// no record of what a gateway would serve, and the nearest true answer is the profile a `gateway
/// run` in this shell would use — this one. The `serves` line says the unit was not read, so the
/// report never claims a unit's authority for a guess.
pub fn probe(host: &dyn Host, env: EnvFn, here: Option<&Where>) -> Snapshot {
    // Through the environment the caller gave, not the process's own: a probe that read the real
    // HOME would report this machine's install while the config beside it came from a scratch one.
    let unit_path = env("HOME")
        .filter(|home| !home.is_empty())
        .map(|home| crate::gateway_cli::unit_path(std::path::Path::new(&home)));
    let text = unit_path
        .as_ref()
        .and_then(|path| std::fs::read_to_string(path).ok());
    let installed = unit_path.clone().filter(|_| text.is_some());
    let (unit_profile, config) = text.as_deref().map(unit_env).unwrap_or((None, None));
    let profile = match installed {
        Some(_) => unit_profile,
        None => unit_profile.or_else(|| here.and_then(|place| place.profile.clone())),
    };
    let reads = config
        .clone()
        .or_else(|| {
            installed
                .is_none()
                .then(|| here.and_then(|place| place.config.clone()))
                .flatten()
        })
        .or_else(|| config::config_path(env))
        .filter(|path| path.exists());
    let serves = Serves {
        profile,
        config,
        reads,
        unit: installed,
    };

    let shown = host.show();
    let unit = match (shown.as_deref().map(parse_show), &unit_path) {
        // systemd's word first: it is the only one about the process rather than about a file.
        (Some(shown), _) if shown.state == "active" => Unit::Active {
            age: shown
                .entered_us
                .zip(host.uptime_secs())
                .and_then(|(entered_us, uptime)| {
                    let seconds = uptime - entered_us as f64 / 1_000_000.0;
                    // A clock that moved the wrong way is not an age; it is a clock that moved.
                    (seconds >= 0.0).then(|| Duration::from_secs(seconds as u64))
                }),
            pid: shown.pid,
        },
        (_, Some(path)) if !path.exists() => Unit::NotInstalled(path.clone()),
        (Some(shown), _) => Unit::Inactive(shown.state),
        (None, _) => Unit::Unknown(
            "systemctl did not answer — systemd may not be running for this user".to_string(),
        ),
    };

    let (endpoint, endpoint_trouble) = match &serves.reads {
        None => (
            None,
            Some("no config file to read the port from".to_string()),
        ),
        Some(path) => match Config::load_with_profile(Some(path), serves.profile.as_deref(), env) {
            Ok(cfg) => {
                let (host_name, port) = (cfg.web.host.clone(), cfg.web.port);
                let answers = host.answers(&host_name, port);
                (
                    Some(Endpoint {
                        host: host_name,
                        port,
                        answers,
                    }),
                    None,
                )
            }
            Err(why) => (None, Some(format!("{}: {why}", path.display()))),
        },
    };

    Snapshot {
        unit,
        endpoint,
        endpoint_trouble,
        jobs: jobs(env),
        serves,
    }
}

fn jobs(env: EnvFn) -> Jobs {
    let Some(root) = config::home_root(env) else {
        return Jobs {
            total: 0,
            enabled: 0,
            newest: None,
            trouble: Some("HOME is not set, so there is no cron root".to_string()),
        };
    };
    match cron::views(&root, eclipse_core::session::now_ms() as i64) {
        Ok(views) => {
            let newest = views
                .iter()
                .filter_map(|view| view.last_started_ms.map(|at| (at, view)))
                .max_by_key(|(at, _)| *at)
                .map(|(at, view)| Newest {
                    job: view.name.clone(),
                    // A tick that has started and not finished is the one thing this verb can say
                    // about *now*: the previous run's outcome would be about the run before it.
                    outcome: match (&view.last_outcome, view.last_finished_ms) {
                        (_, Some(finished)) if finished >= at => view
                            .last_outcome
                            .clone()
                            .unwrap_or_else(|| "no outcome recorded".to_string()),
                        _ => "running".to_string(),
                    },
                    at_ms: at,
                });
            Jobs {
                total: views.len(),
                enabled: views.iter().filter(|view| view.enabled).count(),
                newest,
                trouble: None,
            }
        }
        Err(why) => Jobs {
            total: 0,
            enabled: 0,
            newest: None,
            trouble: Some(why.to_string()),
        },
    }
}

// ---------------------------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------------------------

/// `/gateway`: the report. Plain text with no `Style`, because a transcript block is styled by the
/// renderer that draws it and this one serves a `println!` and a `Note` both.
pub fn text(snapshot: &Snapshot, here: Option<&Where>) -> String {
    let mut out = String::new();
    out.push_str(&headline(&snapshot.unit));
    out.push('\n');
    out.push_str(&format!("  up for    {}\n", age_word(&snapshot.unit)));
    if let Unit::Active { pid: Some(pid), .. } = &snapshot.unit {
        out.push_str(&format!("  pid       {pid}\n"));
    }
    match (&snapshot.endpoint, &snapshot.endpoint_trouble) {
        (Some(endpoint), _) => {
            // A port that answers under an inactive unit is a gateway somebody started by hand.
            // Saying only "down" beside "answers" would be the kind of contradiction a reader
            // stops trusting the whole report over.
            let verdict = match (endpoint.answers, &snapshot.unit) {
                (true, Unit::Active { .. }) => "answers".to_string(),
                (true, _) => "answers (the unit is not active)".to_string(),
                (false, _) => "down".to_string(),
            };
            out.push_str(&format!(
                "  port      {}:{} — {verdict}\n",
                endpoint.host, endpoint.port
            ))
        }
        (None, Some(why)) => out.push_str(&format!("  port      unknown — {why}\n")),
        (None, None) => out.push_str("  port      unknown\n"),
    }
    out.push_str(&format!("  jobs      {}\n", jobs_line(&snapshot.jobs)));
    out.push_str(&format!(
        "  serves    {}\n",
        serves_line(&snapshot.serves, here)
    ));
    out.push_str(&format!("  fix       {}\n", fix_line(&snapshot.unit)));
    out
}

/// `/platforms`: the gateway's report, then the platform table. The alias is the gateway's view
/// plus the one thing it cannot show yet, so `/platforms` never says less than `/gateway`.
pub fn platforms(snapshot: &Snapshot, here: Option<&Where>) -> String {
    let mut out = text(snapshot, here);
    out.push('\n');
    if PLATFORMS.is_empty() {
        out.push_str("platforms: none configured\n");
        out.push_str(
            "  the gateway carries the dashboard API and the scheduler; no messaging front end is \
             attached to it\n",
        );
        out.push_str(
            "  a platform would be one row here: name · transport · state · requests carried\n",
        );
        return out;
    }
    out.push_str("platforms:\n");
    for platform in PLATFORMS {
        out.push_str(&format!(
            "  {} · {} · {} · {} requests carried\n",
            platform.name, platform.transport, platform.state, platform.carried
        ));
    }
    out
}

fn headline(unit: &Unit) -> String {
    match unit {
        Unit::Active { .. } => "gateway: up".to_string(),
        Unit::Inactive(word) => format!("gateway: down ({word})"),
        Unit::NotInstalled(path) => format!("gateway: not installed — {}", path.display()),
        Unit::Unknown(why) => format!("gateway: unknown — {why}"),
    }
}

/// The age, or `down`: the issue's own wording, and the same word the port row uses, so one grep
/// answers "is any part of this up".
fn age_word(unit: &Unit) -> String {
    match unit {
        Unit::Active {
            age: Some(age),
            pid: _,
        } => span(*age),
        // Up, but systemd did not say when it started: saying "0 s" would be an invention.
        Unit::Active { age: None, .. } => "unknown".to_string(),
        Unit::Inactive(_) | Unit::NotInstalled(_) => "down".to_string(),
        Unit::Unknown(_) => "unknown".to_string(),
    }
}

/// `3 d 4 h`, `4 h 12 m`, `12 m`, `48 s` — two units, because a third is noise.
fn span(age: Duration) -> String {
    let secs = age.as_secs();
    let (days, hours, minutes) = (secs / 86_400, (secs % 86_400) / 3_600, (secs % 3_600) / 60);
    if days > 0 {
        format!("{days} d {hours} h")
    } else if hours > 0 {
        format!("{hours} h {minutes} m")
    } else if minutes > 0 {
        format!("{minutes} m")
    } else {
        format!("{secs} s")
    }
}

fn jobs_line(jobs: &Jobs) -> String {
    if let Some(why) = &jobs.trouble {
        return format!("could not be read — {why}");
    }
    if jobs.total == 0 {
        return "none scheduled — `eclipse cron add` writes the first".to_string();
    }
    let mut out = format!("{} scheduled, {} enabled", jobs.total, jobs.enabled);
    match &jobs.newest {
        Some(newest) => out.push_str(&format!(
            " · newest run {}: {}, {}",
            newest.job,
            newest.outcome,
            cron::iso_local(newest.at_ms)
        )),
        None => out.push_str(" · nothing has run yet"),
    }
    out
}

/// Which profile the gateway serves, and whether it is the one this session loaded.
///
/// The comparison is what the issue asked for: a gateway started with another profile is reported
/// as another profile, not as this one. Both halves have to match — a profile is a config file, a
/// home and a store, and the same name over a different file is not the same gateway.
fn serves_line(serves: &Serves, here: Option<&Where>) -> String {
    let reads = match &serves.reads {
        Some(path) => path.display().to_string(),
        None => return "nothing to read: no unit file and no config".to_string(),
    };
    let profile = serves.profile.as_deref().unwrap_or("default");
    let name = if serves.profile.is_some() {
        format!("profile {profile}")
    } else {
        "the default profile".to_string()
    };
    if serves.unit.is_none() {
        // Nothing was installed: whatever is answering on the port is not described by a unit, so
        // the only honest thing to name is the config the port above came from — and whose it is.
        return format!(
            "{name}, reading {reads} — no unit was read: this is what this session would serve"
        );
    }
    let Some(place) = here else {
        // A session started without a config file has nothing to compare against, and guessing
        // that it is this one would be the mistake the verb exists to avoid.
        return format!("{name}, reading {reads} — this session read no config file to compare");
    };
    let mine = place.profile.as_deref();
    let my_config = place.config.as_deref();
    let my_reads = my_config.map(|path| path.display().to_string());
    let same_profile = profile == mine.unwrap_or("default");
    let same_config = my_reads.as_deref() == Some(reads.as_str());
    // The session's own file is named only when it is a *different* file: repeating the line above
    // under a different label reads as two files where there is one.
    let this_file = match &my_reads {
        Some(path) if *path != reads => format!(", reading {path}"),
        Some(_) => String::new(),
        None => ", reading no config file".to_string(),
    };
    let tail = match (same_profile, same_config) {
        (true, true) => "this session's own".to_string(),
        (true, false) => format!(
            "same profile, another config file (this session reads {})",
            my_reads.as_deref().unwrap_or("the default one")
        ),
        (false, _) => format!(
            "not this session's (this one is {}{this_file})",
            mine.unwrap_or("default")
        ),
    };
    format!("{name}, reading {reads} — {tail}")
}

fn fix_line(unit: &Unit) -> String {
    match unit {
        Unit::Active { .. } => {
            "read-only — `eclipse gateway start|stop|restart` are the verbs that change it"
                .to_string()
        }
        Unit::Inactive(_) => "eclipse gateway start".to_string(),
        Unit::NotInstalled(_) => "eclipse gateway install".to_string(),
        Unit::Unknown(_) => "eclipse gateway status".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    use std::time::Instant;

    /// A host that answers from a script, so a gateway can be up, down or on another profile
    /// without a systemd user bus.
    struct Fake {
        show: Option<String>,
        uptime: Option<f64>,
        listening: Option<u16>,
    }

    impl Fake {
        fn down() -> Self {
            Fake {
                show: Some("ActiveState=inactive\nExecMainPID=0\n".into()),
                uptime: Some(500.0),
                listening: None,
            }
        }
    }

    impl Host for Fake {
        fn show(&self) -> Option<String> {
            self.show.clone()
        }
        fn uptime_secs(&self) -> Option<f64> {
            self.uptime
        }
        fn answers(&self, _host: &str, port: u16) -> bool {
            self.listening == Some(port)
        }
    }

    fn env_with(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
        move |key: &str| match key {
            "HOME" => Some(home.display().to_string()),
            _ => None,
        }
    }

    /// A scratch install with one config, so a probe has a port to read and nothing else.
    fn install(home: &Path, port: u16) -> PathBuf {
        let root = home.join(".eclipse");
        std::fs::create_dir_all(root.join("config")).unwrap();
        std::fs::write(root.join("config.toml"), format!("[web]\nport = {port}\n")).unwrap();
        root
    }

    fn write_unit(home: &Path, body: &str) -> PathBuf {
        let dir = home.join(".config/systemd/user");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(SERVICE_NAME);
        std::fs::write(&path, body).unwrap();
        path
    }

    fn place(profile: Option<&str>, config: &Path) -> Where {
        Where {
            profile: profile.map(str::to_string),
            config: Some(config.to_path_buf()),
            overlay: None,
            home: None,
            sessions: None,
        }
    }

    #[test]
    fn a_unit_that_is_up_reports_its_age_pid_port_and_jobs() {
        let home = tempfile::tempdir().unwrap();
        let cfg = install(home.path(), 8787);
        std::fs::write(cfg.join("config.toml"), "[web]\nport = 8787\n").unwrap();
        let unit = write_unit(
            home.path(),
            &format!(
                "[Service]\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
                cfg.join("config.toml").display()
            ),
        );
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let shown = format!(
            "ActiveState=active\nActiveEnterTimestampMonotonic={}\nExecMainPID=4242\n",
            // Up for 4 h 12 m of the fake host's 1 h uptime is impossible, so the fake's clock is
            // the one that has to move: see the age test below for the arithmetic itself.
            0
        );
        // Nothing is scheduled in this home, and the port is not listening: the report says so
        // rather than inventing a job.
        let snapshot = probe(
            &Fake {
                show: Some(shown),
                uptime: Some(1000.0),
                listening: None,
            },
            env_fn,
            None,
        );
        let text = text(&snapshot, None);
        assert!(text.starts_with("gateway: up\n"), "{text}");
        assert!(text.contains("  pid       4242\n"), "{text}");
        assert!(
            text.contains("  port      127.0.0.1:8787 — down\n"),
            "{text}"
        );
        assert!(
            text.contains("none scheduled"),
            "an empty cron root says so: {text}"
        );
        assert!(
            text.contains(&format!("reading {}", cfg.join("config.toml").display())),
            "the config the unit names is the one the port came from: {text}"
        );
        assert!(unit.exists());
    }

    /// The age is the difference between the boot clock and the unit's own monotonic start — the
    /// arithmetic that makes "an active unit that restarted four minutes ago" visible.
    #[test]
    fn the_age_is_the_boot_clock_minus_the_units_own_start() {
        let home = tempfile::tempdir().unwrap();
        install(home.path(), 8787);
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        // Boot 10 000 s ago; the unit entered `active` 252 s in, so it is 9 748 s old — 2 h 42 m.
        let snapshot = probe(
            &Fake {
                show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=252000000\n".into()),
                uptime: Some(10_000.0),
                listening: None,
            },
            env_fn,
            None,
        );
        assert!(
            text(&snapshot, None).contains("  up for    2 h 42 m\n"),
            "{}",
            text(&snapshot, None)
        );

        // A start on the boot clock ahead of the uptime is a clock that moved, not a negative age.
        let confused = probe(
            &Fake {
                show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=99000000\n".into()),
                uptime: Some(1.0),
                listening: None,
            },
            env_fn,
            None,
        );
        assert_eq!(age_word(&confused.unit), "unknown");
    }

    #[test]
    fn a_gateway_that_is_down_says_down_for_the_state_the_age_and_the_port() {
        let home = tempfile::tempdir().unwrap();
        install(home.path(), 8787);
        // Installed, and systemd says it is inactive: the ordinary "someone stopped it" case.
        write_unit(
            home.path(),
            "[Service]\nExecStart=/usr/bin/eclipse-gateway\n",
        );
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(&Fake::down(), env_fn, None);
        let text = text(&snapshot, None);
        assert!(text.contains("gateway: down (inactive)"), "{text}");
        assert!(text.contains("  up for    down\n"), "{text}");
        assert!(
            text.contains("  port      127.0.0.1:8787 — down\n"),
            "{text}"
        );
        assert!(text.contains("  fix       eclipse gateway start"), "{text}");
    }

    /// A gateway someone started by hand (`eclipse gateway run`) answers on the port while the
    /// unit is inactive. Both facts are true, and a report that printed "down" beside "answers"
    /// would read as a bug in the report.
    #[test]
    fn a_port_that_answers_under_an_inactive_unit_says_which_it_is() {
        let home = tempfile::tempdir().unwrap();
        let root = install(home.path(), 8787);
        write_unit(
            home.path(),
            "[Service]\nExecStart=/usr/bin/eclipse-gateway\n",
        );
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(
            &Fake {
                show: Some("ActiveState=inactive\n".into()),
                uptime: Some(500.0),
                listening: Some(8787),
            },
            env_fn,
            None,
        );
        let said = text(&snapshot, None);
        assert!(said.contains("gateway: down (inactive)"), "{said}");
        assert!(
            said.contains("  port      127.0.0.1:8787 — answers (the unit is not active)"),
            "{said}"
        );
        // And the active case keeps the plain word.
        let up = probe(
            &Fake {
                show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=0\n".into()),
                uptime: Some(500.0),
                listening: Some(8787),
            },
            env_fn,
            None,
        );
        assert!(
            text(&up, None).contains("  port      127.0.0.1:8787 — answers\n"),
            "{}",
            text(&up, None)
        );
        assert!(root.join("config.toml").exists());
    }

    /// With no unit installed there is no record of what a gateway would serve, so the report uses
    /// the profile a `gateway run` in this shell would use — this session's — and says that is what
    /// it did instead of claiming a unit's authority.
    #[test]
    fn with_no_unit_installed_the_profile_reported_is_the_one_this_session_would_serve() {
        let home = tempfile::tempdir().unwrap();
        let root = install(home.path(), 8787);
        std::fs::create_dir_all(root.join("profiles/lab")).unwrap();
        let overlay = root.join("profiles/lab/config.toml");
        std::fs::write(&overlay, "[web]\nport = 9099\n").unwrap();
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let mine = place(Some("lab"), &root.join("config.toml"));
        let said = text(&probe(&Fake::down(), env_fn, Some(&mine)), Some(&mine));
        assert!(
            said.contains("profile lab, reading "),
            "the overlay's profile, not the default: {said}"
        );
        assert!(
            said.contains("no unit was read: this is what this session would serve"),
            "{said}"
        );
        // The port is the overlay's, because that is the config the profile would load.
        assert!(said.contains("127.0.0.1:9099 — down"), "{said}");
    }

    /// The done-when: with nothing listening the verb still answers, and quickly. The port is a
    /// real closed one, and the whole probe is what is timed — not just the connect.
    #[test]
    fn a_port_nothing_listens_on_is_answered_fast() {
        let free = {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            let port = listener.local_addr().unwrap().port();
            drop(listener);
            port
        };
        let home = tempfile::tempdir().unwrap();
        install(home.path(), free);
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let started = Instant::now();
        let snapshot = probe(&Fake::down(), env_fn, None);
        let took = started.elapsed();
        assert!(
            took < Duration::from_millis(500),
            "a dead gateway must not make the composer pause: {took:?}"
        );
        assert_eq!(
            snapshot.endpoint.as_ref().map(|e| e.answers),
            Some(false),
            "nothing is listening on {free}"
        );
        assert!(
            text(&snapshot, None).contains(&format!("127.0.0.1:{free} — down")),
            "{}",
            text(&snapshot, None)
        );
    }

    /// `--profile` again: the unit that serves another profile is reported as another profile, not
    /// as this session's.
    #[test]
    fn a_unit_installed_for_another_profile_is_not_reported_as_this_sessions() {
        let home = tempfile::tempdir().unwrap();
        let cfg = install(home.path(), 8787);
        write_unit(
            home.path(),
            &format!(
                "[Service]\nEnvironment=\"ECLIPSE_PROFILE=work\"\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
                cfg.join("config.toml").display()
            ),
        );
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let mine = cfg.join("config.toml");
        let snapshot = probe(&Fake::down(), env_fn, None);

        let other = text(&snapshot, Some(&place(None, &mine)));
        assert!(
            other.contains("profile work")
                && other.contains("not this session's (this one is default"),
            "{other}"
        );

        // The same profile and the same file: now it is this session's own.
        let same = text(&snapshot, Some(&place(Some("work"), &mine)));
        assert!(same.contains("this session's own"), "{same}");

        // The same name over a different file is not the same gateway, and the line says which
        // file this session actually read.
        let elsewhere = text(
            &snapshot,
            Some(&place(Some("work"), Path::new("/tmp/other.toml"))),
        );
        assert!(
            elsewhere.contains("same profile, another config file"),
            "{elsewhere}"
        );
        assert!(elsewhere.contains("/tmp/other.toml"), "{elsewhere}");
    }

    /// No unit at all: "not installed" is the headline, the file is named, and the fix is `install`
    /// — not `start`, which would fail on a missing unit.
    #[test]
    fn no_unit_is_named_as_not_installed_with_the_file_and_the_command_that_writes_it() {
        let home = tempfile::tempdir().unwrap();
        install(home.path(), 8787);
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(&Fake::down(), env_fn, None);
        let text = text(&snapshot, None);
        assert!(text.contains("gateway: not installed"), "{text}");
        assert!(text.contains(SERVICE_NAME), "{text}");
        assert!(text.contains("fix       eclipse gateway install"), "{text}");
        assert!(text.contains("no unit was read"), "{text}");
    }

    /// A broken `jobs.toml` is not "0 jobs": the file is named and the reason is said, because a
    /// scheduler that can read no jobs and a scheduler with none look identical otherwise.
    #[test]
    fn a_jobs_file_that_does_not_parse_is_reported_instead_of_counted_as_zero() {
        let home = tempfile::tempdir().unwrap();
        let root = install(home.path(), 8787);
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(root.join("cron/jobs.toml"), "this is not toml [[[").unwrap();
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(&Fake::down(), env_fn, None);
        assert!(snapshot.jobs.trouble.is_some(), "{:?}", snapshot.jobs);
        let text = text(&snapshot, None);
        assert!(
            text.contains("could not be read") && !text.contains("none scheduled"),
            "{text}"
        );
    }

    /// The job count and the newest outcome, from the state file the tick writes — including a
    /// tick that has started and not finished, which is a fact about now rather than about the
    /// run before it.
    #[test]
    fn the_job_count_and_the_newest_outcome_come_from_the_store() {
        let home = tempfile::tempdir().unwrap();
        let root = install(home.path(), 8787);
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(
            root.join("cron/jobs.toml"),
            "[[job]]\nname = \"brief\"\nschedule = \"daily 07:30\"\nprompt = \"say good morning\"\n\
             \n[[job]]\nname = \"sweep\"\nschedule = \"hourly\"\nprompt = \"sweep\"\nenabled = false\n",
        )
        .unwrap();
        std::fs::create_dir_all(root.join("state")).unwrap();
        std::fs::write(
            root.join("state/cron.json"),
            r#"{"jobs": {"brief": {"runs": 2, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "ok"}}}"#,
        )
        .unwrap();
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(&Fake::down(), env_fn, None);
        assert_eq!(snapshot.jobs.total, 2);
        assert_eq!(snapshot.jobs.enabled, 1, "one job is switched off");
        let newest = snapshot.jobs.newest.clone().expect("brief has run");
        assert_eq!(newest.job, "brief");
        assert_eq!(newest.outcome, "ok");
        let line = jobs_line(&snapshot.jobs);
        assert!(line.contains("2 scheduled, 1 enabled"), "{line}");
        assert!(line.contains("newest run brief: ok"), "{line}");

        // Started and not finished: the report says running, not the previous outcome.
        std::fs::write(
            root.join("state/cron.json"),
            r#"{"jobs": {"brief": {"runs": 2, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "ok"},
                "sweep": {"runs": 3, "last_started_ms": 2000, "last_outcome": "ok"}}}"#,
        )
        .unwrap();
        let running = probe(&Fake::down(), env_fn, None);
        assert_eq!(
            running.jobs.newest.as_ref().map(|n| n.outcome.as_str()),
            Some("running")
        );
    }

    /// `/platforms` is the gateway's report plus the truth about platforms: none, and what one
    /// would look like. It never says less than `/gateway`.
    #[test]
    fn platforms_says_there_are_none_and_shows_the_shape_one_would_have() {
        let home = tempfile::tempdir().unwrap();
        install(home.path(), 8787);
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let snapshot = probe(&Fake::down(), env_fn, None);
        let said = platforms(&snapshot, None);
        assert!(said.starts_with("gateway:"), "{said}");
        assert!(said.contains("platforms: none configured"), "{said}");
        assert!(said.contains("no messaging front end"), "{said}");
        assert!(
            said.contains("name · transport · state · requests carried"),
            "the columns are named rather than promised: {said}"
        );
        assert!(PLATFORMS.is_empty(), "there are none yet");
    }

    /// Running the verb leaves the config, the unit file and the store exactly as they were: a
    /// report that writes is not a report.
    #[test]
    fn a_report_changes_no_file() {
        let home = tempfile::tempdir().unwrap();
        let cfg = install(home.path(), 8787);
        let unit = write_unit(
            home.path(),
            "[Service]\nEnvironment=\"ECLIPSE_PROFILE=lab\"\n",
        );
        std::fs::create_dir_all(cfg.join("cron")).unwrap();
        std::fs::write(cfg.join("cron/jobs.toml"), "").unwrap();
        let env = env_with(home.path());
        let env_fn: EnvFn = &env;
        let before = |path: &Path| std::fs::read(path).unwrap_or_default();
        let (config_before, unit_before, jobs_before) = (
            before(&cfg.join("config.toml")),
            before(&unit),
            before(&cfg.join("cron/jobs.toml")),
        );
        let snapshot = probe(&Fake::down(), env_fn, None);
        let _ = platforms(&snapshot, None);
        assert_eq!(before(&cfg.join("config.toml")), config_before);
        assert_eq!(before(&unit), unit_before);
        assert_eq!(before(&cfg.join("cron/jobs.toml")), jobs_before);
        // And no store was opened: counting sessions would have created it.
        assert!(
            !eclipse_core::session::db_path(&cfg.join("state/sessions")).exists(),
            "the verb opened the session store"
        );
    }

    #[test]
    fn the_unit_environment_is_read_as_the_pair_it_is() {
        let text = "[Unit]\nDescription=x\n\n[Service]\n\
                    Environment=\"ECLIPSE_PROFILE=lab\"\n\
                    Environment=\"ECLIPSE_CONFIG=/srv/eclipse/lab.toml\"\n";
        let (profile, config) = unit_env(text);
        assert_eq!(profile.as_deref(), Some("lab"));
        assert_eq!(config.as_deref(), Some(Path::new("/srv/eclipse/lab.toml")));

        // A plain install pins nothing: the unit reads the configured default.
        assert_eq!(
            unit_env("[Service]\nExecStart=/usr/bin/eclipse\n"),
            (None, None)
        );
        // And an empty value is absence, not a profile called "".
        assert_eq!(unit_env("Environment=\"ECLIPSE_PROFILE=\"\n"), (None, None));
    }

    #[test]
    fn systemctls_own_words_are_kept_and_a_zero_is_absence() {
        let shown = parse_show(
            "ActiveState=active\nActiveEnterTimestampMonotonic=1234000000\nExecMainPID=99\n",
        );
        assert_eq!(shown.state, "active");
        assert_eq!(shown.pid, Some(99));
        assert_eq!(shown.entered_us, Some(1_234_000_000));

        // `0` is what systemd prints for "never"/"none", and reporting it as fact would be wrong.
        let never =
            parse_show("ActiveState=failed\nActiveEnterTimestampMonotonic=0\nExecMainPID=0\n");
        assert_eq!(never.state, "failed");
        assert_eq!(never.pid, None);
        assert_eq!(never.entered_us, None);
        assert_eq!(parse_show("").state, "");
    }

    #[test]
    fn an_age_is_two_units_and_no_more() {
        assert_eq!(span(Duration::from_secs(48)), "48 s");
        assert_eq!(span(Duration::from_secs(12 * 60 + 5)), "12 m");
        assert_eq!(span(Duration::from_secs(4 * 3600 + 12 * 60)), "4 h 12 m");
        assert_eq!(span(Duration::from_secs(3 * 86_400 + 4 * 3600)), "3 d 4 h");
    }
}