zc2 0.0.47

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
//! The machine check shared by `zc doctor`, `zc setup` and the desktop app's
//! first-run "Check this machine" screen (zc#509, plan snapshot S2).
//!
//! Every check is read-only and bounded in time: nothing here installs,
//! starts or signs in. `zc doctor --json` prints [`Report`], which the app
//! reads through its bundled zc.

use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Ok,
    /// Works, but something is worth knowing (shown, never blocks setup).
    Warn,
    /// Sharing cannot work until this is fixed.
    Fail,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Check {
    /// Stable id: `profile`, `signed_in`, `hub`, `cpu`, `memory`, `disk`,
    /// `runtime`, `node_key`, `action_key`.
    pub id: String,
    pub label: String,
    pub status: Status,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Report {
    /// `lab` | `staging` | `prod`.
    pub env: String,
    pub api_url: String,
    pub os: String,
    pub arch: String,
    pub checks: Vec<Check>,
}

impl Report {
    /// No check failed.
    pub fn ok(&self) -> bool {
        self.checks.iter().all(|c| c.status != Status::Fail)
    }
}

fn check(id: &str, label: impl Into<String>, status: Status, detail: impl Into<String>) -> Check {
    Check {
        id: id.into(),
        label: label.into(),
        status,
        detail: detail.into(),
    }
}

/// Total memory in bytes.
pub fn total_memory() -> Option<u64> {
    #[cfg(target_os = "linux")]
    {
        let text = std::fs::read_to_string("/proc/meminfo").ok()?;
        let kb: u64 = text
            .lines()
            .find(|l| l.starts_with("MemTotal:"))?
            .split_whitespace()
            .nth(1)?
            .parse()
            .ok()?;
        Some(kb * 1024)
    }
    #[cfg(target_os = "macos")]
    {
        let out = std::process::Command::new("sysctl")
            .args(["-n", "hw.memsize"])
            .output()
            .ok()?;
        String::from_utf8_lossy(&out.stdout).trim().parse().ok()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        None
    }
}

/// Free bytes on the file system holding `path`.
pub fn free_disk(path: &Path) -> Option<u64> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
        let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
        // SAFETY: `c` is a valid NUL-terminated path and `st` a writable statvfs.
        if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
            return None;
        }
        #[allow(clippy::unnecessary_cast)]
        Some(st.f_bavail as u64 * st.f_frsize as u64)
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

const GB: f64 = 1024.0 * 1024.0 * 1024.0;

/// What a machine needs to lend anything useful: below these, a warning.
const MIN_FREE_DISK_GB: f64 = 20.0;
const MIN_MEMORY_GB: f64 = 4.0;

pub fn cpu_check(cpus: usize) -> Check {
    let lend = (cpus / 2).max(1);
    check(
        "cpu",
        format!("{cpus} CPUs"),
        if cpus >= 2 { Status::Ok } else { Status::Warn },
        format!("lends up to {lend} by default (half, at least one)"),
    )
}

pub fn memory_check(bytes: Option<u64>) -> Check {
    match bytes {
        Some(b) => {
            let gb = b as f64 / GB;
            check(
                "memory",
                format!("{gb:.0} GB memory"),
                if gb >= MIN_MEMORY_GB {
                    Status::Ok
                } else {
                    Status::Warn
                },
                if gb >= MIN_MEMORY_GB {
                    "enough for public jobs".to_string()
                } else {
                    format!("under {MIN_MEMORY_GB:.0} GB: few jobs will fit")
                },
            )
        }
        None => check("memory", "Memory", Status::Warn, "could not read the total"),
    }
}

pub fn disk_check(bytes: Option<u64>) -> Check {
    match bytes {
        Some(b) => {
            let gb = b as f64 / GB;
            check(
                "disk",
                format!("{gb:.0} GB free disk"),
                if gb >= MIN_FREE_DISK_GB {
                    Status::Ok
                } else {
                    Status::Warn
                },
                if gb >= MIN_FREE_DISK_GB {
                    "room for job images".to_string()
                } else {
                    format!("under {MIN_FREE_DISK_GB:.0} GB: job images may not fit")
                },
            )
        }
        None => check(
            "disk",
            "Free disk",
            Status::Warn,
            "could not read free space",
        ),
    }
}

/// `GET <hub>/api/health`, timed.
fn hub_check(api_url: &str) -> Check {
    let url = format!("{}/api/health", api_url.trim_end_matches('/'));
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .http_status_as_error(false)
            .timeout_global(Some(Duration::from_secs(5)))
            .build(),
    );
    let t = Instant::now();
    match agent.get(&url).call() {
        Ok(r) if r.status().is_success() => check(
            "hub",
            "Hub reachable",
            Status::Ok,
            format!("{} · {} ms", host_of(api_url), t.elapsed().as_millis()),
        ),
        Ok(r) => check(
            "hub",
            "Hub reachable",
            Status::Fail,
            format!("{} answered HTTP {}", host_of(api_url), r.status().as_u16()),
        ),
        Err(e) => check(
            "hub",
            "Hub reachable",
            Status::Fail,
            format!("{}: {e}", host_of(api_url)),
        ),
    }
}

fn host_of(url: &str) -> &str {
    let s = url.split("://").nth(1).unwrap_or(url);
    s.split('/').next().unwrap_or(s)
}

/// Signed in = an API key in `~/.zakuro/credentials` (or `ZAKURO_API_KEY`).
pub fn signed_in_check(file_key: bool, env_key: bool) -> Check {
    if file_key || env_key {
        check(
            "signed_in",
            "Signed in",
            Status::Ok,
            if file_key {
                "key in ~/.zakuro/credentials"
            } else {
                "ZAKURO_API_KEY"
            },
        )
    } else {
        check("signed_in", "Not signed in", Status::Fail, "run zc login")
    }
}

/// Run every check. `with_network` adds the hub round trip.
pub fn machine_report(with_network: bool) -> Report {
    let resolved = crate::profile::resolve();
    let api_url = resolved.api_url.0.clone();
    // The hub this machine talks to names the environment: a LaunchAgent or
    // an app started from Finder has no ZAKURO_ENV, so the profile alone says
    // prod while `zc login --staging` pointed the credentials at staging.
    let env = crate::deeplink::env_for_api_url(Some(&api_url));
    let state_dir = crate::credentials::dir();
    let file_key = crate::credentials::path()
        .and_then(|p| std::fs::read_to_string(p).ok())
        .map(|t| crate::credentials::parse(&t))
        .and_then(|m| m.get("api_key").cloned())
        .is_some_and(|k| !k.trim().is_empty());
    let env_key = std::env::var("ZAKURO_API_KEY").is_ok_and(|k| !k.trim().is_empty());

    let mut checks = vec![check(
        "profile",
        format!("Profile {}", env.name()),
        if resolved.unknown_env.is_some() {
            Status::Warn
        } else {
            Status::Ok
        },
        match &resolved.unknown_env {
            Some(v) => format!("ZAKURO_ENV={v:?} is not lab|staging|prod; using prod"),
            None => host_of(&api_url).to_string(),
        },
    )];
    checks.push(signed_in_check(file_key, env_key));
    if with_network {
        checks.push(hub_check(&api_url));
    }
    let cpus = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1);
    checks.push(cpu_check(cpus));
    checks.push(memory_check(total_memory()));
    let home = state_dir
        .clone()
        .or_else(|| std::env::var_os("HOME").map(Into::into))
        .unwrap_or_else(|| "/".into());
    let probe_dir = if home.exists() { home } else { "/".into() };
    checks.push(disk_check(free_disk(&probe_dir)));

    let probe = crate::broker::deploy::runtime_probe();
    checks.push(check(
        "runtime",
        if probe.available {
            format!("Container runtime ({})", probe.runtime.unwrap_or("docker"))
        } else {
            "No container runtime".to_string()
        },
        // Workers run on the host without one; only containerised jobs need it.
        if probe.available {
            Status::Ok
        } else {
            Status::Warn
        },
        if probe.available {
            "containerised jobs can run".to_string()
        } else {
            format!("host workers only: {}", probe.detail)
        },
    ));

    let node_key = crate::broker::node_identity::NodeKey::load_in(state_dir);
    checks.push(match node_key {
        Some(k) => check(
            "node_key",
            "Node identity",
            Status::Ok,
            format!("zc://node-{}", k.fingerprint()),
        ),
        None => check(
            "node_key",
            "No node identity yet",
            Status::Warn,
            "created at sign-in or when sharing starts",
        ),
    });

    let link_env = env;
    checks.push(match crate::deeplink::keys_for(link_env) {
        Ok(k) if !k.is_empty() => check(
            "action_key",
            "Open in Zakuro links",
            Status::Ok,
            format!("hub key {}", k[0].kid),
        ),
        Ok(_) => check(
            "action_key",
            "Open in Zakuro links off",
            Status::Warn,
            format!(
                "no hub action key for {}; signed zakuro:// links are refused (set {})",
                link_env.name(),
                crate::deeplink::ENV_ACTION_PUBKEYS
            ),
        ),
        Err(e) => check("action_key", "Open in Zakuro links", Status::Fail, e),
    });

    Report {
        env: env.name().to_string(),
        api_url,
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
        checks,
    }
}

/// One line per check, as `zc doctor` and `zc setup` print them.
pub fn format_check(c: &Check) -> String {
    let mark = match c.status {
        Status::Ok => "✓",
        Status::Warn => "!",
        Status::Fail => "✗",
    };
    format!("  {mark} {:<30} {}", c.label, c.detail)
}

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

    #[test]
    fn thresholds_warn_but_never_fail_on_hardware() {
        assert_eq!(cpu_check(12).status, Status::Ok);
        assert!(cpu_check(12).detail.contains("up to 6"));
        assert_eq!(cpu_check(1).status, Status::Warn);
        assert_eq!(
            memory_check(Some(36 * 1024 * 1024 * 1024)).label,
            "36 GB memory"
        );
        assert_eq!(
            memory_check(Some(2 * 1024 * 1024 * 1024)).status,
            Status::Warn
        );
        assert_eq!(
            disk_check(Some(10 * 1024 * 1024 * 1024)).status,
            Status::Warn
        );
        assert_eq!(disk_check(None).status, Status::Warn);
        assert_eq!(signed_in_check(false, false).status, Status::Fail);
        assert_eq!(signed_in_check(false, true).detail, "ZAKURO_API_KEY");
    }

    #[test]
    fn report_ok_means_nothing_failed() {
        let r = Report {
            env: "prod".into(),
            api_url: "https://hub.zakuro-ai.com".into(),
            os: "linux".into(),
            arch: "x86_64".into(),
            checks: vec![cpu_check(1), signed_in_check(true, false)],
        };
        assert!(r.ok());
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(v["checks"][0]["status"], "warn");
        assert_eq!(
            host_of("https://hub.zakuro-ai.com/api"),
            "hub.zakuro-ai.com"
        );
    }

    #[test]
    fn the_real_machine_reads_without_network() {
        let r = machine_report(false);
        let ids: Vec<&str> = r.checks.iter().map(|c| c.id.as_str()).collect();
        for id in [
            "profile",
            "signed_in",
            "cpu",
            "memory",
            "disk",
            "runtime",
            "node_key",
            "action_key",
        ] {
            assert!(ids.contains(&id), "{id} in {ids:?}");
        }
        assert!(!ids.contains(&"hub"));
        #[cfg(target_os = "linux")]
        assert!(total_memory().unwrap() > 0);
        #[cfg(unix)]
        assert!(free_disk(Path::new("/")).is_some());
    }
}