zc2 0.0.42

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
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
//! Where the session's data comes from, off the UI thread: the mesh from
//! the same cached listing `zc ls` uses, everything else from the running
//! `zc agent`. Results come back to the event loop as [`Event`]s.

use super::app::{AgentState, Effect, Event, Write};
use super::model::MeshSnapshot;
use crate::agent::client::AgentClient;
use crate::agent::summary::Summary;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{RecvTimeoutError, Sender};
use std::time::Duration;

pub const MESH_EVERY: Duration = Duration::from_secs(15);
pub const AGENT_EVERY: Duration = Duration::from_secs(5);
pub const AGENT_TIMEOUT: Duration = Duration::from_secs(2);
pub const WRITE_TIMEOUT: Duration = Duration::from_secs(5);

/// `~/.zakuro/agent`, where a running agent leaves `agent.json`.
pub fn agent_dir() -> Option<PathBuf> {
    crate::credentials::dir().map(|d| d.join("agent"))
}

/// The mesh now: the hub's directory probed on this (poller) thread and
/// saved for `zc ls`, falling back to the last saved listing, plus this
/// machine's broker's workers. Unlike `crate::mesh_listing`, it spawns no
/// background refresh — the session polls every 15 s and would leave a
/// finished child behind each time.
pub fn mesh_once() -> MeshSnapshot {
    let (brokers, listing) = live_listing(
        crate::mesh_listing_from_directory,
        crate::listing_cache::save,
        crate::listing_cache::load_any,
    );
    let (workers, err) = local_workers();
    MeshSnapshot::from_listing(&brokers, &listing, &workers, err)
}

/// The broker listing from `probe`, saved; else `cached`; else a
/// local-only view that says the hub could not be reached.
pub fn live_listing(
    probe: impl FnOnce() -> Option<(Vec<crate::ListedBroker>, crate::Listing)>,
    save: impl FnOnce(&[crate::ListedBroker], &crate::Listing),
    cached: impl FnOnce() -> Option<(Vec<crate::ListedBroker>, crate::Listing)>,
) -> (Vec<crate::ListedBroker>, crate::Listing) {
    if let Some((brokers, listing)) = probe() {
        save(&brokers, &listing);
        return (brokers, listing);
    }
    cached().unwrap_or_else(|| {
        (
            Vec::new(),
            crate::Listing::LocalOnly("the hub directory is unavailable".into()),
        )
    })
}

/// The workers this machine's broker knows, or why not. Only a broker
/// that is already running is read: `ZAKURO_BROKER` when set, else the
/// first loopback broker on 9000-9010. Unlike `resolve_default_broker`,
/// this never starts one.
fn local_workers() -> (Vec<serde_json::Value>, Option<String>) {
    local_workers_from(
        || match std::env::var("ZAKURO_BROKER") {
            Ok(b) if !b.trim().is_empty() => crate::broker::uri::resolve(&b).ok(),
            _ => crate::autobroker::find_local_broker(),
        },
        crate::fetch_worker_list,
    )
}

fn local_workers_from(
    find: impl FnOnce() -> Option<String>,
    fetch: impl FnOnce(&str) -> Result<Vec<serde_json::Value>, String>,
) -> (Vec<serde_json::Value>, Option<String>) {
    let Some(url) = find() else {
        return (
            Vec::new(),
            Some("no broker is running on this machine — :up starts one".into()),
        );
    };
    match fetch(&url) {
        Ok(w) => (w, None),
        Err(e) => (Vec::new(), Some(e)),
    }
}

/// The last listing however old (its age shows), with live workers: what
/// the first frame draws while [`mesh_once`] may still be probing.
pub fn mesh_cached() -> Option<MeshSnapshot> {
    let (brokers, listing) = crate::listing_cache::load_any()?;
    let (workers, err) = local_workers();
    Some(MeshSnapshot::from_listing(
        &brokers, &listing, &workers, err,
    ))
}

fn client(dir: Option<&Path>) -> Option<AgentClient> {
    AgentClient::from_dir(dir?)
}

fn parse_summary(v: serde_json::Value) -> Result<Summary, String> {
    serde_json::from_value(v).map_err(|e| format!("agent summary: {e}"))
}

pub fn agent_once(dir: Option<&Path>) -> AgentState {
    let Some(c) = client(dir) else {
        return AgentState::NotRunning(None);
    };
    match c.summary(AGENT_TIMEOUT).and_then(parse_summary) {
        Ok(s) => AgentState::Running(Box::new(s)),
        Err(e) => AgentState::NotRunning(Some(e)),
    }
}

/// The agent API call for a write (agent `server.rs`: `/v1/sharing`,
/// `/v1/workers`, `/v1/price` with `scope: "device"`).
pub fn write_request(w: &Write) -> (&'static str, serde_json::Value) {
    match w {
        Write::Sharing(on) => ("/v1/sharing", serde_json::json!({ "on": on })),
        Write::Workers(n) => ("/v1/workers", serde_json::json!({ "count": n })),
        Write::Price(p) => (
            "/v1/price",
            serde_json::json!({ "scope": "device", "price_per_hour": p }),
        ),
    }
}

pub fn apply(dir: Option<&Path>, w: &Write) -> Result<Summary, String> {
    let c = client(dir).ok_or_else(|| "zc agent is not running".to_string())?;
    let (path, body) = write_request(w);
    c.put(path, body, WRITE_TIMEOUT).and_then(parse_summary)
}

/// `POST /v1/refresh`: the agent re-polls the hub and answers with the
/// fresh summary.
pub fn refresh_hub(dir: Option<&Path>) -> AgentState {
    let Some(c) = client(dir) else {
        return AgentState::NotRunning(None);
    };
    match c.post("/v1/refresh", WRITE_TIMEOUT).and_then(parse_summary) {
        Ok(s) => AgentState::Running(Box::new(s)),
        Err(e) => AgentState::NotRunning(Some(e)),
    }
}

/// Start the agent so that it outlives the session: launchd on macOS
/// (`zc agent install`, which waits for it to answer), else a detached
/// `zc agent run` in its own process group, then wait up to 5 s for it.
pub fn start_agent(dir: Option<&Path>) -> Result<(), String> {
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    let mut cmd = std::process::Command::new(&exe);
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    if cfg!(target_os = "macos") {
        let ok = cmd
            .args(["agent", "install"])
            .status()
            .is_ok_and(|s| s.success());
        return match ok {
            true => Ok(()),
            false => Err("`zc agent install` failed — run it in a shell to see why".into()),
        };
    }
    cmd.args(["agent", "run"]);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    cmd.spawn().map_err(|e| format!("starting zc agent: {e}"))?;
    for _ in 0..50 {
        std::thread::sleep(Duration::from_millis(100));
        if matches!(agent_once(dir), AgentState::Running(_)) {
            return Ok(());
        }
    }
    Err("zc agent did not answer within 5 s".into())
}

/// The handle the event loop keeps to nudge the mesh poller.
pub struct Pollers {
    pub(crate) mesh: Sender<()>,
}

impl Pollers {
    pub fn refresh_mesh(&self) {
        let _ = self.mesh.send(());
    }
}

/// One thread per source, each sending a snapshot at once and then on its
/// cadence (or when nudged). Both stop when the session's receiver is gone.
pub fn spawn_pollers(tx: Sender<Event>, dir: Option<PathBuf>) -> Pollers {
    let pollers = spawn_mesh_poller(tx.clone(), mesh_cached, mesh_once);
    std::thread::spawn(move || loop {
        if tx.send(Event::Agent(agent_once(dir.as_deref()))).is_err() {
            return;
        }
        std::thread::sleep(AGENT_EVERY);
    });
    pollers
}

/// The mesh poller: `cached` once, at once, when there is one; then `live`
/// now and every [`MESH_EVERY`] or when nudged.
pub fn spawn_mesh_poller(
    tx: Sender<Event>,
    cached: impl FnOnce() -> Option<MeshSnapshot> + Send + 'static,
    live: impl Fn() -> MeshSnapshot + Send + 'static,
) -> Pollers {
    let (mesh_tx, mesh_rx) = std::sync::mpsc::channel::<()>();
    std::thread::spawn(move || {
        if let Some(snap) = cached() {
            if tx.send(Event::Mesh(snap)).is_err() {
                return;
            }
        }
        loop {
            if tx.send(Event::Mesh(live())).is_err() {
                return;
            }
            if let Err(RecvTimeoutError::Disconnected) = mesh_rx.recv_timeout(MESH_EVERY) {
                return;
            }
        }
    });
    Pollers { mesh: mesh_tx }
}

/// Carry out the effects that need only the network; the event loop
/// handles the ones that need the terminal (copy, open, suspend).
pub fn execute(effect: Effect, tx: &Sender<Event>, pollers: &Pollers, dir: Option<PathBuf>) {
    let tx = tx.clone();
    match effect {
        Effect::RefreshMesh => pollers.refresh_mesh(),
        Effect::RefreshAgent => {
            std::thread::spawn(move || {
                let _ = tx.send(Event::Agent(refresh_hub(dir.as_deref())));
            });
        }
        Effect::Apply(w) => {
            std::thread::spawn(move || {
                let r = apply(dir.as_deref(), &w).map(Box::new);
                let _ = tx.send(Event::Done(w, r));
            });
        }
        Effect::StartAgent => {
            std::thread::spawn(move || {
                let r = start_agent(dir.as_deref());
                let _ = tx.send(Event::AgentStarted(r));
            });
        }
        Effect::Copy(_) | Effect::OpenUrl(_) | Effect::Suspend(_) => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::files::{save_json, AgentFile, AGENT_FILE};
    use std::io::{BufRead, BufReader, Read, Write as _};
    use std::sync::{Arc, Mutex};

    const SUMMARY: &str = include_str!("../../docs/agent-api/summary.v1.json");

    /// An agent stand-in: answers each connection with the next canned
    /// `(status, body)`, recording `"METHOD /path body"` for each request.
    fn stub_agent(replies: Vec<(u16, String)>) -> (PathBuf, Arc<Mutex<Vec<String>>>) {
        let dir = crate::agent::files::tests::tmp("session-data");
        std::fs::create_dir_all(&dir).unwrap();
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = l.local_addr().unwrap().port();
        save_json(
            &dir.join(AGENT_FILE),
            &AgentFile {
                v: 1,
                port,
                token: "tok".into(),
                pid: 0,
                version: "t".into(),
            },
        )
        .unwrap();
        let seen = Arc::new(Mutex::new(Vec::new()));
        let rec = seen.clone();
        std::thread::spawn(move || {
            for (code, body) in replies {
                let Ok((mut s, _)) = l.accept() else { return };
                let mut r = BufReader::new(s.try_clone().unwrap());
                let mut first = String::new();
                r.read_line(&mut first).unwrap();
                let mut len = 0usize;
                loop {
                    let mut h = String::new();
                    r.read_line(&mut h).unwrap();
                    if h.trim().is_empty() {
                        break;
                    }
                    if let Some(v) = h.to_ascii_lowercase().strip_prefix("content-length:") {
                        len = v.trim().parse().unwrap_or(0);
                    }
                }
                let mut b = vec![0; len];
                r.read_exact(&mut b).unwrap();
                let parts: Vec<&str> = first.split_whitespace().collect();
                rec.lock().unwrap().push(format!(
                    "{} {} {}",
                    parts[0],
                    parts[1],
                    String::from_utf8_lossy(&b)
                ));
                let _ = write!(
                    s,
                    "HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len()
                );
            }
        });
        (dir, seen)
    }

    #[test]
    fn no_agent_file_means_not_running_with_no_reason() {
        let dir = crate::agent::files::tests::tmp("session-none");
        assert_eq!(agent_once(Some(&dir)), AgentState::NotRunning(None));
        assert_eq!(agent_once(None), AgentState::NotRunning(None));
    }

    #[test]
    fn a_running_agent_yields_its_summary() {
        let (dir, _) = stub_agent(vec![(200, SUMMARY.into())]);
        match agent_once(Some(&dir)) {
            AgentState::Running(s) => assert_eq!(s.this_mac.name, "jeans-mbp"),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn a_dead_agent_port_is_not_running_with_a_reason() {
        let (dir, _) = stub_agent(vec![]);
        // The stub thread exits at once; nothing listens after it drops.
        std::thread::sleep(Duration::from_millis(50));
        assert!(matches!(
            agent_once(Some(&dir)),
            AgentState::NotRunning(Some(_))
        ));
    }

    #[test]
    fn writes_put_the_agent_contract_bodies() {
        assert_eq!(
            write_request(&Write::Sharing(true)),
            ("/v1/sharing", serde_json::json!({"on": true}))
        );
        assert_eq!(
            write_request(&Write::Workers(3)),
            ("/v1/workers", serde_json::json!({"count": 3}))
        );
        assert_eq!(
            write_request(&Write::Price(22.0)),
            (
                "/v1/price",
                serde_json::json!({"scope": "device", "price_per_hour": 22.0})
            )
        );
    }

    #[test]
    fn apply_returns_the_new_summary_or_the_agents_message() {
        let err = r#"{"error":{"code":"invalid_input","message":"price must be at most 120"}}"#;
        let (dir, seen) = stub_agent(vec![(200, SUMMARY.into()), (400, err.into())]);
        assert!(apply(Some(&dir), &Write::Workers(2)).is_ok());
        assert_eq!(
            apply(Some(&dir), &Write::Price(999.0)).unwrap_err(),
            "price must be at most 120"
        );
        let seen = seen.lock().unwrap();
        let (head, body) = seen[0].split_at("PUT /v1/workers ".len());
        assert_eq!(head, "PUT /v1/workers ");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(body).unwrap(),
            serde_json::json!({"count": 2})
        );
        assert!(seen[1].starts_with("PUT /v1/price "));
    }

    #[test]
    fn refresh_posts_to_the_agent() {
        let (dir, seen) = stub_agent(vec![(200, SUMMARY.into())]);
        assert!(matches!(refresh_hub(Some(&dir)), AgentState::Running(_)));
        assert!(seen.lock().unwrap()[0].starts_with("POST /v1/refresh"));
    }

    /// The first frame never waits on the network: a cached listing, of
    /// any age, goes out before the live one.
    #[test]
    fn the_cached_mesh_goes_out_before_the_live_one() {
        let (tx, rx) = std::sync::mpsc::channel();
        let _p = spawn_mesh_poller(
            tx,
            || {
                Some(MeshSnapshot {
                    as_of_secs: Some(999),
                    ..Default::default()
                })
            },
            || {
                std::thread::sleep(Duration::from_millis(200));
                MeshSnapshot::default()
            },
        );
        let first = rx
            .recv_timeout(Duration::from_millis(100))
            .expect("cached at once");
        assert!(
            matches!(first, Event::Mesh(ref m) if m.as_of_secs == Some(999)),
            "{first:?}"
        );
        let second = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(
            matches!(second, Event::Mesh(ref m) if m.as_of_secs.is_none()),
            "{second:?}"
        );
    }

    /// The session reads a broker that is already running and never starts
    /// one (`resolve_default_broker` would, and print over the screen).
    #[test]
    fn without_a_running_broker_there_are_no_workers_and_a_reason() {
        let (w, err) = local_workers_from(|| None, |_| unreachable!("nothing to fetch"));
        assert!(w.is_empty());
        assert!(err
            .unwrap()
            .contains("no broker is running on this machine"));
        let (w, err) = local_workers_from(
            || Some("http://127.0.0.1:9000".into()),
            |u| Ok(vec![serde_json::json!({"name": u})]),
        );
        assert_eq!(w.len(), 1);
        assert!(err.is_none());
    }

    /// The live listing probes on this thread and saves the result itself:
    /// no `refresh_in_background` child (one every poll, never reaped).
    #[test]
    fn a_live_listing_saves_what_it_probed() {
        use crate::{ListedBroker, Listing};
        let saved = std::cell::Cell::new(false);
        let fresh = (
            vec![ListedBroker {
                fp: "aaaa".into(),
                name: None,
                is_self: false,
            }],
            Listing::Directory {
                unreachable: 0,
                offline: 0,
                as_of_secs: None,
            },
        );
        let (b, _) = live_listing(|| Some(fresh.clone()), |_, _| saved.set(true), || None);
        assert_eq!(b[0].fp, "aaaa");
        assert!(saved.get());
    }

    #[test]
    fn without_the_hub_the_live_listing_falls_back_to_the_cache_then_local_only() {
        use crate::{ListedBroker, Listing};
        let cached = (
            vec![ListedBroker {
                fp: "cccc".into(),
                name: None,
                is_self: false,
            }],
            Listing::Directory {
                unreachable: 0,
                offline: 0,
                as_of_secs: Some(60),
            },
        );
        let (b, _) = live_listing(
            || None,
            |_, _| panic!("nothing to save"),
            || Some(cached.clone()),
        );
        assert_eq!(b[0].fp, "cccc");
        let (b, l) = live_listing(|| None, |_, _| panic!("nothing to save"), || None);
        assert!(b.is_empty());
        assert!(matches!(l, Listing::LocalOnly(_)));
    }

    #[test]
    fn execute_apply_sends_done() {
        let (dir, _) = stub_agent(vec![(200, SUMMARY.into())]);
        let (tx, rx) = std::sync::mpsc::channel();
        let (ptx, _prx) = std::sync::mpsc::channel();
        let pollers = Pollers { mesh: ptx };
        execute(
            Effect::Apply(Write::Sharing(false)),
            &tx,
            &pollers,
            Some(dir),
        );
        match rx.recv_timeout(Duration::from_secs(5)).unwrap() {
            Event::Done(Write::Sharing(false), Ok(_)) => {}
            other => panic!("{other:?}"),
        }
    }
}