aion-cli 0.18.0

The `aion` command line: operate Aion durable workflows over gRPC and run the Aion server.
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
//! The bare `aion` launcher: start the workflow server in the background,
//! wait until it answers its own liveness probe, report in plain language
//! where everything lives, and open the ops console in the browser.
//!
//! This is the newcomer's whole path: install from crates.io, type `aion`,
//! get a running server and a console — the server itself scaffolds
//! `<AION_HOME>/config.toml` on a first boot that finds no config (#180),
//! and this launcher reports that in words rather than JSON. `--foreground`
//! keeps the server in this terminal instead; `--no-open` skips the browser.

use std::net::SocketAddr;
use std::path::Path;
use std::process::{ExitCode, Stdio};
use std::time::Instant;

use aion_server::config::{
    CliOverrides, FIRST_RUN_CONFIG, ServerConfig, StoreBackend, StoreConfig, aion_home,
};

use crate::console::{self, HealthProbe};

/// Interval between liveness probes while waiting for the spawned server.
const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(200);

/// How many trailing server-log lines a failure report quotes.
const LOG_TAIL_LINES: usize = 40;

/// How many bytes are read from the end of the (append-forever) server log to
/// find those lines. 64 KiB comfortably covers 40 JSON log lines.
const LOG_TAIL_WINDOW_BYTES: u64 = 64 * 1024;

/// A launcher failure: what to tell the operator and which exit code it
/// carries (2 for configuration/refusal; a spawned server's own exit code,
/// or 1, for a server that failed).
struct LaunchFailure {
    /// Exit code for the process.
    code: u8,
    /// Plain-language report, printed to stderr.
    message: String,
}

impl LaunchFailure {
    /// A configuration or refusal failure (exit 2, matching `aion server`'s
    /// config exit code).
    fn refusal(message: String) -> Self {
        Self { code: 2, message }
    }

    /// A runtime failure of the spawned server. When the server itself
    /// exited, its own code is propagated (so config-refusal 2 stays
    /// distinguishable from a crash); otherwise 1.
    fn runtime(status: Option<std::process::ExitStatus>, message: String) -> Self {
        let code = status
            .and_then(|status| status.code())
            .and_then(|code| u8::try_from(code).ok())
            .filter(|&code| code != 0)
            .unwrap_or(1);
        Self { code, message }
    }
}

/// Run the bare `aion` launcher. `--foreground` delegates to the ordinary
/// in-process server path with browser-open semantics; the default spawns
/// `aion server` detached and reports once it is live.
pub async fn run(foreground: bool, no_open: bool) -> ExitCode {
    if foreground {
        return run_foreground(no_open).await;
    }
    match run_background(no_open).await {
        Ok(code) => code,
        Err(failure) => {
            eprintln!("aion: {}", failure.message);
            ExitCode::from(failure.code)
        }
    }
}

/// `aion --foreground`: the ordinary server path, in this terminal, with the
/// console opened once the listener is live (unless `--no-open`).
async fn run_foreground(no_open: bool) -> ExitCode {
    crate::harness::announce_composed_harness();
    if !no_open {
        crate::server::spawn_browser_open(&CliOverrides::default());
    }
    aion_server::run(CliOverrides::default()).await
}

/// The background path: resolve the address the server will bind, refuse or
/// short-circuit on what already holds it, spawn, wait for liveness, report.
async fn run_background(no_open: bool) -> Result<ExitCode, LaunchFailure> {
    // Resolve the effective config exactly the way the spawned server will
    // (discovery + environment overlay + defaults) so launcher and server
    // cannot disagree about the address. A first run with no config resolves
    // the built-in defaults, and the config the server then scaffolds (#180)
    // carries those same addresses — a coincidence pinned by aion-server's
    // `the_template_addresses_equal_the_built_in_defaults`.
    let overrides = CliOverrides::default();
    let config = ServerConfig::load(&overrides).map_err(|error| {
        LaunchFailure::refusal(format!(
            "could not resolve the server configuration: {error}"
        ))
    })?;
    let home = aion_home().map_err(|error| {
        LaunchFailure::refusal(format!("could not resolve the Aion home: {error}"))
    })?;
    let (store, runtime) = config.into_parts();
    let address = runtime.listen.http;
    let url = console::served_url(address);

    match console::probe_health(address).await {
        HealthProbe::Live => {
            println!("aion is already running.");
            println!("console: {url}");
            open_console(no_open, &url);
            return Ok(ExitCode::SUCCESS);
        }
        HealthProbe::NotAion(answer) => {
            return Err(LaunchFailure::refusal(not_aion_report(
                address,
                answer.as_deref(),
            )));
        }
        HealthProbe::Down => {}
    }

    // Remember which config layer exists BEFORE the spawn, so the report can
    // say whether the server's first boot scaffolded one (#180). `--config`
    // is not offered on the bare launcher, so the layers are `./aion.toml`
    // then `<home>/config.toml`.
    let working_dir = std::env::current_dir().map_err(|error| {
        LaunchFailure::refusal(format!("could not resolve the current directory: {error}"))
    })?;
    let project_config = working_dir.join("aion.toml");
    let home_config = home.path.join("config.toml");
    let pre_existing = [&project_config, &home_config]
        .into_iter()
        .find(|path| path.exists())
        .cloned();

    let log_path = home.path.join("server.log");
    let mut child = spawn_server(&home.path, &log_path)?;

    // Wait for liveness, watching the child so an early death is reported
    // with its own words (the log tail) instead of a silent timeout.
    let started = Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                // Two racing launchers: the loser's child exits on the bind
                // conflict AFTER the winner's server went live. That is not a
                // failure of aion — probe again and report the survivor
                // rather than quoting a healthy server's log as a corpse.
                if matches!(console::probe_health(address).await, HealthProbe::Live) {
                    println!("aion is already running (another launch won the race).");
                    println!("console: {url}");
                    open_console(no_open, &url);
                    return Ok(ExitCode::SUCCESS);
                }
                return Err(LaunchFailure::runtime(
                    Some(status),
                    format!(
                        "the server exited during startup ({status}); its log ends with:\n{}\nfull log: {}",
                        log_tail(&log_path),
                        log_path.display()
                    ),
                ));
            }
            Ok(None) => {}
            Err(error) => {
                return Err(LaunchFailure::runtime(
                    None,
                    format!(
                        "could not watch the server process: {error}; its log is {}",
                        log_path.display()
                    ),
                ));
            }
        }
        if matches!(console::probe_health(address).await, HealthProbe::Live) {
            break;
        }
        if started.elapsed() >= console::LIVE_BUDGET {
            // Still starting is not proven dead: leave the process running
            // rather than destroy a boot that may be seconds from ready, and
            // hand the operator everything needed to watch or stop it.
            return Err(LaunchFailure::runtime(
                None,
                format!(
                    "the server has not answered {url}health/live within {}s; it is still \
                     running as process {pid} — watch its log ({log}) or stop it with `kill {pid}`. \
                     The log ends with:\n{tail}",
                    console::LIVE_BUDGET.as_secs(),
                    pid = child.id(),
                    log = log_path.display(),
                    tail = log_tail(&log_path)
                ),
            ));
        }
        tokio::time::sleep(POLL_INTERVAL).await;
    }

    let config_line = config_report_line(pre_existing.as_deref(), &project_config, &home_config);
    print!(
        "{}",
        ready_report(&store, &config_line, &url, &log_path, child.id())
    );
    open_console(no_open, &url);
    Ok(ExitCode::SUCCESS)
}

/// Spawn `aion server` (this same executable) detached: its own process
/// group, stdin closed, stdout+stderr appended owner-only to
/// `<home>/server.log`.
///
/// Deliberately NOT the worker SDK's contained-child shape: kill-on-drop
/// would take the server down the moment this launcher exits, which is the
/// opposite of the point.
fn spawn_server(home: &Path, log_path: &Path) -> Result<std::process::Child, LaunchFailure> {
    provision_home(home)?;
    let mut log_options = std::fs::OpenOptions::new();
    log_options.create(true).append(true);
    // The log carries whatever the server says — workflow names, paths,
    // addresses — so it gets the same owner-only mode the server gives the
    // config it scaffolds. An existing log's mode belongs to the operator.
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        log_options.mode(0o600);
    }
    let log_out = log_options.open(log_path).map_err(|error| {
        LaunchFailure::refusal(format!(
            "could not open the server log {}: {error}",
            log_path.display()
        ))
    })?;
    let log_err = log_out.try_clone().map_err(|error| {
        LaunchFailure::refusal(format!(
            "could not open the server log {}: {error}",
            log_path.display()
        ))
    })?;
    let executable = std::env::current_exe().map_err(|error| {
        LaunchFailure::refusal(format!("could not resolve the aion executable: {error}"))
    })?;
    let mut command = std::process::Command::new(executable);
    command
        .arg("server")
        .stdin(Stdio::null())
        .stdout(log_out)
        .stderr(log_err);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;
        // Its own process group: terminal signals aimed at the launcher (or
        // the shell that ran it) never reach the server.
        command.process_group(0);
    }
    command.spawn().map_err(|error| {
        LaunchFailure::refusal(format!("could not start the server process: {error}"))
    })
}

/// Provision the Aion home the way the server's own config scaffold does
/// (`ConfinedDir::open_or_create`): create it owner-only, refuse a symlink,
/// and tighten a permissive mode on a directory that already exists — all
/// BEFORE anything (the log file) is written beneath it.
fn provision_home(home: &Path) -> Result<(), LaunchFailure> {
    match std::fs::symlink_metadata(home) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            return Err(LaunchFailure::refusal(format!(
                "the Aion home {} is a symlink; the server refuses symlinked state roots — \
                 point AION_HOME at the real directory instead",
                home.display()
            )));
        }
        Ok(metadata) if !metadata.is_dir() => {
            return Err(LaunchFailure::refusal(format!(
                "the Aion home {} exists but is not a directory",
                home.display()
            )));
        }
        Ok(_) => {
            #[cfg(unix)]
            tighten_home(home)?;
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            std::fs::create_dir_all(home).map_err(|error| {
                LaunchFailure::refusal(format!(
                    "could not create the Aion home {}: {error}",
                    home.display()
                ))
            })?;
            #[cfg(unix)]
            tighten_home(home)?;
        }
        Err(error) => {
            return Err(LaunchFailure::refusal(format!(
                "could not inspect the Aion home {}: {error}",
                home.display()
            )));
        }
    }
    Ok(())
}

/// Owner-only, matching the server's own sensitive-root provisioning (which
/// tightens a permissive owned directory rather than refusing it).
#[cfg(unix)]
fn tighten_home(home: &Path) -> Result<(), LaunchFailure> {
    use std::os::unix::fs::PermissionsExt as _;
    let mode = std::fs::metadata(home)
        .map_err(|error| {
            LaunchFailure::refusal(format!(
                "could not inspect the Aion home {}: {error}",
                home.display()
            ))
        })?
        .permissions()
        .mode();
    if mode & 0o077 != 0 {
        std::fs::set_permissions(home, std::fs::Permissions::from_mode(0o700)).map_err(
            |error| {
                LaunchFailure::refusal(format!(
                    "could not set owner-only permissions on {}: {error}",
                    home.display()
                ))
            },
        )?;
    }
    Ok(())
}

/// The config line of the ready report. "Created" is claimed only when the
/// file did not exist before the spawn AND its bytes now equal the server's
/// embedded first-run template — anything else is reported as what was found.
fn config_report_line(
    pre_existing: Option<&Path>,
    project_config: &Path,
    home_config: &Path,
) -> String {
    if let Some(path) = pre_existing {
        return format!("config: {}", path.display());
    }
    match std::fs::read(home_config) {
        Ok(bytes) if bytes == FIRST_RUN_CONFIG.as_bytes() => format!(
            "config: created {} on first start — comments inside explain every surface it enables",
            home_config.display()
        ),
        Ok(_) => format!(
            "config: {} (appeared during startup; not the stock first-run template)",
            home_config.display()
        ),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => format!(
            "config: built-in defaults (no {} or {})",
            project_config.display(),
            home_config.display()
        ),
        Err(error) => format!(
            "config: {} (could not read it: {error})",
            home_config.display()
        ),
    }
}

/// The plain-language success report Tom's ask names: where the config, data,
/// console, and log live, and how to stop the server. Ends with a newline.
fn ready_report(
    store: &StoreConfig,
    config_line: &str,
    url: &str,
    log_path: &Path,
    pid: u32,
) -> String {
    let data_line = match store.backend {
        StoreBackend::Haematite => match store.data_dir.as_deref() {
            Some(data_dir) => format!("data: {data_dir}"),
            None => "data: haematite store (directory resolved by the server)".to_owned(),
        },
        StoreBackend::Memory => "data: in-memory — state does not survive a stop".to_owned(),
    };
    format!(
        "aion is up.\n{config_line}\n{data_line}\nconsole: {url}\nlog: {log}\n\
         server process id: {pid} (stop it with: kill {pid})\n",
        log = log_path.display()
    )
}

/// Open the console in the platform browser unless `--no-open` said not to.
fn open_console(no_open: bool, url: &str) {
    if no_open {
        return;
    }
    println!("opening your browser…");
    if let Err(error) = console::open_browser(url) {
        // Best-effort by design: the server is up either way.
        println!("could not open a browser ({error}); open {url} yourself");
    }
}

/// The refusal for a port that answered, but not as an Aion server.
fn not_aion_report(address: SocketAddr, answer: Option<&str>) -> String {
    let answered = match answer {
        Some(line) => format!("it answered `{line}`"),
        None => "it accepted the connection but did not answer the liveness probe".to_owned(),
    };
    format!(
        "port {port} at {address} is already in use by something that is not an Aion server \
         ({answered}). Stop that process, or point Aion elsewhere: set `[server] listen_address` \
         in the config, or AION_SERVER_LISTEN_ADDRESS.",
        port = address.port()
    )
}

/// The last [`LOG_TAIL_LINES`] lines of the server log for a failure report,
/// read from a bounded window at the END of the file — the log is
/// append-forever, so an unbounded read would grow with server age. A log
/// that cannot be read is itself reported, never swallowed.
fn log_tail(path: &Path) -> String {
    match read_tail_window(path) {
        Ok(text) => {
            let lines: Vec<&str> = text.lines().collect();
            let start = lines.len().saturating_sub(LOG_TAIL_LINES);
            let tail = lines[start..].join("\n");
            if tail.is_empty() {
                "(the log is empty)".to_owned()
            } else {
                tail
            }
        }
        Err(error) => format!("(could not read the log: {error})"),
    }
}

/// Read at most [`LOG_TAIL_WINDOW_BYTES`] from the end of the file.
fn read_tail_window(path: &Path) -> std::io::Result<String> {
    use std::io::{Read as _, Seek as _};
    let mut file = std::fs::File::open(path)?;
    let length = file.metadata()?.len();
    file.seek(std::io::SeekFrom::Start(
        length.saturating_sub(LOG_TAIL_WINDOW_BYTES),
    ))?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)?;
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

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

    type TestError = Box<dyn std::error::Error>;

    #[test]
    fn the_not_aion_refusal_names_port_and_answer() -> Result<(), std::net::AddrParseError> {
        let address: SocketAddr = "127.0.0.1:8080".parse()?;
        let quoted = not_aion_report(address, Some("HTTP/1.1 404 Not Found"));
        assert!(quoted.contains("port 8080"));
        assert!(quoted.contains("not an Aion server"));
        assert!(quoted.contains("`HTTP/1.1 404 Not Found`"));
        assert!(quoted.contains("AION_SERVER_LISTEN_ADDRESS"));

        let silent = not_aion_report(address, None);
        assert!(silent.contains("port 8080"));
        assert!(silent.contains("did not answer the liveness probe"));
        Ok(())
    }

    #[test]
    fn the_config_line_claims_created_only_for_the_template_bytes() -> Result<(), TestError> {
        let scratch = tempfile::tempdir()?;
        let project_config = scratch.path().join("aion.toml");
        let home_config = scratch.path().join("config.toml");

        // A pre-existing config is reported as found, whatever the home holds.
        let line = config_report_line(Some(&project_config), &project_config, &home_config);
        assert_eq!(line, format!("config: {}", project_config.display()));

        // Absent before AND after: built-in defaults.
        let line = config_report_line(None, &project_config, &home_config);
        assert!(line.starts_with("config: built-in defaults"));

        // Appeared with exactly the template bytes: created by the server.
        std::fs::write(&home_config, FIRST_RUN_CONFIG)?;
        let line = config_report_line(None, &project_config, &home_config);
        assert!(
            line.contains(&format!("created {}", home_config.display())),
            "template bytes must report as created, got: {line}"
        );

        // Appeared with OTHER bytes: found, never claimed as created.
        std::fs::write(&home_config, "# operator's own\n")?;
        let line = config_report_line(None, &project_config, &home_config);
        assert!(
            !line.contains("created") && line.contains("appeared during startup"),
            "foreign bytes must not claim creation, got: {line}"
        );
        Ok(())
    }

    #[test]
    fn the_ready_report_names_every_location_per_backend() {
        let log_path = Path::new("/tmp/aion-home/server.log");
        let mut store = StoreConfig::default();
        store.backend = StoreBackend::Haematite;
        store.data_dir = Some("/data/haematite".to_owned());
        let report = ready_report(&store, "config: X", "http://127.0.0.1:8080/", log_path, 42);
        assert!(report.starts_with("aion is up.\n"));
        assert!(report.contains("config: X\n"));
        assert!(report.contains("data: /data/haematite\n"));
        assert!(report.contains("console: http://127.0.0.1:8080/\n"));
        assert!(report.contains("log: /tmp/aion-home/server.log\n"));
        assert!(report.contains("server process id: 42 (stop it with: kill 42)\n"));

        store.backend = StoreBackend::Memory;
        let report = ready_report(&store, "config: X", "u", log_path, 1);
        assert!(report.contains("data: in-memory — state does not survive a stop\n"));
    }

    #[test]
    fn the_log_tail_is_bounded_and_reports_unreadable_logs() -> Result<(), TestError> {
        let scratch = tempfile::tempdir()?;
        let log = scratch.path().join("server.log");

        let missing = log_tail(&log);
        assert!(
            missing.starts_with("(could not read the log:"),
            "a missing log must be reported, got: {missing}"
        );

        std::fs::write(&log, "")?;
        assert_eq!(log_tail(&log), "(the log is empty)");

        // More lines than the tail keeps: only the last LOG_TAIL_LINES stay,
        // even when the file is larger than the read window.
        let line = "x".repeat(1024);
        let mut many = String::new();
        for n in 0..100 {
            use std::fmt::Write as _;
            let _ = writeln!(many, "{n} {line}");
        }
        std::fs::write(&log, many)?;
        let tail = log_tail(&log);
        assert_eq!(tail.lines().count(), LOG_TAIL_LINES);
        assert!(tail.lines().last().is_some_and(|l| l.starts_with("99 ")));
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn provisioning_tightens_a_permissive_home_and_refuses_a_symlink() -> Result<(), TestError> {
        use std::os::unix::fs::PermissionsExt as _;

        let scratch = tempfile::tempdir()?;
        let home = scratch.path().join("aion-home");
        std::fs::create_dir(&home)?;
        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o755))?;
        provision_home(&home).map_err(|failure| failure.message)?;
        assert_eq!(
            std::fs::metadata(&home)?.permissions().mode() & 0o777,
            0o700,
            "a permissive existing home must be tightened before the log is written"
        );

        let linked = scratch.path().join("linked-home");
        std::os::unix::fs::symlink(&home, &linked)?;
        let Err(failure) = provision_home(&linked) else {
            return Err("a symlinked home must be refused".into());
        };
        assert_eq!(failure.code, 2);
        assert!(failure.message.contains("symlink"));
        Ok(())
    }
}