zc2 0.0.50

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
//! Spaces v1, producer side: this broker claims batches from the hub, runs
//! each Space's container (pulled by digest), serves the in-container worker
//! over a Unix socket, and sends signed receipts.
//!
//! Opt-in: `zc spaces enable [--min-price-per-hour N]` PUTs the hub settings
//! and writes `<state_dir>/spaces/settings.json`, which the scheduler polls.

pub mod client;
pub mod preempt;
pub mod receipt;
pub mod runner;
pub mod schedule;
#[cfg(unix)]
pub mod socket;
#[cfg(unix)]
pub mod worker;

/// Spaces talk to their container over a Unix socket: elsewhere a Space
/// cannot be hosted, and says so instead of failing to build.
#[cfg(not(unix))]
pub mod socket {
    use super::runner::Session;
    use std::path::Path;
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;

    pub fn serve(_: &Path, _: Arc<Session>, _: Arc<AtomicBool>) -> Result<(), String> {
        Err("hosting a Space needs Unix sockets, which this platform does not have".into())
    }
}

/// `zc space worker` runs inside a (Linux) Space container only.
#[cfg(not(unix))]
pub mod worker {
    pub fn run_cli(_: &[String]) -> i32 {
        eprintln!("zc space worker runs inside a Linux Space container; it is not supported on this platform");
        2
    }
}

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::{Arc, Mutex, OnceLock};

use serde::{Deserialize, Serialize};

/// Raised by the idle benchmark while it measures; the Spaces scheduler sends
/// no claims meanwhile.
pub fn bench_running() -> Arc<AtomicBool> {
    static F: OnceLock<Arc<AtomicBool>> = OnceLock::new();
    F.get_or_init(Arc::default).clone()
}

/// Number of Space containers currently running; the idle benchmark treats
/// any as busy so it never measures a saturated node.
pub fn space_containers() -> Arc<AtomicUsize> {
    static C: OnceLock<Arc<AtomicUsize>> = OnceLock::new();
    C.get_or_init(Arc::default).clone()
}

/// Local, scheduler-visible copy of the provider settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct Settings {
    pub enabled: bool,
    #[serde(default)]
    pub min_price_per_hour: Option<f64>,
}

fn settings_path(dir: &Path) -> PathBuf {
    dir.join("spaces").join("settings.json")
}

fn status_path(dir: &Path) -> PathBuf {
    dir.join("spaces").join("status.json")
}

pub fn read_settings(dir: &Path) -> Settings {
    std::fs::read_to_string(settings_path(dir))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_default()
}

pub fn write_settings(dir: &Path, s: &Settings) -> Result<(), String> {
    let p = settings_path(dir);
    if let Some(d) = p.parent() {
        std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
    }
    std::fs::write(&p, serde_json::to_string_pretty(s).unwrap()).map_err(|e| e.to_string())
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ActiveSpace {
    pub space_id: String,
    pub queued: usize,
    pub running: usize,
}

/// What `zc spaces status` shows; written by the broker process.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct StatusFile {
    #[serde(default)]
    pub day: String,
    #[serde(default)]
    pub completed_today: u64,
    #[serde(default)]
    pub earned_today: f64,
    #[serde(default)]
    pub active: Vec<ActiveSpace>,
}

fn today() -> String {
    chrono::Utc::now().format("%Y-%m-%d").to_string()
}

pub struct Stats {
    path: PathBuf,
    inner: Mutex<StatusFile>,
}

impl Stats {
    pub fn new(dir: &Path) -> Stats {
        Stats {
            path: status_path(dir),
            inner: Mutex::new(read_status(dir)),
        }
    }

    fn save(&self, s: &StatusFile) {
        if let Some(d) = self.path.parent() {
            let _ = std::fs::create_dir_all(d);
        }
        let _ = std::fs::write(&self.path, serde_json::to_string_pretty(s).unwrap());
    }

    fn roll(s: &mut StatusFile) {
        let t = today();
        if s.day != t {
            s.day = t;
            s.completed_today = 0;
            s.earned_today = 0.0;
        }
    }

    pub fn record_paid(&self, paid: f64) {
        let mut s = self.inner.lock().unwrap();
        Self::roll(&mut s);
        s.completed_today += 1;
        s.earned_today += paid;
        self.save(&s);
    }

    pub fn set_active(&self, active: Vec<ActiveSpace>) {
        let mut s = self.inner.lock().unwrap();
        Self::roll(&mut s);
        s.active = active;
        self.save(&s);
    }
}

pub fn read_status(dir: &Path) -> StatusFile {
    let mut s: StatusFile = std::fs::read_to_string(status_path(dir))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_default();
    if s.day != today() {
        s.completed_today = 0;
        s.earned_today = 0.0;
    }
    s
}

/// `zc spaces enable|disable|status`. Returns the exit code.
pub fn run_cli(args: &[String]) -> i32 {
    let Some(dir) = crate::credentials::dir() else {
        eprintln!("Error: no state directory (set HOME or ZAKURO_HOME)");
        return 1;
    };
    let hub = || -> Result<client::Hub, String> {
        let key = std::env::var("ZAKURO_API_KEY")
            .ok()
            .filter(|k| !k.trim().is_empty())
            .ok_or("not signed in (run `zc login` or set ZAKURO_API_KEY)")?;
        let node_key = crate::broker::node_identity::NodeKey::load_or_create();
        Ok(client::Hub::new(
            &crate::credentials::default_api_url(),
            &key,
            &node_key.public_b64(),
        ))
    };
    match args.first().map(String::as_str).unwrap_or("status") {
        "enable" => {
            let price = match parse_price(&args[1..]) {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("Error: {e}");
                    return 2;
                }
            };
            match hub().and_then(|h| enable(&h, &dir, price)) {
                Ok(()) => {
                    println!("Spaces enabled. Restart the broker if it is not running.");
                    // Deprecated alias: the switch is `workloads.spaces` now.
                    if let Err(e) = crate::policy::migrate::alias_spaces(
                        &dir,
                        true,
                        read_settings(&dir).min_price_per_hour,
                    ) {
                        eprintln!("Error: policy.toml not updated: {e}");
                    }
                    0
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    1
                }
            }
        }
        "disable" => match hub().and_then(|h| disable(&h, &dir)) {
            Ok(()) => {
                println!("Spaces disabled. Running batches finish; no new work is claimed.");
                if let Err(e) = crate::policy::migrate::alias_spaces(&dir, false, None) {
                    eprintln!("Error: policy.toml not updated: {e}");
                }
                0
            }
            Err(e) => {
                eprintln!("Error: {e}");
                1
            }
        },
        "status" => {
            print_status(&dir);
            0
        }
        other => {
            eprintln!(
                "usage: zc spaces [enable [--min-price-per-hour N]|disable|status] (got '{other}')"
            );
            2
        }
    }
}

pub fn parse_price(args: &[String]) -> Result<Option<f64>, String> {
    let mut it = args.iter();
    let mut price = None;
    while let Some(a) = it.next() {
        if a == "--min-price-per-hour" {
            let v = it.next().ok_or("--min-price-per-hour needs a value")?;
            let p: f64 = v.parse().map_err(|_| format!("bad price '{v}'"))?;
            if p.is_nan() || p < 0.0 {
                return Err("price must be >= 0".into());
            }
            price = Some(p);
        } else {
            return Err(format!("unknown argument '{a}'"));
        }
    }
    Ok(price)
}

/// PUT the settings, then record them locally for the scheduler.
pub fn enable(hub: &client::Hub, dir: &Path, min_price: Option<f64>) -> Result<(), String> {
    // An omitted flag keeps the stored price: the hub replaces the column
    // with whatever the PUT carries, and `None` would clear it.
    let min_price = min_price.or(read_settings(dir).min_price_per_hour);
    hub.put_settings(true, min_price)?;
    write_settings(
        dir,
        &Settings {
            enabled: true,
            min_price_per_hour: min_price,
        },
    )
}

pub fn disable(hub: &client::Hub, dir: &Path) -> Result<(), String> {
    // Send the stored price so disabling never clears the hub's minimum.
    hub.put_settings(false, read_settings(dir).min_price_per_hour)?;
    let mut s = read_settings(dir);
    s.enabled = false;
    write_settings(dir, &s)
}

fn print_status(dir: &Path) {
    let s = read_settings(dir);
    let st = read_status(dir);
    println!("Spaces: {}", if s.enabled { "enabled" } else { "disabled" });
    if let Some(p) = s.min_price_per_hour {
        println!("Min price per hour: {p}");
    }
    if st.active.is_empty() {
        println!("Active Spaces: none");
    } else {
        println!("Active Spaces:");
        for a in &st.active {
            println!(
                "  {}  queued={} running={}",
                a.space_id, a.queued, a.running
            );
        }
    }
    println!(
        "Today: {} batches completed, ¥{:.4} earned",
        st.completed_today, st.earned_today
    );
}

#[cfg(test)]
pub(crate) mod testutil {
    //! A stub hub on 127.0.0.1 that records requests and answers by path.
    use std::sync::{Arc, Mutex};

    pub struct StubHub {
        pub url: String,
        pub requests: Arc<Mutex<Vec<(String, String, String)>>>, // method, path, body
    }

    /// `respond(method, path, body) -> (status, json body)`.
    pub fn stub_hub<F>(respond: F) -> StubHub
    where
        F: Fn(&str, &str, &str) -> (u16, String) + Send + 'static,
    {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let url = format!("http://{}", server.server_addr().to_ip().unwrap());
        let requests = Arc::new(Mutex::new(Vec::new()));
        let reqs = requests.clone();
        std::thread::spawn(move || {
            for mut rq in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(rq.as_reader(), &mut body);
                let method = rq.method().to_string();
                let path = rq.url().to_string();
                reqs.lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), body.clone()));
                let (code, out) = respond(&method, &path, &body);
                let resp = tiny_http::Response::from_string(out)
                    .with_status_code(code)
                    .with_header(
                        tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                    );
                let _ = rq.respond(resp);
            }
        });
        StubHub { url, requests }
    }

    impl StubHub {
        /// Assert every recorded request whose path contains `needle` (and at
        /// least one exists) carries `"node_pubkey": pk` in its JSON body.
        pub fn assert_pubkey(&self, needle: &str, pk: &str) {
            let reqs = self.requests.lock().unwrap();
            let hits: Vec<_> = reqs.iter().filter(|(_, p, _)| p.contains(needle)).collect();
            assert!(!hits.is_empty(), "no request matching {needle}");
            for (_, p, b) in hits {
                let v: serde_json::Value = serde_json::from_str(b).unwrap();
                assert_eq!(v["node_pubkey"], pk, "node_pubkey missing on {p}");
            }
        }

        pub fn count(&self, needle: &str) -> usize {
            self.requests
                .lock()
                .unwrap()
                .iter()
                .filter(|(_, p, _)| p.contains(needle))
                .count()
        }
    }
}

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

    #[test]
    fn spaces_enable_puts_settings() {
        let hub = stub_hub(|_, _, _| (200, "{}".to_string()));
        let dir = std::env::temp_dir().join(format!("zk-spaces-en-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let h = client::Hub::new(&hub.url, "zk_test", "PK_TEST");
        enable(&h, &dir, Some(1.5)).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let (m, p, b) = &reqs[0];
            assert_eq!(m, "PUT");
            assert_eq!(p, "/api/broker/spaces/settings");
            let v: serde_json::Value = serde_json::from_str(b).unwrap();
            assert_eq!(v["enabled"], true);
            assert_eq!(v["node_pubkey"], "PK_TEST");
            assert_eq!(v["min_price_per_hour"], 1.5);
        }
        assert!(read_settings(&dir).enabled);
        disable(&h, &dir).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let v: serde_json::Value = serde_json::from_str(&reqs[1].2).unwrap();
            assert_eq!(v["enabled"], false);
            assert_eq!(v["min_price_per_hour"], 1.5, "disable keeps the price");
        }
        enable(&h, &dir, None).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let v: serde_json::Value = serde_json::from_str(&reqs[2].2).unwrap();
            assert_eq!(v["min_price_per_hour"], 1.5, "re-enable keeps the price");
        }
        disable(&h, &dir).unwrap();
        assert!(!read_settings(&dir).enabled);
        assert_eq!(read_settings(&dir).min_price_per_hour, Some(1.5));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_price_flag() {
        let a = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(parse_price(&a(&[])).unwrap(), None);
        assert_eq!(
            parse_price(&a(&["--min-price-per-hour", "2"])).unwrap(),
            Some(2.0)
        );
        assert!(parse_price(&a(&["--min-price-per-hour"])).is_err());
        assert!(parse_price(&a(&["--x"])).is_err());
    }
}