zc2 0.0.26

P2P compute broker with credit-based 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
//! `zc agent install | uninstall` on macOS (spec §6.1): a per-user LaunchAgent.
//! Rendering is a pure function tested everywhere; installing and uninstalling
//! take an injected `launchctl` runner so the logic is tested on every
//! platform. Only the adapter that shells out to the real `launchctl`, and
//! `gui_domain()`, are macOS-only.

use std::io;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;

pub const LABEL: &str = "ai.zakuro.agent";

/// A `launchctl` invocation, injected so install/uninstall never shell out in
/// tests.
pub type Launchctl<'a> = &'a dyn Fn(&[&str]) -> io::Result<ExitStatus>;

pub fn plist_path(home: &Path) -> PathBuf {
    home.join("Library")
        .join("LaunchAgents")
        .join(format!("{LABEL}.plist"))
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// What `zc agent run` reads from its process environment
/// (`AgentConfig::from_env`). `ZAKURO_WORKER_DIR` is carried the same way as
/// the rest, but it is not looked up only at startup: `Core::reconcile_once`
/// re-resolves the zakuro worker directory (`crate::up::resolve_zakuro_dir_for`)
/// fresh on every tick, this carried environment value being just the first
/// thing it checks. `zc agent install` writes each one the installing shell
/// set into the plist, so the agent launchd starts uses the same state dir,
/// port, worker dir, worker cap and worker command.
pub const CARRIED_ENV: [&str; 5] = [
    "ZAKURO_HOME",
    "ZAKURO_AGENT_PORT",
    "ZAKURO_WORKER_DIR",
    "ZAKURO_AGENT_MAX_WORKERS",
    "ZAKURO_AGENT_WORKER_CMD",
];

/// The `CARRIED_ENV` values `lookup` returns, in that order, skipping unset
/// and empty ones. `install` passes the real environment; tests pass a closure.
pub fn carried_env(lookup: impl Fn(&str) -> Option<String>) -> Vec<(&'static str, String)> {
    CARRIED_ENV
        .iter()
        .filter_map(|&k| lookup(k).filter(|v| !v.is_empty()).map(|v| (k, v)))
        .collect()
}

/// Spec §6.1: run `<zc> agent run` at login, keep it alive, give it 60 s to
/// stop its children, a PATH on which `uv` resolves, and a log file. `env`
/// (from `carried_env`) follows PATH in `EnvironmentVariables`, XML-escaped.
pub fn render_plist(zc_path: &str, home: &str, env: &[(&str, String)], log_path: &str) -> String {
    let path = format!(
        "/opt/homebrew/bin:/usr/local/bin:{home}/.local/bin:{home}/.cargo/bin:/usr/bin:/bin"
    );
    let mut vars = format!(
        "\t\t<key>PATH</key>\n\t\t<string>{}</string>\n",
        xml_escape(&path)
    );
    for (key, value) in env {
        vars.push_str(&format!(
            "\t\t<key>{}</key>\n\t\t<string>{}</string>\n",
            xml_escape(key),
            xml_escape(value)
        ));
    }
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>{LABEL}</string>
	<key>ProgramArguments</key>
	<array>
		<string>{zc}</string>
		<string>agent</string>
		<string>run</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
	<key>KeepAlive</key>
	<true/>
	<key>ExitTimeOut</key>
	<integer>60</integer>
	<key>EnvironmentVariables</key>
	<dict>
{vars}	</dict>
	<key>StandardOutPath</key>
	<string>{log}</string>
	<key>StandardErrorPath</key>
	<string>{log}</string>
</dict>
</plist>
"#,
        zc = xml_escape(zc_path),
        log = xml_escape(log_path),
    )
}

/// The per-user launchd domain (spec: `gui/<uid>`). This is the only place
/// that reads the real uid; tests pass their own domain string straight to
/// `install`/`uninstall`.
#[cfg(target_os = "macos")]
pub fn gui_domain() -> String {
    format!("gui/{}", unsafe { libc::getuid() })
}

/// The thin adapter that runs the real `launchctl`. `install`/`uninstall`
/// never call this directly; production callers in `cli.rs` pass it in.
#[cfg(target_os = "macos")]
pub fn run_launchctl(args: &[&str]) -> io::Result<ExitStatus> {
    std::process::Command::new("launchctl").args(args).status()
}

/// Rotate the agent token, write the plist, then `launchctl bootout`
/// (ignoring errors) and `launchctl bootstrap <domain> <plist>`.
pub fn install(
    launchctl: Launchctl,
    domain: &str,
    zc_path: &Path,
    home: &Path,
    env: &[(&str, String)],
    agent_dir: &Path,
    port: u16,
) -> Result<(), String> {
    crate::agent::files::load_or_init_agent_file(agent_dir, port, true)
        .map_err(|e| e.to_string())?;
    let plist = plist_path(home);
    std::fs::create_dir_all(plist.parent().expect("LaunchAgents has a parent"))
        .map_err(|e| e.to_string())?;
    let log = agent_dir.join(crate::agent::files::LOG_FILE);
    std::fs::write(
        &plist,
        render_plist(
            &zc_path.to_string_lossy(),
            &home.to_string_lossy(),
            env,
            &log.to_string_lossy(),
        ),
    )
    .map_err(|e| e.to_string())?;
    let _ = launchctl(&["bootout", &format!("{domain}/{LABEL}")]);
    let st =
        launchctl(&["bootstrap", domain, &plist.to_string_lossy()]).map_err(|e| e.to_string())?;
    if st.success() {
        Ok(())
    } else {
        Err(format!("launchctl bootstrap failed ({st})"))
    }
}

/// `launchctl bootout`, then remove the plist. `~/.zakuro/agent/` is kept.
pub fn uninstall(launchctl: Launchctl, domain: &str, home: &Path) -> Result<(), String> {
    let _ = launchctl(&["bootout", &format!("{domain}/{LABEL}")]);
    let p = plist_path(home);
    if p.exists() {
        std::fs::remove_file(&p).map_err(|e| e.to_string())?;
    }
    Ok(())
}

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

    #[test]
    fn plist_runs_zc_agent_run_under_launchd_with_the_spec_settings() {
        let p = render_plist(
            "/usr/local/bin/zc",
            "/Users/j",
            &[],
            "/Users/j/.zakuro/agent/agent.log",
        );
        assert!(p.contains("<string>ai.zakuro.agent</string>"));
        assert!(p.contains("<string>/usr/local/bin/zc</string>\n\t\t<string>agent</string>\n\t\t<string>run</string>"));
        assert!(p.contains("<key>RunAtLoad</key>\n\t<true/>"));
        assert!(p.contains("<key>KeepAlive</key>\n\t<true/>"));
        assert!(p.contains("<key>ExitTimeOut</key>\n\t<integer>60</integer>"));
        assert!(p.contains("<string>/opt/homebrew/bin:/usr/local/bin:/Users/j/.local/bin:/Users/j/.cargo/bin:/usr/bin:/bin</string>"));
        for key in CARRIED_ENV {
            assert!(
                !p.contains(key),
                "{key} is only written when the installing shell set it"
            );
        }
        assert_eq!(
            p.matches("<string>/Users/j/.zakuro/agent/agent.log</string>")
                .count(),
            2,
            "stdout and stderr"
        );
    }

    #[test]
    fn plist_carries_zakuro_home_and_escapes_xml() {
        let p = render_plist(
            "/opt/a&b/zc",
            "/Users/j",
            &[("ZAKURO_HOME", "/Volumes/z<1>".to_string())],
            "/tmp/agent.log",
        );
        assert!(p.contains("<string>/opt/a&amp;b/zc</string>"));
        assert!(p.contains("<key>ZAKURO_HOME</key>\n\t\t<string>/Volumes/z&lt;1&gt;</string>"));
    }

    /// The plist with one carried variable set.
    fn plist_with(key: &'static str, value: &str) -> String {
        render_plist(
            "/usr/local/bin/zc",
            "/Users/j",
            &[(key, value.to_string())],
            "/tmp/agent.log",
        )
    }

    fn entry(key: &str, escaped_value: &str) -> String {
        format!("\t\t<key>{key}</key>\n\t\t<string>{escaped_value}</string>\n")
    }

    /// Otherwise the LaunchAgent binds the default 4720 while `install`
    /// wrote and printed the shell's port.
    #[test]
    fn plist_carries_the_agent_port() {
        assert!(
            plist_with("ZAKURO_AGENT_PORT", "5000").contains(&entry("ZAKURO_AGENT_PORT", "5000"))
        );
    }

    /// Otherwise the agent launchd starts reports `zakuro_dir_missing` while
    /// `zc up` works from the installing shell.
    #[test]
    fn plist_carries_the_worker_dir_escaped() {
        assert!(plist_with("ZAKURO_WORKER_DIR", "/Users/j/R&D/zak-zakuro")
            .contains(&entry("ZAKURO_WORKER_DIR", "/Users/j/R&amp;D/zak-zakuro")));
    }

    #[test]
    fn plist_carries_the_worker_cap() {
        assert!(plist_with("ZAKURO_AGENT_MAX_WORKERS", "3")
            .contains(&entry("ZAKURO_AGENT_MAX_WORKERS", "3")));
    }

    #[test]
    fn plist_carries_the_worker_command_escaped() {
        assert!(plist_with(
            "ZAKURO_AGENT_WORKER_CMD",
            r#"run-worker --tag "<a&b>" {port}"#
        )
        .contains(&entry(
            "ZAKURO_AGENT_WORKER_CMD",
            "run-worker --tag &quot;&lt;a&amp;b&gt;&quot; {port}"
        )));
    }

    #[test]
    fn carried_env_takes_the_agents_settings_that_are_set_in_order() {
        let env = carried_env(|k| match k {
            "ZAKURO_AGENT_WORKER_CMD" => Some("run-worker {port}".into()),
            "ZAKURO_AGENT_PORT" => Some("5000".into()),
            "ZAKURO_WORKER_DIR" => Some(String::new()), // set but empty: not carried
            "PATH" | "HOME" | "ZAKURO_P2P" => Some("x".into()), // never asked for
            _ => None,
        });
        assert_eq!(
            env,
            vec![
                ("ZAKURO_AGENT_PORT", "5000".to_string()),
                ("ZAKURO_AGENT_WORKER_CMD", "run-worker {port}".to_string()),
            ]
        );
    }

    #[test]
    fn plist_lives_in_the_users_launch_agents() {
        assert_eq!(
            plist_path(std::path::Path::new("/Users/j")),
            std::path::PathBuf::from("/Users/j/Library/LaunchAgents/ai.zakuro.agent.plist")
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn plutil_accepts_the_plist() {
        let dir = crate::agent::files::tests::tmp("plist");
        std::fs::create_dir_all(&dir).unwrap();
        let f = dir.join("a.plist");
        std::fs::write(
            &f,
            render_plist(
                "/usr/local/bin/zc",
                "/Users/j",
                &carried_env(|k| Some(format!("{k}-<&>\"value"))),
                "/tmp/a.log",
            ),
        )
        .unwrap();
        let out = std::process::Command::new("plutil")
            .arg("-lint")
            .arg(&f)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stdout)
        );
    }

    /// A fake `launchctl` that records every call it receives and reports
    /// exit status `ok` (or a failing status when told to).
    struct FakeLaunchctl {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
        fail_bootstrap: bool,
    }

    fn exit_status(success: bool) -> std::process::ExitStatus {
        // There is no public constructor for a specific `ExitStatus`, so this
        // shells out to `true`/`false` to get a real one with the wanted code.
        std::process::Command::new(if success { "true" } else { "false" })
            .status()
            .unwrap()
    }

    impl FakeLaunchctl {
        fn new(fail_bootstrap: bool) -> Self {
            Self {
                calls: std::sync::Mutex::new(vec![]),
                fail_bootstrap,
            }
        }

        fn call(&self, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
            self.calls
                .lock()
                .unwrap()
                .push(args.iter().map(|s| s.to_string()).collect());
            let fail = self.fail_bootstrap && args.first() == Some(&"bootstrap");
            Ok(exit_status(!fail))
        }

        fn calls(&self) -> Vec<Vec<String>> {
            self.calls.lock().unwrap().clone()
        }
    }

    #[test]
    fn install_writes_the_plist_rotates_the_token_and_boots_out_before_bootstrap() {
        let home = crate::agent::files::tests::tmp("launchd-install-home");
        let agent_dir = crate::agent::files::tests::tmp("launchd-install-agent");
        std::fs::create_dir_all(&home).unwrap();
        let existing =
            crate::agent::files::load_or_init_agent_file(&agent_dir, 4720, false).unwrap();

        let fake = FakeLaunchctl::new(false);
        let zc_path = std::path::Path::new("/usr/local/bin/zc");
        install(
            &|a| fake.call(a),
            "gui/501",
            zc_path,
            &home,
            &[],
            &agent_dir,
            4720,
        )
        .expect("install succeeds");

        let plist = plist_path(&home);
        assert!(plist.exists(), "plist written");
        let contents = std::fs::read_to_string(&plist).unwrap();
        assert!(contents.contains("/usr/local/bin/zc"));

        let rotated = crate::agent::files::load_json::<crate::agent::files::AgentFile>(
            &agent_dir.join(crate::agent::files::AGENT_FILE),
        )
        .unwrap();
        assert_ne!(rotated.token, existing.token, "install rotates the token");

        let calls = fake.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0], vec!["bootout", "gui/501/ai.zakuro.agent"]);
        assert_eq!(
            calls[1],
            vec!["bootstrap", "gui/501", &plist.to_string_lossy()]
        );
    }

    #[test]
    fn a_bootout_failure_is_ignored_but_a_bootstrap_failure_is_reported() {
        let home = crate::agent::files::tests::tmp("launchd-install-fail-home");
        let agent_dir = crate::agent::files::tests::tmp("launchd-install-fail-agent");
        std::fs::create_dir_all(&home).unwrap();

        let fake = FakeLaunchctl::new(true);
        let zc_path = std::path::Path::new("/usr/local/bin/zc");
        let err = install(
            &|a| fake.call(a),
            "gui/501",
            zc_path,
            &home,
            &[],
            &agent_dir,
            4720,
        )
        .unwrap_err();
        assert!(err.contains("bootstrap"), "{err}");
    }

    #[test]
    fn uninstall_boots_out_and_removes_the_plist_but_keeps_the_agent_dir() {
        let home = crate::agent::files::tests::tmp("launchd-uninstall-home");
        let agent_dir = crate::agent::files::tests::tmp("launchd-uninstall-agent");
        std::fs::create_dir_all(&home).unwrap();
        crate::agent::files::load_or_init_agent_file(&agent_dir, 4720, false).unwrap();
        let fake = FakeLaunchctl::new(false);
        let zc_path = std::path::Path::new("/usr/local/bin/zc");
        install(
            &|a| fake.call(a),
            "gui/501",
            zc_path,
            &home,
            &[],
            &agent_dir,
            4720,
        )
        .unwrap();
        assert!(plist_path(&home).exists());

        uninstall(&|a| fake.call(a), "gui/501", &home).expect("uninstall succeeds");

        assert!(!plist_path(&home).exists(), "plist removed");
        assert!(
            agent_dir.join(crate::agent::files::AGENT_FILE).exists(),
            "agent dir kept"
        );
        let calls = fake.calls();
        assert_eq!(
            calls.last().unwrap(),
            &vec!["bootout", "gui/501/ai.zakuro.agent"]
        );
    }
}