aion-cli 0.26.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
//! `aion update`: install a version and hand the running server over to it.
//!
//! One command for the whole update, because an update that installs a binary
//! and leaves the old process serving has not updated anything — it has only
//! staged a surprise for the next restart. So this verb does both halves and
//! reports both: what it installed, and which server is serving afterwards.
//!
//! The order is deliberate. The install happens FIRST, against a server that
//! is still serving: a failed install then costs nothing but time, because
//! nothing running was touched. Only once a new binary exists on disk is the
//! running server asked to let go.
//!
//! The successor is started from the INSTALLED PATH, never from
//! `current_exe`: the process running the update is the old binary, and
//! starting it again is the one mistake that would make an update silently
//! do nothing.
//!
//! Exit codes: 0 when the target is installed and (where a server was
//! running) serving; 1 when the update was attempted and did not complete —
//! including the one case that must never be quiet, a successful drain
//! followed by a failed boot, which leaves the home with no server and says
//! so; 2 for a refusal before anything was installed or signalled.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use aion_server::config::aion_home;
use clap::Args;

use crate::boot_narration::BootObservation;
use crate::handover::{self, HandoverRefusal};

/// Arguments for `aion update`.
#[derive(Args, Clone, Debug)]
pub struct UpdateArgs {
    /// Version to install. Absent, the latest STABLE version the package
    /// index publishes — the same version a plain `cargo install aion-cli`
    /// would fetch.
    #[arg(long)]
    version: Option<String>,
    /// Path to the TOML server configuration file. Used only to resolve the
    /// drain patience when the running server's record carries none.
    #[arg(long)]
    config: Option<PathBuf>,
    /// Seconds to wait for the running server to begin draining. Absent, the
    /// running server's own recorded drain window governs, then the config's
    /// `drain.timeout_seconds` — the verb never invents a value.
    #[arg(long)]
    patience: Option<std::num::NonZeroU64>,
}

/// Run `aion update`.
pub async fn run(args: &UpdateArgs) -> ExitCode {
    match update(args).await {
        Ok(code) => code,
        Err(refusal) => {
            eprintln!("aion update: {}", refusal.message);
            ExitCode::from(refusal.code)
        }
    }
}

async fn update(args: &UpdateArgs) -> Result<ExitCode, HandoverRefusal> {
    let home = aion_home()
        .map_err(|error| {
            HandoverRefusal::refused(format!("could not resolve the Aion home: {error}"))
        })?
        .path;
    let target = match &args.version {
        Some(version) => version.clone(),
        None => crate::update_index::latest_stable()
            .await
            .map_err(|error| HandoverRefusal::refused(error.to_string()))?,
    };
    let current = env!("CARGO_PKG_VERSION");
    let running = running_server(&home);

    if let Some(reason) = already_current(current, &target, running.as_ref()) {
        println!("{reason}");
        return Ok(ExitCode::SUCCESS);
    }

    println!("installing aion-cli {target} (this binary is {current})");
    let log_path = install_log_path(&home, &target)?;
    install(&target, &log_path)?;
    let executable = installed_binary(&target, &log_path)?;
    println!("installed aion {target} at {}", executable.display());

    let Some(predecessor) = running else {
        println!(
            "no server is running on this home; aion {target} serves it from the next \
             `aion` launch"
        );
        return Ok(ExitCode::SUCCESS);
    };
    let patience = crate::server_restart::resolve_patience(
        args.patience,
        args.config.as_deref(),
        &predecessor,
    )?;
    handover::release_predecessor(&home, &predecessor, patience)?;
    let successor = handover::start_successor(&home, &executable, Some(&predecessor)).await?;
    println!("{}", update_summary(&target, &executable, &successor));
    Ok(ExitCode::SUCCESS)
}

/// The line that names what was ASKED FOR beside what is now RUNNING.
///
/// These are not always the same string, and the difference is not a defect:
/// the pid record carries the `aion-server` version, while the target names
/// the `aion-cli` version that was installed — and an `aion-cli X` resolves
/// whatever `aion-server` its own dependency range admits, which on a
/// patch-release line is routinely a different number. Measured on the
/// acceptance drive: installing `aion-cli 0.25.0` produced a server whose
/// record read `0.25.1`, and a report that quoted only the record would have
/// shown an update from 0.25.1 to 0.25.1 — true of the library, silent about
/// the thing the operator actually changed.
fn update_summary(
    target: &str,
    executable: &Path,
    successor: &aion_server::control::PidRecord,
) -> String {
    let served = if successor.version == target {
        String::new()
    } else {
        format!(
            " (the running server reports {}, the aion-server version this aion-cli \
             resolved)",
            successor.version
        )
    };
    format!(
        "updated: aion-cli {target} installed at {}; this home is served by pid {}{served}",
        executable.display(),
        successor.pid
    )
}

/// The live verified incarnation serving this home, or `None`.
///
/// A record that cannot be READ is deliberately not `None`: it is reported
/// and then treated as "no server to hand over", because the alternative —
/// signalling a pid this verb could not verify — is the one act the control
/// verbs exist to prevent.
fn running_server(home: &Path) -> Option<aion_server::control::PidRecord> {
    match crate::boot_narration::read_observation(home) {
        BootObservation::Live(record) => Some(*record),
        BootObservation::NoRecord | BootObservation::NotLive(_) => None,
        BootObservation::Unreadable(error) => {
            eprintln!(
                "aion update: this home's pid record could not be read ({error}); the \
                 install will run, but no server will be handed over — check `aion \
                 server status` afterwards"
            );
            None
        }
    }
}

/// Why there is nothing to do, when there is nothing to do.
///
/// "Already current" needs BOTH halves: this binary is the target, and the
/// server actually serving this home is running that same version. A box where
/// the binary was updated but the old server is still serving is exactly the
/// state this verb exists to resolve, and reporting it as current would leave
/// the estate one restart away from a version nobody chose.
fn already_current(
    current: &str,
    target: &str,
    running: Option<&aion_server::control::PidRecord>,
) -> Option<String> {
    if current != target {
        return None;
    }
    match running {
        None => Some(format!(
            "already current: aion {current} is installed and no server is running on \
             this home"
        )),
        Some(record) if record.version == target => Some(format!(
            "already current: aion {current} is installed and pid {} is serving this \
             home on that version",
            record.pid
        )),
        Some(record) => {
            println!(
                "this binary is already aion {current}, but pid {} is serving this home \
                 on {} — handing the home over to {current}",
                record.pid, record.version
            );
            None
        }
    }
}

/// Where the install's own output is kept, so a red install is readable after
/// the fact rather than only in the terminal that ran it.
fn install_log_path(home: &Path, target: &str) -> Result<PathBuf, HandoverRefusal> {
    let logs = home.join("logs");
    std::fs::create_dir_all(&logs).map_err(|error| {
        HandoverRefusal::refused(format!(
            "could not create the log directory {}: {error}; nothing was installed",
            logs.display()
        ))
    })?;
    Ok(logs.join(format!("update-{target}.log")))
}

/// Run `cargo install aion-cli --version <target>` into cargo's OWN default
/// root — the place the operator's existing binary already lives.
///
/// The root is deliberately not chosen here. `--root` would install somewhere
/// of this verb's choosing, which on any box whose `aion` came from `cargo
/// install` means the update lands beside the binary in use rather than on it.
///
/// # Errors
///
/// Returns [`HandoverRefusal::refused`] when cargo cannot be run at all, and
/// [`HandoverRefusal::incomplete`] when the install itself fails — the second
/// is not a refusal because time was spent and a partially-built artifact may
/// exist, though nothing RUNNING was touched either way, and the message says
/// so.
fn install(target: &str, log_path: &Path) -> Result<(), HandoverRefusal> {
    let log = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)
        .map_err(|error| {
            HandoverRefusal::refused(format!(
                "could not open the install log {}: {error}; nothing was installed",
                log_path.display()
            ))
        })?;
    let errors = log.try_clone().map_err(|error| {
        HandoverRefusal::refused(format!(
            "could not open the install log {}: {error}; nothing was installed",
            log_path.display()
        ))
    })?;
    println!("install log: {}", log_path.display());
    let status = std::process::Command::new(cargo_binary())
        .args(["install", "aion-cli", "--version", target])
        .stdin(std::process::Stdio::null())
        .stdout(log)
        .stderr(errors)
        .status()
        .map_err(|error| {
            HandoverRefusal::refused(format!(
                "could not run `cargo install`: {error}. Nothing was installed and \
                 nothing running was touched; install cargo, or put it on PATH"
            ))
        })?;
    if !status.success() {
        return Err(HandoverRefusal::incomplete(format!(
            "`cargo install aion-cli --version {target}` failed ({status}). NOTHING \
             RUNNING WAS TOUCHED — the server on this home is the one that was serving \
             before. The install's own output is in {}",
            log_path.display()
        )));
    }
    Ok(())
}

/// The cargo to run: `$CARGO` when a cargo-invoked context named one (so a
/// pinned toolchain stays pinned), otherwise the `cargo` on PATH.
fn cargo_binary() -> PathBuf {
    std::env::var_os("CARGO").map_or_else(|| PathBuf::from("cargo"), PathBuf::from)
}

/// The `aion` binary the install just wrote, PROVEN to be the target version.
///
/// Cargo's install root resolution, in cargo's own precedence:
/// `$CARGO_INSTALL_ROOT`, then `$CARGO_HOME`, then `$HOME/.cargo`. No default
/// is invented past that — a box with none of the three is a box where this
/// verb cannot know where it installed to, and saying so beats starting
/// whatever `aion` happens to be first on PATH.
///
/// The version is then VERIFIED by asking the binary itself. Without that, a
/// stale binary at the expected path (an install that wrote elsewhere, a root
/// this verb resolved wrongly) would be started as the successor and reported
/// as the new version — a silent downgrade wearing an upgrade's report.
///
/// # Errors
///
/// Returns [`HandoverRefusal::incomplete`] when no install root can be
/// resolved, the binary is missing, or it does not report the target version.
fn installed_binary(target: &str, log_path: &Path) -> Result<PathBuf, HandoverRefusal> {
    let root = install_root().ok_or_else(|| {
        HandoverRefusal::incomplete(format!(
            "aion-cli {target} was installed, but this verb cannot tell WHERE: neither \
             CARGO_INSTALL_ROOT, CARGO_HOME, nor HOME is set, so cargo's install root \
             cannot be resolved. Nothing running was touched. The install's output is \
             in {}; restart the server yourself once you have confirmed the path",
            log_path.display()
        ))
    })?;
    let executable = root.join("bin").join("aion");
    if !executable.is_file() {
        return Err(HandoverRefusal::incomplete(format!(
            "aion-cli {target} reported a successful install, but no `aion` binary is \
             at {}. Nothing running was touched. The install's output is in {}",
            executable.display(),
            log_path.display()
        )));
    }
    let reported = binary_version(&executable).map_err(|error| {
        HandoverRefusal::incomplete(format!(
            "the freshly installed binary at {} could not be asked its version \
             ({error}); nothing running was touched",
            executable.display()
        ))
    })?;
    if reported != target {
        return Err(HandoverRefusal::incomplete(format!(
            "the binary at {} reports version {reported}, not the {target} that was \
             just installed — the install wrote somewhere this verb did not look. \
             NOTHING RUNNING WAS TOUCHED; find the installed binary and restart the \
             server with it. The install's output is in {}",
            executable.display(),
            log_path.display()
        )));
    }
    Ok(executable)
}

/// Cargo's install root, in cargo's own precedence.
fn install_root() -> Option<PathBuf> {
    if let Some(root) = std::env::var_os("CARGO_INSTALL_ROOT") {
        return Some(PathBuf::from(root));
    }
    if let Some(home) = std::env::var_os("CARGO_HOME") {
        return Some(PathBuf::from(home));
    }
    std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo"))
}

/// Ask a binary its own version: `aion --version` prints `aion <x.y.z>`.
fn binary_version(executable: &Path) -> Result<String, String> {
    let output = std::process::Command::new(executable)
        .arg("--version")
        .output()
        .map_err(|error| error.to_string())?;
    if !output.status.success() {
        return Err(format!("`--version` exited {}", output.status));
    }
    let line = String::from_utf8_lossy(&output.stdout);
    parse_version_line(&line).ok_or_else(|| format!("`--version` printed `{}`", line.trim()))
}

/// The version out of a clap `--version` line (`aion 0.25.1`).
fn parse_version_line(line: &str) -> Option<String> {
    line.split_whitespace().nth(1).map(ToOwned::to_owned)
}

#[cfg(test)]
mod tests {
    use super::{already_current, install_log_path, parse_version_line, update_summary};
    use aion_server::control::{IncarnationState, PidRecord};

    fn serving(version: &str) -> PidRecord {
        PidRecord {
            pid: 4242,
            started_at_unix_secs: 1,
            binary_sha256: "0".repeat(64),
            version: version.to_owned(),
            commit: "test".to_owned(),
            state: IncarnationState::Serving,
            http_address: None,
            grpc_address: None,
            intended_http_address: None,
            intended_grpc_address: None,
            stage: None,
            stage_detail: None,
            stage_seq: 0,
            stage_updated_at_unix_secs: 0,
            drain_timeout_seconds: 30,
        }
    }

    /// The fast path needs BOTH halves true. An empty home whose binary is
    /// already the target is current; so is a home whose server runs it.
    #[test]
    fn already_current_needs_the_binary_and_the_server_to_agree()
    -> Result<(), Box<dyn std::error::Error>> {
        let idle = already_current("0.25.1", "0.25.1", None)
            .ok_or("an idle home on the target version must read as current")?;
        assert!(idle.contains("no server is running"), "{idle}");

        let serving_target = already_current("0.25.1", "0.25.1", Some(&serving("0.25.1")))
            .ok_or("a server on the target version must read as current")?;
        assert!(serving_target.contains("4242"), "{serving_target}");
        Ok(())
    }

    /// 🔴 The half that is easy to get wrong: the binary is already the
    /// target, but the SERVER is still running an older version. That is
    /// precisely the state an update must resolve — reporting it as "already
    /// current" would leave the estate one restart away from a version nobody
    /// chose, at a moment nobody picked.
    #[test]
    fn a_stale_server_under_a_current_binary_is_not_already_current() {
        assert!(
            already_current("0.26.0", "0.26.0", Some(&serving("0.25.1"))).is_none(),
            "a server on an older version must not read as already current"
        );
    }

    /// A different target is never "already current", whichever direction it
    /// points — `--version` is also how an operator rolls BACK.
    #[test]
    fn a_different_target_is_never_already_current() {
        assert!(already_current("0.25.1", "0.26.0", None).is_none());
        assert!(already_current("0.26.0", "0.25.1", Some(&serving("0.26.0"))).is_none());
    }

    /// The install log is named for the target and lives under the home, so
    /// two updates never overwrite each other's account.
    #[test]
    fn the_install_log_is_named_for_its_target() -> Result<(), Box<dyn std::error::Error>> {
        let home = tempfile::tempdir()?;
        let path =
            install_log_path(home.path(), "0.26.0").map_err(|refusal| refusal.message.clone())?;
        assert!(path.ends_with("logs/update-0.26.0.log"), "{path:?}");
        assert!(path.parent().is_some_and(std::path::Path::is_dir));
        Ok(())
    }

    /// 🔴 The summary names the INSTALLED target, not only the record.
    ///
    /// The pid record carries the `aion-server` version; the target is the
    /// `aion-cli` version installed. On the acceptance drive those differed —
    /// installing `aion-cli 0.25.0` produced a server recording `0.25.1` —
    /// and a report quoting only the record showed an update from 0.25.1 to
    /// 0.25.1, which is true of the library and silent about the change the
    /// operator asked for.
    #[test]
    fn the_summary_names_the_installed_target_and_flags_a_differing_server() {
        let mut record = serving("0.25.1");
        record.pid = 22103;
        let line = update_summary("0.25.0", std::path::Path::new("/root/bin/aion"), &record);
        assert!(line.contains("aion-cli 0.25.0"), "{line}");
        assert!(line.contains("/root/bin/aion"), "{line}");
        assert!(line.contains("22103"), "{line}");
        assert!(
            line.contains("reports 0.25.1"),
            "a server version differing from the target must be named: {line}"
        );

        // When they agree there is nothing extra to say, and saying it anyway
        // would make every ordinary update read as a discrepancy.
        let agreeing = update_summary(
            "0.25.1",
            std::path::Path::new("/root/bin/aion"),
            &serving("0.25.1"),
        );
        assert!(!agreeing.contains("reports"), "{agreeing}");
    }

    /// The version check reads clap's line shape, and refuses anything that
    /// is not one — an empty answer must not silently become "matches".
    #[test]
    fn the_version_line_is_read_or_refused() {
        assert_eq!(
            parse_version_line("aion 0.26.0\n").as_deref(),
            Some("0.26.0")
        );
        assert_eq!(
            parse_version_line("aion-cli 1.2.3").as_deref(),
            Some("1.2.3")
        );
        assert_eq!(parse_version_line("aion"), None);
        assert_eq!(parse_version_line(""), None);
    }
}