zc2 0.0.51

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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Deployment reconciler: makes the hub's desired "environments" — pre-
//! loaded, warmed images ready to execute a remote function — true on THIS
//! host, reports progress back to the hub, rolls back on failure, and bills
//! served `/serve/:deployment_id` requests by execution time on every
//! verified (2xx) response.
//!
//! Contract with the hub (`zak-dashboard`, being built in parallel):
//!   GET  {api_url}/api/broker/deployments/desired
//!   POST {api_url}/api/broker/deployments/{id}/status
//!
//! Both are authenticated the same way the rest of the broker's dashboard
//! calls are (`X-Broker-Api-Key`), plus `X-Node-Pubkey` identifying which
//! host is reporting — a node only ever reconciles ITS OWN desired set, and
//! the hub uses the pubkey to tell nodes apart the same way it already does
//! for `/api/broker/node/register` (see `node_sync.rs`).

pub mod expose;
pub mod policy;
pub mod reconcile;
pub mod runtime;
pub mod serve;
pub mod state;

use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};

// Re-exported so external callers (and doc links) can name these without
// reaching into the submodules directly; `#[allow(unused_imports)]` because
// nothing in THIS crate currently needs the short path — they're still part
// of the module's public surface (used by name in doc comments) and by any
// future caller (e.g. a dashboard-shaped integration test) that wants
// `deploy::Action` rather than `deploy::reconcile::Action`.
#[allow(unused_imports)]
pub use reconcile::{plan, plan_failure, Action};
#[allow(unused_imports)]
pub use runtime::{
    doctor_report, runtime_available, runtime_probe, ContainerRuntime, DockerCli, RunSpec,
    RuntimeError, RuntimeProbe,
};
#[allow(unused_imports)]
pub use state::DeploymentRecord;
pub use state::LocalState;

/// One port the deployment's container listens on.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Port {
    pub container: u16,
    #[serde(default = "default_protocol")]
    pub protocol: String,
}

fn default_protocol() -> String {
    "http".to_string()
}

/// How to probe a running container for readiness.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Healthcheck {
    #[serde(rename = "type")]
    pub kind: String, // "http" | "tcp"
    pub port: u16,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(default = "default_timeout_s")]
    pub timeout_s: u64,
}

fn default_timeout_s() -> u64 {
    60
}

/// What a running environment may reach. `grants` are handed to the
/// container as env vars. `policy` is the hub's IAM-style policy document
/// (kept raw so an unparseable one fails closed instead of failing the whole
/// desired list); this node enforces its `network:Connect` statements on the
/// container's docker network — see [`policy`]. Other services (datasets,
/// storage, ...) are not enforced here. Unset / legacy-backfill policies are
/// not enforced (back-compat).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ServiceAccount {
    pub name: String,
    #[serde(default)]
    pub grants: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<serde_json::Value>,
}

/// The deployment this one is replacing, as the hub describes it. Usually
/// `previous.id == this.id` (a version bump of the same deployment); when it
/// names a DIFFERENT id, the hub is describing a slot handoff — e.g. a
/// blue/green cutover where this deployment takes over from another one
/// entirely — and this node stops that other deployment's container once
/// this one is healthy (see `reconcile::plan`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreviousDeployment {
    pub id: String,
    pub image: String,
    #[serde(default)]
    pub cmd: Option<String>,
    #[serde(default)]
    pub ports: Vec<Port>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
    #[serde(default)]
    pub healthcheck: Option<Healthcheck>,
}

/// One entry of `GET /api/broker/deployments/desired`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Desired {
    pub id: String,
    pub version: u64,
    pub name: String,
    pub image: String,
    #[serde(default)]
    pub cmd: Option<String>,
    #[serde(default)]
    pub ports: Vec<Port>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
    #[serde(default)]
    pub healthcheck: Option<Healthcheck>,
    /// Yen per second of execution — billed per served request on
    /// `duration_ms` actually spent proxied into the environment (see
    /// `deploy::serve`), not a flat per-call price. The hub has already
    /// resolved this to an effective value for auto-priced deployments.
    pub price_per_second: f64,
    pub desired_state: String, // "running" | "stopped"
    /// What this environment may reach; its network policy is enforced on
    /// this node (see `ServiceAccount` and [`policy`]).
    #[serde(default)]
    pub service_account: Option<ServiceAccount>,
    /// `true`: keep the environment's container running and ready.
    /// `false`: allowed to stop it when idle and cold-start on the next
    /// `/serve` call — NOT YET IMPLEMENTED, treated as `true` (see
    /// `reconcile::drive`'s `Start` handling).
    #[serde(default = "default_warm")]
    pub warm: bool,
    #[serde(default)]
    pub previous: Option<Box<PreviousDeployment>>,
}

pub(crate) fn default_warm() -> bool {
    true
}

#[derive(Debug, Deserialize)]
struct DesiredResponse {
    deployments: Vec<Desired>,
}

/// `GET {api_url}/api/broker/deployments/desired` for this node.
pub fn fetch_desired(
    api_url: &str,
    api_key: &str,
    node_pubkey: &str,
) -> Result<Vec<Desired>, String> {
    let endpoint = format!(
        "{}/api/broker/deployments/desired",
        api_url.trim_end_matches('/')
    );
    let resp = ureq::get(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("X-Node-Pubkey", node_pubkey)
        .call()
        .map_err(|e| e.to_string())?;
    if resp.status().as_u16() != 200 {
        return Err(format!("fetch_desired HTTP {}", resp.status().as_u16()));
    }
    let text = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    let parsed: DesiredResponse = serde_json::from_str(&text).map_err(|e| e.to_string())?;
    Ok(parsed.deployments)
}

/// The body of `POST {api_url}/api/broker/deployments/{id}/status`.
/// `mesh_endpoint` is always present, `null` when the deployment isn't
/// exposed: each report replaces the hub's row, so leaving the key out would
/// not mean "unchanged". `failure` adds `code`, `logs` and `probes_failed`
/// when set, and each only when it has a value (an older hub ignores unknown
/// fields; a missing key is how it tells "no logs" from empty ones). `logs`
/// is the startup log tail of a `healthy` report, which has no `failure`: it
/// adds `logs` alone, never a `code`.
#[allow(clippy::too_many_arguments)]
fn status_payload(
    node_pubkey: &str,
    version: u64,
    phase: &str,
    message: &str,
    attempt: u32,
    container_id: Option<&str>,
    endpoint: Option<&str>,
    mesh_endpoint: Option<&str>,
    failure: Option<&reconcile::FailureDetail>,
    logs: Option<&str>,
) -> serde_json::Value {
    let mut payload = serde_json::json!({
        "node_pubkey": node_pubkey,
        "version": version,
        "phase": phase,
        "message": message,
        "attempt": attempt,
        "container_id": container_id,
        "endpoint": endpoint,
        "mesh_endpoint": mesh_endpoint,
    });
    if let Some(f) = failure {
        payload["code"] = serde_json::json!(f.code);
        if let Some(logs) = &f.logs {
            payload["logs"] = serde_json::json!(logs);
        }
        if let Some(n) = f.probes_failed {
            payload["probes_failed"] = serde_json::json!(n);
        }
    } else if let Some(logs) = logs {
        payload["logs"] = serde_json::json!(logs);
    }
    payload
}

/// `POST {api_url}/api/broker/deployments/{id}/status`. A non-2xx answer
/// (e.g. an older hub that 422s the `health_check` phase) is not an error
/// here: the status is dropped and the reconcile loop carries on.
#[allow(clippy::too_many_arguments)]
pub fn report_status(
    api_url: &str,
    api_key: &str,
    node_pubkey: &str,
    id: &str,
    version: u64,
    phase: &str,
    message: &str,
    attempt: u32,
    container_id: Option<&str>,
    endpoint: Option<&str>,
    mesh_endpoint: Option<&str>,
    failure: Option<&reconcile::FailureDetail>,
    logs: Option<&str>,
) {
    let url = format!(
        "{}/api/broker/deployments/{}/status",
        api_url.trim_end_matches('/'),
        id
    );
    let payload = status_payload(
        node_pubkey,
        version,
        phase,
        message,
        attempt,
        container_id,
        endpoint,
        mesh_endpoint,
        failure,
        logs,
    );
    let body = serde_json::to_string(&payload).unwrap_or_default();
    let result = ureq::post(&url)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("X-Node-Pubkey", node_pubkey)
        .header("Content-Type", "application/json")
        .send(body.as_str());
    if let Err(e) = result {
        eprintln!("  [DEPLOY] failed to report status for {id}: {e}");
    }
}

/// `reconcile::StatusReporter` backed by the real hub HTTP contract above.
pub struct HttpReporter<'a> {
    pub api_url: &'a str,
    pub api_key: &'a str,
    pub node_pubkey: &'a str,
}

impl reconcile::StatusReporter for HttpReporter<'_> {
    fn report(
        &self,
        id: &str,
        version: u64,
        phase: &str,
        message: &str,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        mesh_endpoint: Option<&str>,
    ) {
        report_status(
            self.api_url,
            self.api_key,
            self.node_pubkey,
            id,
            version,
            phase,
            message,
            attempt,
            container_id,
            endpoint,
            mesh_endpoint,
            None,
            None,
        );
    }

    fn report_healthy(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        endpoint: Option<&str>,
        logs: Option<&str>,
    ) {
        report_status(
            self.api_url,
            self.api_key,
            self.node_pubkey,
            id,
            version,
            "healthy",
            "",
            attempt,
            container_id,
            endpoint,
            None,
            None,
            logs,
        );
    }

    fn report_failure(
        &self,
        id: &str,
        version: u64,
        attempt: u32,
        container_id: Option<&str>,
        failure: &reconcile::FailureDetail,
    ) {
        report_status(
            self.api_url,
            self.api_key,
            self.node_pubkey,
            id,
            version,
            "failed",
            &failure.message,
            attempt,
            container_id,
            None,
            None,
            Some(failure),
            None,
        );
    }
}

/// One reconcile pass: fetch desired state from the hub and drive local
/// docker state toward it. Called from the broker's periodic tick loop (see
/// `server.rs`, "Periodic worker sync"); a no-op when `api_url`/`api_key`
/// aren't configured — a broker with no dashboard has nothing to reconcile
/// against, same precondition `WORKER_SYNC` and the roster refresh use.
pub fn tick(state: &Arc<crate::broker::BrokerState>) {
    let (Some(api_url), Some(api_key)) = (&state.config.api_url, &state.config.api_key) else {
        return;
    };
    let node_pubkey = state.node_key.public_b64();

    let desired = match fetch_desired(api_url, api_key, &node_pubkey) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("  [DEPLOY] failed to fetch desired deployments: {e}");
            return;
        }
    };
    // An EMPTY list from a successful fetch still reconciles: the hub drops a
    // deleted deployment after its stopped grace period, and `plan()` tears
    // down whatever the node still runs that the hub no longer lists. Only a
    // fetch ERROR (above) skips the pass — it must never tear anything down.

    let rt = DockerCli;
    if !rt.available() {
        // Say why (zc#473): the probe's reason + next step, not a fixed string.
        let failure =
            reconcile::FailureDetail::new("no_runtime", runtime_probe().failure_message());
        // Nothing this node can do — tell the hub once per tick rather than
        // silently leaving every deployment stuck "pending" from its side
        // (an empty list has nothing to report).
        for d in &desired {
            if d.desired_state == "running" {
                report_status(
                    api_url,
                    api_key,
                    &node_pubkey,
                    &d.id,
                    d.version,
                    "failed",
                    &failure.message,
                    1,
                    None,
                    None,
                    None,
                    Some(&failure),
                    None,
                );
            }
        }
        return;
    }

    let mut local = LocalState::load();
    let reporter = HttpReporter {
        api_url,
        api_key,
        node_pubkey: &node_pubkey,
    };
    let mesh_ip = expose::exposure_ip(
        crate::broker::discovery::get_mesh_ip(),
        std::env::var("ZAKURO_MESH_EXPOSE").ok().as_deref(),
    );
    if mesh_ip.is_some() {
        // Who may use the mesh forwarder: the owner's addresses (zc#212).
        expose::refresh_allowlist(api_url, api_key);
    }
    reconcile::drive_and_expose(
        &rt,
        &reporter,
        expose::forwarder(),
        mesh_ip.as_deref(),
        &desired,
        &mut local,
    );
}

/// `zc deployments` — print this node's local reconciler state (from
/// `deployments.json`) plus a `docker ps` view of the containers it created,
/// for debugging a stuck or unexpected deployment without reaching for
/// `sqlite3`/dashboard access.
pub fn print_deployments() {
    let local = LocalState::load();
    if local.deployments.is_empty() {
        println!("No local deployment state (nothing reconciled on this node yet).");
    } else {
        println!(
            "{:<24} {:>7}  {:<12} {:<22} {:<22} {:<6} {:<20} CONTAINER",
            "DEPLOYMENT", "VERSION", "PHASE", "ENDPOINT", "MESH", "WARM", "SERVICE_ACCOUNT"
        );
        let mut ids: Vec<&String> = local.deployments.keys().collect();
        ids.sort();
        for id in ids {
            let rec = &local.deployments[id];
            let service_account = rec
                .service_account
                .as_ref()
                .map(|sa| {
                    let net = if policy::network_access(Some(sa)).isolated() {
                        " net=isolated"
                    } else {
                        ""
                    };
                    format!("{}[{}]{net}", sa.name, sa.grants.join(","))
                })
                .unwrap_or_else(|| "-".to_string());
            println!(
                "{:<24} {:>7}  {:<12} {:<22} {:<22} {:<6} {:<20} {}",
                id,
                rec.version,
                rec.phase,
                rec.endpoint.as_deref().unwrap_or("-"),
                rec.mesh_endpoint.as_deref().unwrap_or("-"),
                rec.warm,
                service_account,
                rec.container_id.as_deref().unwrap_or("-"),
            );
        }
    }

    println!();
    let rt = DockerCli;
    if !rt.available() {
        println!("(docker not available on this host)");
        return;
    }
    let ps = [
        "ps",
        "-a",
        "--filter",
        "label=zakuro.deployment",
        "--format",
        "table {{.Names}}\t{{.Status}}\t{{.Ports}}",
    ]
    .map(String::from);
    match crate::sandbox::engine::command(&ps)
        .and_then(|mut c| c.output().map_err(|e| e.to_string()))
    {
        Ok(out) if out.status.success() => {
            print!("{}", String::from_utf8_lossy(&out.stdout));
        }
        Ok(out) => {
            eprintln!(
                "docker ps failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Err(e) => eprintln!("docker ps failed: {e}"),
    }
}

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

    #[test]
    fn status_payload_carries_the_mesh_endpoint() {
        let payload = status_payload(
            "pk",
            3,
            "healthy",
            "",
            1,
            Some("c1"),
            Some("172.17.0.3:8888"),
            Some("10.13.13.22:8888"),
            None,
            None,
        );
        assert_eq!(payload["endpoint"], "172.17.0.3:8888");
        assert_eq!(payload["mesh_endpoint"], "10.13.13.22:8888");
    }

    #[test]
    fn status_payload_sends_an_explicit_null_when_not_exposed() {
        let payload = status_payload("pk", 3, "stopped", "", 1, None, None, None, None, None);
        assert!(payload.get("mesh_endpoint").is_some_and(|v| v.is_null()));
    }

    #[test]
    fn status_payload_omits_failure_fields_unless_set() {
        let payload = status_payload("pk", 3, "healthy", "", 1, None, None, None, None, None);
        for key in ["code", "logs", "probes_failed"] {
            assert!(payload.get(key).is_none(), "{key} should be absent");
        }
    }

    #[test]
    fn status_payload_carries_healthy_startup_logs_without_a_code() {
        let payload = status_payload(
            "pk",
            3,
            "healthy",
            "",
            1,
            Some("c1"),
            Some("172.17.0.3:8888"),
            None,
            None,
            Some("token=abc"),
        );
        assert_eq!(payload["phase"], "healthy");
        assert_eq!(payload["logs"], "token=abc");
        assert!(payload.get("code").is_none());
        assert!(payload.get("probes_failed").is_none());
    }

    #[test]
    fn status_payload_carries_failure_code_logs_and_probes() {
        let mut f =
            reconcile::FailureDetail::new("health_failed", "GET http://1.2.3.4:80/ → HTTP 503");
        f.logs = Some("boom".to_string());
        f.probes_failed = Some(7);
        let payload = status_payload(
            "pk",
            3,
            "failed",
            &f.message,
            1,
            Some("c1"),
            None,
            None,
            Some(&f),
            None,
        );
        assert_eq!(payload["phase"], "failed");
        assert_eq!(payload["code"], "health_failed");
        assert_eq!(payload["message"], "GET http://1.2.3.4:80/ → HTTP 503");
        assert_eq!(payload["logs"], "boom");
        assert_eq!(payload["probes_failed"], 7);

        // A pull failure has a code but no logs / probe count.
        let pull = reconcile::FailureDetail::new("pull_failed", "denied");
        let payload = status_payload(
            "pk",
            3,
            "failed",
            &pull.message,
            1,
            None,
            None,
            None,
            Some(&pull),
            None,
        );
        assert_eq!(payload["code"], "pull_failed");
        assert!(payload.get("logs").is_none());
        assert!(payload.get("probes_failed").is_none());
    }
}