zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! `zc update --check` and `zc update --from-crates`: compare this zc with
//! the newest `zc2` published on crates.io, and install it by building that
//! exact version with cargo (the same path `ZAKURO_AUTO_UPDATE` brokers use,
//! [`crate::broker::auto_update`]).
//!
//! `--target <path>` compares and replaces another binary, `--agent` the one
//! the installed agent runs (the app's bundled zc updates the agent's zc this
//! way, whatever version that zc is).
//!
//! The Zakuro Desktop app drives both through `--json`: `--check` prints one
//! object, `--from-crates` prints one event per line (`check`, `up_to_date`,
//! `building`, `verifying`, `installed`, `agent_restarted` or
//! `agent_not_restarted`, then `done`, or `error` at any step).
//!
//! The new binary replaces the running one atomically (a rename, so a running
//! agent keeps its old inode), then the agent is restarted when its
//! LaunchAgent / systemd unit runs this very binary. The restart goes through
//! `launchctl kickstart -k` / `systemctl --user restart`: `zc agent install`
//! would rewrite the plist from this process's environment and drop what the
//! owner set in it.

use crate::broker::auto_update;
use serde::Serialize;
use serde_json::json;
use std::path::{Path, PathBuf};

/// What `--check` reports.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Check {
    pub current: String,
    /// `None` when crates.io could not be read (`error` says why).
    pub latest: Option<String>,
    /// `latest` is strictly newer than `current`.
    pub newer: bool,
    pub source: &'static str,
    #[serde(rename = "crate")]
    pub crate_name: &'static str,
    /// The binary an install would replace.
    pub exe: String,
    /// Its directory is writable (else an install would fail).
    pub writable: bool,
    /// The cargo an install would build with; `None`: no cargo, no install.
    pub cargo: Option<String>,
    pub error: Option<String>,
}

/// Which `zc update` flags this module handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Check,
    FromCrates,
}

pub fn mode(args: &[String]) -> Option<Mode> {
    if args.iter().any(|a| a == "--from-crates") {
        Some(Mode::FromCrates)
    } else if args.iter().any(|a| a == "--check") {
        Some(Mode::Check)
    } else {
        None
    }
}

/// The binary to compare and replace: `--target <path>`, `--agent` (the
/// binary the agent's LaunchAgent / systemd unit runs), else this zc. The
/// app's bundled zc uses `--agent`, so an agent too old to know
/// `--from-crates` still gets updated.
pub fn target(args: &[String]) -> Result<Option<PathBuf>, String> {
    if let Some(i) = args.iter().position(|a| a == "--target") {
        let p = args
            .get(i + 1)
            .filter(|v| !v.starts_with("--"))
            .ok_or("--target needs a path")?;
        return Ok(Some(PathBuf::from(p)));
    }
    if args.iter().any(|a| a == "--agent") {
        return agent_binary()
            .map(Some)
            .ok_or_else(|| "no zc agent is installed (zc agent install)".to_string());
    }
    Ok(None)
}

pub fn run(mode: Mode, args: &[String]) -> i32 {
    let json = args.iter().any(|a| a == "--json");
    let target = match target(args) {
        Ok(t) => t,
        Err(e) => {
            return Out { json }.error(&e);
        }
    };
    match mode {
        Mode::Check => {
            let c = check(target.as_deref());
            if json {
                println!("{}", serde_json::to_string(&c).unwrap_or_default());
            } else {
                let flag = if args.iter().any(|a| a == "--agent") {
                    " --agent"
                } else {
                    ""
                };
                print!(
                    "{}",
                    format_check(&c).replace("--from-crates", &format!("--from-crates{flag}"))
                );
            }
            if c.error.is_some() {
                1
            } else {
                0
            }
        }
        Mode::FromCrates => install(json, target.as_deref()),
    }
}

fn current_exe() -> PathBuf {
    std::env::current_exe()
        .ok()
        .map(|p| std::fs::canonicalize(&p).unwrap_or(p))
        .unwrap_or_default()
}

/// `target`'s version: this build's own when it is this binary, else what
/// the binary prints for `--version`.
fn version_of(target: &Path) -> Option<String> {
    let me = current_exe();
    let t = std::fs::canonicalize(target).unwrap_or_else(|_| target.to_path_buf());
    if t == me {
        return Some(env!("CARGO_PKG_VERSION").to_string());
    }
    let bytes = std::fs::read(&t).ok()?;
    crate::update::binary_version(&t, &bytes)
}

pub fn check(target: Option<&Path>) -> Check {
    let exe = target
        .map(|t| std::fs::canonicalize(t).unwrap_or_else(|_| t.to_path_buf()))
        .unwrap_or_else(current_exe);
    let (current, version_error) = match version_of(&exe) {
        Some(v) => (v, None),
        None => (
            String::new(),
            Some(format!("could not read the version of {}", exe.display())),
        ),
    };
    let writable = exe.parent().is_some_and(crate::update::dir_writable);
    let cargo = auto_update::cargo_from_env()
        .ok()
        .map(|p| p.display().to_string());
    let (latest, error) = match latest_on_crates() {
        Ok(v) => (Some(v), version_error),
        Err(e) => (None, Some(format!("could not read crates.io: {e}"))),
    };
    let newer = latest
        .as_deref()
        .is_some_and(|l| auto_update::is_newer_version(l, &current));
    Check {
        current,
        latest,
        newer,
        source: "crates.io",
        crate_name: auto_update::CRATE_NAME,
        exe: exe.display().to_string(),
        writable,
        cargo,
        error,
    }
}

fn latest_on_crates() -> Result<String, String> {
    let index = auto_update::index_url_from_env()?;
    let fetch = crate::update::UreqFetcher::with_user_agent(concat!(
        "zc/",
        env!("CARGO_PKG_VERSION"),
        " (update check)"
    ));
    auto_update::check_latest(&fetch, &index)
}

pub fn format_check(c: &Check) -> String {
    match (&c.latest, &c.error) {
        (_, Some(e)) => format!("zc {} · {e}\n", c.current),
        (Some(l), None) if c.newer => format!(
            "zc {} · crates.io has {} {l}\n  Install it: zc update --from-crates{}\n",
            c.current,
            c.crate_name,
            if c.cargo.is_none() {
                " (needs cargo: https://rustup.rs)"
            } else {
                ""
            }
        ),
        (Some(l), None) => format!(
            "zc {} is up to date (crates.io {} {l})\n",
            c.current, c.crate_name
        ),
        (None, None) => format!("zc {}\n", c.current),
    }
}

/// Prints one line per step: JSON events, or plain text.
struct Out {
    json: bool,
}

impl Out {
    fn event(&self, v: serde_json::Value, text: &str) {
        if self.json {
            println!("{v}");
        } else if !text.is_empty() {
            println!("{text}");
        }
    }

    fn error(&self, message: &str) -> i32 {
        if self.json {
            println!("{}", json!({ "event": "error", "message": message }));
        } else {
            eprintln!("✗ {message}");
        }
        1
    }
}

fn install(json: bool, target: Option<&Path>) -> i32 {
    let out = Out { json };
    let c = check(target);
    if let Some(e) = &c.error {
        return out.error(e);
    }
    let exe = PathBuf::from(&c.exe);
    let latest = c.latest.clone().unwrap_or_default();
    out.event(
        json!({ "event": "check", "current": c.current, "latest": latest }),
        &format!("zc {} · crates.io {} {latest}", c.current, c.crate_name),
    );
    if !c.newer {
        out.event(
            json!({ "event": "up_to_date", "version": c.current }),
            "Already up to date.",
        );
        return 0;
    }
    if c.cargo.is_none() {
        return out.error(
            "cargo not found: install Rust (https://rustup.rs), then try again; zc builds the new version from crates.io",
        );
    }
    if !c.writable {
        return out.error(&format!(
            "{} is not writable, so this zc cannot replace itself",
            Path::new(&c.exe)
                .parent()
                .unwrap_or(Path::new("/"))
                .display()
        ));
    }
    out.event(
        json!({ "event": "building", "version": latest, "cargo": c.cargo }),
        &format!("Building zc {latest} from crates.io (several minutes)…"),
    );
    let bytes = match auto_update::build_from_crates_for(&latest, &exe) {
        Ok(b) => b,
        Err(e) => return out.error(&format!("build failed: {e}")),
    };
    out.event(
        json!({ "event": "verifying", "version": latest }),
        "Checking the new binary…",
    );
    if let Err(e) = auto_update::verify_binary_for(&exe, &bytes, &latest) {
        return out.error(&format!("the built zc {latest} failed its check: {e}"));
    }
    if let Err(e) = crate::update::replace_binary_atomic(&exe, &bytes) {
        return out.error(&format!("could not install it over {}: {e}", c.exe));
    }
    out.event(
        json!({ "event": "installed", "version": latest, "exe": c.exe }),
        &format!("✓ Installed zc {latest} at {}", c.exe),
    );
    match restart_agent(Path::new(&c.exe)) {
        Restart::Restarted => out.event(
            json!({ "event": "agent_restarted" }),
            "✓ Restarted the zc agent on the new version.",
        ),
        Restart::NotThisBinary(why) | Restart::Failed(why) => out.event(
            json!({ "event": "agent_not_restarted", "reason": why }),
            &format!("  The agent was not restarted: {why}"),
        ),
    }
    out.event(json!({ "event": "done", "version": latest }), "");
    0
}

#[derive(Debug, PartialEq, Eq)]
enum Restart {
    Restarted,
    NotThisBinary(String),
    Failed(String),
}

/// The binary the agent's service definition runs: the first `<string>`
/// after `<key>ProgramArguments</key>` in the plist, or the first word of
/// `ExecStart=` in the unit. Pure.
pub fn service_binary(definition: &str) -> Option<String> {
    let mut lines = definition.lines().map(str::trim);
    while let Some(l) = lines.next() {
        if l == "<key>ProgramArguments</key>" {
            for l in lines.by_ref() {
                if let Some(v) = l
                    .strip_prefix("<string>")
                    .and_then(|v| v.strip_suffix("</string>"))
                {
                    return Some(v.replace("&amp;", "&"));
                }
            }
            return None;
        }
        if let Some(rest) = l.strip_prefix("ExecStart=") {
            return rest
                .split_whitespace()
                .next()
                .map(|w| w.trim_matches('"').to_string());
        }
    }
    None
}

fn service_definition() -> Option<String> {
    let home = std::env::var_os("HOME").map(PathBuf::from)?;
    #[cfg(target_os = "macos")]
    let path = crate::agent::launchd::plist_path(&home);
    #[cfg(target_os = "linux")]
    let path =
        crate::agent::systemd::unit_path(&home, std::env::var("XDG_CONFIG_HOME").ok().as_deref());
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    let path: Option<PathBuf> = {
        let _ = home;
        None
    };
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    let path = Some(path);
    std::fs::read_to_string(path?).ok()
}

/// The zc binary the installed agent runs.
pub fn agent_binary() -> Option<PathBuf> {
    service_definition()
        .and_then(|d| service_binary(&d))
        .map(PathBuf::from)
}

/// Whether the agent's service definition runs `exe`: the plist names it in a
/// `<string>` of ProgramArguments, the unit in `ExecStart`. Pure.
pub fn service_runs(definition: &str, exe: &Path) -> bool {
    let exe = exe.display().to_string();
    definition.lines().any(|l| {
        let l = l.trim();
        l == format!("<string>{exe}</string>")
            || l.strip_prefix("ExecStart=")
                .and_then(|rest| rest.split_whitespace().next())
                .is_some_and(|first| first.trim_matches('"') == exe)
    })
}

fn restart_agent(exe: &Path) -> Restart {
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return Restart::NotThisBinary("no HOME".into());
    };
    #[cfg(target_os = "macos")]
    {
        let plist = crate::agent::launchd::plist_path(&home);
        let Ok(text) = std::fs::read_to_string(&plist) else {
            return Restart::NotThisBinary("no zc agent is installed".into());
        };
        if !service_runs(&text, exe) {
            return Restart::NotThisBinary(format!(
                "the agent runs another zc ({} does not name {})",
                plist.display(),
                exe.display()
            ));
        }
        let target = format!(
            "{}/{}",
            crate::agent::launchd::gui_domain(),
            crate::agent::launchd::LABEL
        );
        match std::process::Command::new("launchctl")
            .args(["kickstart", "-k", &target])
            .status()
        {
            Ok(s) if s.success() => Restart::Restarted,
            Ok(s) => Restart::Failed(format!("launchctl kickstart exited with {s}")),
            Err(e) => Restart::Failed(format!("launchctl: {e}")),
        }
    }
    #[cfg(target_os = "linux")]
    {
        let unit = crate::agent::systemd::unit_path(
            &home,
            std::env::var("XDG_CONFIG_HOME").ok().as_deref(),
        );
        let Ok(text) = std::fs::read_to_string(&unit) else {
            return Restart::NotThisBinary("no zc agent is installed".into());
        };
        if !service_runs(&text, exe) {
            return Restart::NotThisBinary(format!(
                "the agent runs another zc ({} does not name {})",
                unit.display(),
                exe.display()
            ));
        }
        match std::process::Command::new("systemctl")
            .args(["--user", "restart", crate::agent::systemd::UNIT])
            .status()
        {
            Ok(s) if s.success() => Restart::Restarted,
            Ok(s) => Restart::Failed(format!("systemctl exited with {s}")),
            Err(e) => Restart::Failed(format!("systemctl: {e}")),
        }
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        let _ = (home, exe);
        Restart::NotThisBinary("restart the zc agent yourself".into())
    }
}

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

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn picks_the_mode() {
        assert_eq!(mode(&args(&["--check", "--json"])), Some(Mode::Check));
        assert_eq!(mode(&args(&["--from-crates"])), Some(Mode::FromCrates));
        assert_eq!(
            mode(&args(&["--check", "--from-crates"])),
            Some(Mode::FromCrates)
        );
        assert_eq!(mode(&args(&[])), None);
        assert_eq!(mode(&args(&["--from-source"])), None);
    }

    #[test]
    fn finds_the_binary_in_a_plist_or_a_unit() {
        let exe = Path::new("/Users/u/.local/bin/zc");
        let plist = "<key>ProgramArguments</key>\n  <array>\n    <string>/Users/u/.local/bin/zc</string>\n    <string>agent</string>";
        assert!(service_runs(plist, exe));
        assert!(!service_runs(plist, Path::new("/usr/local/bin/zc")));
        let unit = "[Service]\nExecStart=\"/Users/u/.local/bin/zc\" agent run\n";
        assert!(service_runs(unit, exe));
        let unit = "[Service]\nExecStart=/Users/u/.local/bin/zc agent run\n";
        assert!(service_runs(unit, exe));
        assert!(!service_runs("ExecStart=/opt/zc agent run", exe));
    }

    #[test]
    fn reads_the_agent_binary_from_a_plist_or_a_unit() {
        let plist = "<dict>\n  <key>Label</key>\n  <string>ai.zakuro.agent</string>\n  <key>ProgramArguments</key>\n  <array>\n    <string>/Users/u/.local/bin/zc</string>\n    <string>agent</string>\n    <string>run</string>\n  </array>";
        assert_eq!(
            service_binary(plist).as_deref(),
            Some("/Users/u/.local/bin/zc")
        );
        let unit = "[Unit]\nDescription=zc agent\n[Service]\nExecStart=\"/home/u/.local/bin/zc\" agent run\n";
        assert_eq!(
            service_binary(unit).as_deref(),
            Some("/home/u/.local/bin/zc")
        );
        assert_eq!(service_binary("nothing here"), None);
    }

    #[test]
    fn target_flags() {
        assert_eq!(
            target(&args(&["--check", "--target", "/x/zc"])).unwrap(),
            Some(PathBuf::from("/x/zc"))
        );
        assert!(target(&args(&["--target"])).is_err());
        assert!(target(&args(&["--target", "--json"])).is_err());
        assert_eq!(target(&args(&["--check"])).unwrap(), None);
    }

    #[test]
    fn the_check_text_says_what_to_do() {
        let mut c = Check {
            current: "0.0.44".into(),
            latest: Some("0.0.45".into()),
            newer: true,
            source: "crates.io",
            crate_name: "zc2",
            exe: "/x/zc".into(),
            writable: true,
            cargo: Some("/x/cargo".into()),
            error: None,
        };
        assert!(format_check(&c).contains("zc update --from-crates\n"));
        c.cargo = None;
        assert!(format_check(&c).contains("needs cargo"));
        c.newer = false;
        c.latest = Some("0.0.44".into());
        assert!(format_check(&c).contains("is up to date"));
        c.error = Some("could not read crates.io: HTTP 503".into());
        assert!(format_check(&c).contains("could not read crates.io"));
    }

    #[test]
    fn check_serializes_the_crate_name_as_crate() {
        let c = Check {
            current: "0.0.44".into(),
            latest: None,
            newer: false,
            source: "crates.io",
            crate_name: "zc2",
            exe: String::new(),
            writable: false,
            cargo: None,
            error: Some("x".into()),
        };
        let v = serde_json::to_value(&c).unwrap();
        assert_eq!(v["crate"], "zc2");
        assert_eq!(v["latest"], serde_json::Value::Null);
    }
}