zc2 0.0.52

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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Several nodes on one machine (ADR ZC-0027).
//!
//! A machine always has its **main** node: the agent's own broker and share
//! workers, which take the hub's jobs. The owner may add up to [`MAX_EXTRA`]
//! more, each one a real mesh node:
//!
//! - its own identity (`<home>/nodes/<id>/state/node_key`) and policy, so the
//!   hub lists it as its own device;
//! - its own broker (`zc broker <port>`, a host process, on the machine's one
//!   mesh address);
//! - its workers as a `docker compose` project (`zk-node-<id>`) in the
//!   machine's one sandbox (the Lima/Colima VM, the LXC sandbox, or Docker);
//! - a fixed share of the owner's limit, taken out of what the main node may
//!   lend, so all nodes together never exceed that limit;
//! - optionally one hub environment it hosts (`environment`): the node then
//!   takes environment guests only, and the main node keeps the hub's jobs.
//!
//! `nodes.json` under the machine's home is the registry. `zc node run <id>`
//! runs one node until SIGTERM; the agent keeps one per registered node
//! while sharing is on (`agent::node_manager`).

pub mod cli;
pub mod runner;
pub mod usage;

use crate::sandbox::{Amount, Budget, HostResources, Limits};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// The main node's id: the one the agent itself runs.
pub const MAIN: &str = "main";
/// Set by `zc node run` on itself and its broker: which node this process is.
pub const ID_ENV: &str = "ZAKURO_NODE_ID";
/// On every container an extra node starts. Absent: the main node's.
pub const NODE_LABEL: &str = "zakuro.node";
/// Extra nodes per machine. Each takes two broker ports from the relayed
/// range 9000-9010 (broker + QUIC), and the main node holds 9000/9001.
pub const MAX_EXTRA: u32 = 4;
pub const MAX_WORKERS: u32 = 8;

const GIB: u64 = 1024 * 1024 * 1024;
/// What the main node always keeps, so the hub's jobs still have a home.
pub const MAIN_MIN_CPU_MILLIS: u32 = 1000;
pub const MAIN_MIN_MEMORY: u64 = 2 * GIB;
/// The smallest extra node.
pub const NODE_MIN_CPU_MILLIS: u32 = 500;
pub const NODE_MIN_MEMORY: u64 = GIB;
pub const NODE_MIN_DISK: u64 = 5 * GIB;

/// Ask a child process to stop: SIGTERM on Unix, so it can tear down what
/// it started; elsewhere there is no polite signal, so it is killed.
pub fn ask_to_stop(child: &mut std::process::Child) {
    #[cfg(unix)]
    // SAFETY: kill(2) on our own child's pid.
    unsafe {
        libc::kill(child.id() as libc::pid_t, libc::SIGTERM);
    }
    #[cfg(not(unix))]
    {
        let _ = child.kill();
    }
}

/// This process's node when it is an extra one.
pub fn explicit_id() -> Option<String> {
    std::env::var(ID_ENV)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty() && v != MAIN)
}

pub fn current_id() -> String {
    explicit_id().unwrap_or_else(|| MAIN.to_string())
}

/// One extra node, as registered.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NodeSpec {
    /// `[a-z0-9-]{1,24}`: the directory, the compose project, the label.
    pub id: String,
    /// 1..=[`MAX_EXTRA`]: picks the ports. Never reused while registered.
    pub index: u32,
    /// The hub environment template this node hosts; `None`: more of the
    /// hub's jobs.
    #[serde(default)]
    pub environment: Option<String>,
    /// The template's display name, kept for when the hub is unreachable.
    #[serde(default)]
    pub environment_name: Option<String>,
    pub workers: u32,
    pub cpu_millis: u32,
    pub memory_bytes: u64,
    pub disk_bytes: u64,
    /// RFC 3339.
    pub created: String,
}

impl NodeSpec {
    /// The broker's port; QUIC takes the next one.
    pub fn broker_port(&self) -> u16 {
        9000 + 2 * self.index as u16
    }

    /// Worker `i`'s port, published on the host's loopback only. 40 apart:
    /// the main node scans `3960..3960+max_workers+19`.
    pub fn worker_port(&self, i: u32) -> u16 {
        3960 + 40 * self.index as u16 + i as u16
    }

    pub fn scan_range(&self) -> String {
        format!(
            "{}-{}",
            self.worker_port(0),
            self.worker_port(MAX_WORKERS + 3)
        )
    }

    pub fn project(&self) -> String {
        format!("zk-node-{}", self.id)
    }

    pub fn dir(&self, home: &Path) -> PathBuf {
        node_dir(home, &self.id)
    }

    /// The node's own zakuro home (`ZAKURO_HOME` of its broker).
    pub fn state_dir(&self, home: &Path) -> PathBuf {
        self.dir(home).join("state")
    }

    pub fn limits(&self) -> Limits {
        Limits {
            cpu_millis: self.cpu_millis,
            memory_bytes: self.memory_bytes,
            gpus: crate::sandbox::Gpus::None,
        }
    }

    /// The share of the node its compose workers split. A node that hosts
    /// an environment keeps half for the environment itself when it also
    /// runs workers, and all of it when it runs none.
    pub fn workers_share(&self) -> Limits {
        let l = self.limits();
        if self.environment.is_some() {
            Limits {
                cpu_millis: l.cpu_millis / 2,
                memory_bytes: l.memory_bytes / 2,
                gpus: l.gpus,
            }
        } else {
            l
        }
    }

    /// `ZAKURO_DEPLOY_BUDGET_SLICE` for the node's broker: what one
    /// environment deployment may take of the node.
    pub fn deploy_slice(&self) -> &'static str {
        match (self.environment.is_some(), self.workers) {
            (true, 0) => "100%",
            (true, _) => "50%",
            (false, _) => "25%",
        }
    }
}

pub fn nodes_dir(home: &Path) -> PathBuf {
    home.join("nodes")
}

pub fn node_dir(home: &Path, id: &str) -> PathBuf {
    nodes_dir(home).join(id)
}

/// What the extra nodes hold of the owner's limit.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reserved {
    pub cpu_millis: u32,
    pub memory_bytes: u64,
    pub disk_bytes: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
    #[serde(default)]
    pub v: u32,
    #[serde(default)]
    pub nodes: Vec<NodeSpec>,
}

impl Registry {
    pub fn path(home: &Path) -> PathBuf {
        nodes_dir(home).join("nodes.json")
    }

    /// The registry at `home`. Missing or unreadable: no extra nodes (a
    /// machine that never made one has no file).
    pub fn load(home: &Path) -> Registry {
        let mut reg: Registry = std::fs::read(Self::path(home))
            .ok()
            .and_then(|b| serde_json::from_slice(&b).ok())
            .unwrap_or_default();
        // The ids become directory names and labels: a hand-edited file
        // cannot smuggle a path in.
        reg.nodes
            .retain(|n| valid_id(&n.id) && (1..=MAX_EXTRA).contains(&n.index));
        reg
    }

    /// Atomic: a reader never sees half a file.
    pub fn save(&self, home: &Path) -> Result<(), String> {
        let path = Self::path(home);
        let dir = nodes_dir(home);
        std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
        let mut out = self.clone();
        out.v = 1;
        let tmp = dir.join(format!(".nodes.json.{}", std::process::id()));
        let body = serde_json::to_vec_pretty(&out).map_err(|e| e.to_string())?;
        std::fs::write(&tmp, body).map_err(|e| format!("{}: {e}", tmp.display()))?;
        std::fs::rename(&tmp, &path).map_err(|e| format!("{}: {e}", path.display()))
    }

    pub fn get(&self, id: &str) -> Option<&NodeSpec> {
        self.nodes.iter().find(|n| n.id == id)
    }

    pub fn reserved(&self) -> Reserved {
        self.reserved_except(None)
    }

    fn reserved_except(&self, skip: Option<&str>) -> Reserved {
        let mut r = Reserved::default();
        for n in self.nodes.iter().filter(|n| Some(n.id.as_str()) != skip) {
            r.cpu_millis += n.cpu_millis;
            r.memory_bytes += n.memory_bytes;
            r.disk_bytes += n.disk_bytes;
        }
        r
    }

    fn free_index(&self) -> Option<u32> {
        (1..=MAX_EXTRA).find(|i| self.nodes.iter().all(|n| n.index != *i))
    }
}

/// The owner's limit for the whole machine, resolved on this host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MachineLimit {
    pub cpu_millis: u32,
    pub memory_bytes: u64,
    pub disk_bytes: u64,
}

impl MachineLimit {
    pub fn from_budget(b: &Budget, host: &HostResources) -> Result<Self, String> {
        let l = b.total(host)?;
        Ok(Self {
            cpu_millis: l.cpu_millis,
            memory_bytes: l.memory_bytes,
            disk_bytes: b.disk_bytes,
        })
    }

    /// The machine's limit from its policy file.
    pub fn load(home: &Path) -> Result<Self, String> {
        let b = crate::policy::machine_budget(Some(home), &|k| std::env::var(k).ok())?;
        Self::from_budget(&b, &HostResources::detect())
    }

    /// What is left for the main node once `r` is taken.
    pub fn main_share(&self, r: &Reserved) -> MachineLimit {
        MachineLimit {
            cpu_millis: self.cpu_millis.saturating_sub(r.cpu_millis),
            memory_bytes: self.memory_bytes.saturating_sub(r.memory_bytes),
            disk_bytes: self.disk_bytes.saturating_sub(r.disk_bytes),
        }
    }
}

/// `budget` (the machine's) less what the extra nodes hold: the main node's
/// own budget. With nothing reserved it is returned untouched, percentages
/// and all. A share that cannot be resolved on this host (a memory
/// percentage of an unknown total) is left as it is.
pub fn minus_reserved(budget: Budget, r: &Reserved, host: &HostResources) -> Budget {
    if *r == Reserved::default() {
        return budget;
    }
    let Ok(total) = MachineLimit::from_budget(&budget, host) else {
        return budget;
    };
    let left = total.main_share(r);
    Budget {
        // Never zero: an over-reserved machine (the limit was lowered under
        // its nodes) leaves the main node its floor, and admission refuses
        // what does not fit.
        cpu: Amount::Absolute(f64::from(left.cpu_millis.max(100)) / 1000.0),
        memory: Amount::Absolute(left.memory_bytes.max(256 * 1024 * 1024) as f64),
        gpu: budget.gpu,
        disk_bytes: left.disk_bytes,
    }
}

/// What the owner asks for when adding a node.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NewNode {
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub environment: Option<String>,
    #[serde(default)]
    pub environment_name: Option<String>,
    #[serde(default)]
    pub workers: Option<u32>,
    pub cpu_cores: f64,
    pub memory_bytes: u64,
    #[serde(default)]
    pub disk_bytes: Option<u64>,
}

/// `[a-z0-9-]`, from a name or a template id; `node` when nothing is left.
pub fn slug(raw: &str) -> String {
    let mut s = String::new();
    for c in raw.trim().to_ascii_lowercase().chars() {
        if c.is_ascii_lowercase() || c.is_ascii_digit() {
            s.push(c);
        } else if !s.ends_with('-') && !s.is_empty() {
            s.push('-');
        }
    }
    let s: String = s.trim_end_matches('-').chars().take(24).collect();
    let s = s.trim_end_matches('-').to_string();
    if s.is_empty() || s == MAIN {
        "node".into()
    } else {
        s
    }
}

/// Whether `id` is one [`slug`] could have made: safe as a directory name.
pub fn valid_id(id: &str) -> bool {
    !id.is_empty() && id != MAIN && slug(id) == id
}

fn unique_id(reg: &Registry, base: &str) -> String {
    if reg.get(base).is_none() {
        return base.to_string();
    }
    (2..)
        .map(|n| {
            let tail = format!("-{n}");
            let head: String = base.chars().take(24 - tail.len()).collect();
            format!("{head}{tail}")
        })
        .find(|c| reg.get(c).is_none())
        .unwrap_or_else(|| base.to_string())
}

fn check_size(
    reg: &Registry,
    skip: Option<&str>,
    cpu_millis: u32,
    memory_bytes: u64,
    disk_bytes: u64,
    workers: u32,
    machine: &MachineLimit,
) -> Result<(), String> {
    if workers > MAX_WORKERS {
        return Err(format!("a node runs at most {MAX_WORKERS} workers"));
    }
    if cpu_millis < NODE_MIN_CPU_MILLIS {
        return Err("a node needs at least half a core".into());
    }
    if memory_bytes < NODE_MIN_MEMORY {
        return Err("a node needs at least 1 GB of memory".into());
    }
    if disk_bytes < NODE_MIN_DISK {
        return Err("a node needs at least 5 GB of disk".into());
    }
    let mut r = reg.reserved_except(skip);
    r.cpu_millis += cpu_millis;
    r.memory_bytes += memory_bytes;
    r.disk_bytes += disk_bytes;
    let left = machine.main_share(&r);
    let gb = |b: u64| b as f64 / GIB as f64;
    if left.cpu_millis < MAIN_MIN_CPU_MILLIS || r.cpu_millis > machine.cpu_millis {
        return Err(format!(
            "not enough CPU inside Zakuro's limit: the limit is {:.1} cores, and the main node keeps at least 1. Raise the limit on Resources, or make a node smaller.",
            f64::from(machine.cpu_millis) / 1000.0
        ));
    }
    if left.memory_bytes < MAIN_MIN_MEMORY || r.memory_bytes > machine.memory_bytes {
        return Err(format!(
            "not enough memory inside Zakuro's limit: the limit is {:.1} GB, and the main node keeps at least 2. Raise the limit on Resources, or make a node smaller.",
            gb(machine.memory_bytes)
        ));
    }
    if r.disk_bytes > machine.disk_bytes {
        return Err(format!(
            "not enough disk inside Zakuro's limit ({:.0} GB). Raise the limit on Resources, or make a node smaller.",
            gb(machine.disk_bytes)
        ));
    }
    Ok(())
}

/// The spec for a new node, or why it cannot be added. Nothing is written.
pub fn plan_add(
    reg: &Registry,
    req: &NewNode,
    machine: &MachineLimit,
    now: &str,
) -> Result<NodeSpec, String> {
    let Some(index) = reg.free_index() else {
        return Err(format!(
            "this machine already runs {MAX_EXTRA} extra nodes, the most it can"
        ));
    };
    let environment = req
        .environment
        .as_ref()
        .map(|e| e.trim().to_string())
        .filter(|e| !e.is_empty());
    if let Some(e) = &environment {
        if let Some(n) = reg
            .nodes
            .iter()
            .find(|n| n.environment.as_deref() == Some(e))
        {
            return Err(format!("node {} already hosts {e}", n.id));
        }
    }
    let base = match (&req.id, &environment) {
        (Some(id), _) if !id.trim().is_empty() => {
            let s = slug(id);
            if s != id.trim() {
                return Err("a node id is lowercase letters, digits and dashes (24 at most), and not \"main\"".into());
            }
            if reg.get(&s).is_some() {
                return Err(format!("there is already a node {s}"));
            }
            s
        }
        (_, Some(e)) => slug(e),
        _ => "jobs".to_string(),
    };
    // A node with an environment needs no worker of its own; one that takes
    // more of the hub's jobs is nothing without at least one.
    let workers = req
        .workers
        .unwrap_or(if environment.is_some() { 0 } else { 1 });
    if environment.is_none() && workers == 0 {
        return Err("a node with no environment needs at least one worker".into());
    }
    if !(req.cpu_cores.is_finite() && req.cpu_cores > 0.0 && req.cpu_cores <= 1024.0) {
        return Err("cpu_cores must be a positive number".into());
    }
    let cpu_millis = (req.cpu_cores * 1000.0).round() as u32;
    let disk_bytes = req.disk_bytes.unwrap_or(10 * GIB);
    check_size(
        reg,
        None,
        cpu_millis,
        req.memory_bytes,
        disk_bytes,
        workers,
        machine,
    )?;
    Ok(NodeSpec {
        id: unique_id(reg, &base),
        index,
        environment,
        environment_name: req
            .environment_name
            .clone()
            .filter(|n| !n.trim().is_empty()),
        workers,
        cpu_millis,
        memory_bytes: req.memory_bytes,
        disk_bytes,
        created: now.to_string(),
    })
}

/// A change to a registered node's size or workers.
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct NodePatch {
    #[serde(default)]
    pub workers: Option<u32>,
    #[serde(default)]
    pub cpu_cores: Option<f64>,
    #[serde(default)]
    pub memory_bytes: Option<u64>,
    #[serde(default)]
    pub disk_bytes: Option<u64>,
}

pub fn plan_patch(
    reg: &Registry,
    id: &str,
    patch: &NodePatch,
    machine: &MachineLimit,
) -> Result<NodeSpec, String> {
    let mut n = reg
        .get(id)
        .cloned()
        .ok_or_else(|| format!("no node {id}"))?;
    if let Some(w) = patch.workers {
        n.workers = w;
    }
    if let Some(c) = patch.cpu_cores {
        if !(c.is_finite() && c > 0.0 && c <= 1024.0) {
            return Err("cpu_cores must be a positive number".into());
        }
        n.cpu_millis = (c * 1000.0).round() as u32;
    }
    if let Some(m) = patch.memory_bytes {
        n.memory_bytes = m;
    }
    if let Some(d) = patch.disk_bytes {
        n.disk_bytes = d;
    }
    if n.environment.is_none() && n.workers == 0 {
        return Err("a node with no environment needs at least one worker".into());
    }
    check_size(
        reg,
        Some(id),
        n.cpu_millis,
        n.memory_bytes,
        n.disk_bytes,
        n.workers,
        machine,
    )?;
    Ok(n)
}

/// Worker `i`'s name: the node's own fingerprint first, as the main node's.
pub fn worker_name(fp8: &str, i: u32) -> String {
    format!("{fp8}-w{i}")
}

/// One worker of a node's compose project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposeWorker {
    pub service: String,
    pub name: String,
    pub container: String,
    pub port: u16,
}

pub fn compose_workers(spec: &NodeSpec, fp8: &str) -> Vec<ComposeWorker> {
    (0..spec.workers)
        .map(|i| {
            let name = worker_name(fp8, i);
            ComposeWorker {
                service: format!("w{i}"),
                container: crate::up::worker_container_name(&name),
                name,
                port: spec.worker_port(i),
            }
        })
        .collect()
}

/// The node's `compose.yaml`: one service per worker, each with its slice
/// of the node as hard limits, published on the host's loopback only, and
/// labelled so the budget sum and the usage view find it. The image's own
/// entrypoint runs; the worker is exec'd into it afterwards, exactly as the
/// main node's share workers are (`up::share_start_spec`).
pub fn compose_yaml(spec: &NodeSpec, fp8: &str, image: &str) -> String {
    let workers = compose_workers(spec, fp8);
    let per = spec.workers_share().split(spec.workers.max(1));
    let q = |s: &str| serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into());
    let mut y = format!(
        "# Written by zc for node {} (ADR ZC-0027). Do not edit: zc rewrites it.\nname: {}\n",
        spec.id,
        spec.project()
    );
    if workers.is_empty() {
        y.push_str("services: {}\n");
        return y;
    }
    y.push_str("services:\n");
    for w in &workers {
        y.push_str(&format!(
            "  {svc}:\n    image: {image}\n    container_name: {container}\n    restart: \"no\"\n    cpus: {cpus}\n    mem_limit: {mem}\n    memswap_limit: {mem}\n    environment:\n      {s6}: \"0\"\n    ports:\n      - \"127.0.0.1:{port}:{port}\"\n    labels:\n      zakuro.share: \"1\"\n      zakuro.worker: {name}\n      {node_label}: {node}\n      {budget_label}: {budget}\n",
            svc = w.service,
            image = q(image),
            container = q(&w.container),
            cpus = per.cpus_flag(),
            mem = per.memory_bytes,
            s6 = crate::up::S6_WAIT_ENV,
            port = w.port,
            name = q(&w.name),
            node_label = NODE_LABEL,
            node = q(&spec.id),
            budget_label = crate::sandbox::BUDGET_LABEL,
            budget = q(&per.budget_label()),
        ));
    }
    y
}

/// The node's `policy.toml` content: its share as the budget, and what it
/// takes. An environment node takes environment guests only; a jobs node
/// takes what the main node takes, less environments.
pub fn apply_policy(p: &mut crate::policy::Policy, spec: &NodeSpec) {
    p.budget.cpu = format!("{}", f64::from(spec.cpu_millis) / 1000.0);
    p.budget.memory = format!("{}", spec.memory_bytes);
    p.budget.disk = format!("{}G", (spec.disk_bytes / GIB).max(1));
    // No container backend hands a GPU to an extra node yet.
    p.budget.gpu = false;
    let env = spec.environment.is_some();
    p.workloads.environments = env;
    p.workloads.spaces = !env;
    p.workloads.hub_serving = !env;
    p.workloads.atelier = crate::policy::Atelier::Off;
}

// ---- the registry's operations (the CLI and the agent's API share them) ----

/// Left in a removed node's directory until the agent has stopped it, taken
/// its environment off the hub and deleted the directory.
pub const REMOVED_MARKER: &str = "removed";

/// Register a new node at `home` and give it its identity. The agent starts
/// it within a few seconds while sharing is on.
pub fn add(home: &Path, req: &NewNode) -> Result<NodeSpec, String> {
    let _guard = crate::policy::lock(home)?;
    let mut reg = Registry::load(home);
    let machine = MachineLimit::load(home)?;
    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    let spec = plan_add(&reg, req, &machine, &now)?;
    // A directory left by a removal the agent has not finished yet.
    let dir = spec.dir(home);
    if dir.join(REMOVED_MARKER).exists() {
        return Err(format!(
            "node {} is still being removed; try again in a moment",
            spec.id
        ));
    }
    runner::prepare(home, &spec)?;
    reg.nodes.push(spec.clone());
    reg.save(home)?;
    Ok(spec)
}

/// Change a node's size or workers. Its runner restarts on its own.
pub fn patch(home: &Path, id: &str, patch: &NodePatch) -> Result<NodeSpec, String> {
    let _guard = crate::policy::lock(home)?;
    let mut reg = Registry::load(home);
    let machine = MachineLimit::load(home)?;
    let spec = plan_patch(&reg, id, patch, &machine)?;
    for n in reg.nodes.iter_mut().filter(|n| n.id == id) {
        *n = spec.clone();
    }
    reg.save(home)?;
    Ok(spec)
}

/// Unregister a node. Its share goes back to the main node at once; the
/// agent stops it and deletes its directory (and its identity) after.
pub fn remove(home: &Path, id: &str) -> Result<NodeSpec, String> {
    let _guard = crate::policy::lock(home)?;
    let mut reg = Registry::load(home);
    let spec = reg
        .get(id)
        .cloned()
        .ok_or_else(|| format!("no node {id}"))?;
    reg.nodes.retain(|n| n.id != id);
    let dir = spec.dir(home);
    let _ = std::fs::create_dir_all(&dir);
    std::fs::write(
        dir.join(REMOVED_MARKER),
        serde_json::to_vec(&spec).unwrap_or_default(),
    )
    .map_err(|e| format!("{}: {e}", dir.display()))?;
    reg.save(home)?;
    Ok(spec)
}

/// The removed nodes whose directories are still there, from their markers.
pub fn removed(home: &Path) -> Vec<NodeSpec> {
    let Ok(rd) = std::fs::read_dir(nodes_dir(home)) else {
        return Vec::new();
    };
    rd.flatten()
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().into_owned();
            let b = std::fs::read(e.path().join(REMOVED_MARKER)).ok()?;
            let spec: NodeSpec = serde_json::from_slice(&b).ok()?;
            // The marker must describe the directory it sits in.
            (valid_id(&spec.id) && spec.id == name).then_some(spec)
        })
        .collect()
}

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

    fn machine() -> MachineLimit {
        MachineLimit {
            cpu_millis: 5000,
            memory_bytes: 8 * GIB,
            disk_bytes: 50 * GIB,
        }
    }

    fn req(env: Option<&str>, cpu: f64, mem_gb: u64) -> NewNode {
        NewNode {
            id: None,
            environment: env.map(str::to_string),
            environment_name: None,
            workers: None,
            cpu_cores: cpu,
            memory_bytes: mem_gb * GIB,
            disk_bytes: None,
        }
    }

    fn add(reg: &mut Registry, r: &NewNode) -> Result<NodeSpec, String> {
        let n = plan_add(reg, r, &machine(), "2026-11-12T00:00:00Z")?;
        reg.nodes.push(n.clone());
        Ok(n)
    }

    #[test]
    fn nodes_get_their_own_ports_and_never_the_main_nodes() {
        let mut reg = Registry::default();
        let a = add(&mut reg, &req(Some("pytorch"), 1.0, 2)).unwrap();
        let b = add(&mut reg, &req(None, 1.0, 2)).unwrap();
        assert_eq!(
            (a.id.as_str(), a.index, a.broker_port()),
            ("pytorch", 1, 9002)
        );
        assert_eq!((b.id.as_str(), b.index, b.broker_port()), ("jobs", 2, 9004));
        assert_eq!((a.worker_port(0), b.worker_port(1)), (4000, 4041));
        assert_eq!(a.scan_range(), "4000-4011");
        // An environment node needs no worker; a jobs node gets one.
        assert_eq!((a.workers, b.workers), (0, 1));
        // A removed node's index is free again; ids stay unique.
        reg.nodes.remove(0);
        let c = add(&mut reg, &req(None, 0.5, 1)).unwrap();
        assert_eq!((c.id.as_str(), c.index), ("jobs-2", 1));
    }

    #[test]
    fn the_nodes_together_stay_inside_the_owners_limit() {
        let mut reg = Registry::default();
        add(&mut reg, &req(Some("a"), 2.0, 3)).unwrap();
        add(&mut reg, &req(Some("b"), 2.0, 3)).unwrap();
        // 4 of 5 cores are taken: the main node keeps its one, so no more.
        let e = add(&mut reg, &req(Some("c"), 0.5, 1)).unwrap_err();
        assert!(e.contains("not enough CPU"), "{e}");
        assert_eq!(
            reg.reserved(),
            Reserved {
                cpu_millis: 4000,
                memory_bytes: 6 * GIB,
                disk_bytes: 20 * GIB
            }
        );
        // Memory: 6 of 8 GB taken, the main node keeps 2.
        reg.nodes[1].cpu_millis = 500;
        let e = add(&mut reg, &req(Some("c"), 0.5, 1)).unwrap_err();
        assert!(e.contains("not enough memory"), "{e}");
    }

    #[test]
    fn one_node_per_environment_and_at_most_four() {
        let mut reg = Registry::default();
        add(&mut reg, &req(Some("pytorch"), 0.5, 1)).unwrap();
        let e = add(&mut reg, &req(Some("pytorch"), 0.5, 1)).unwrap_err();
        assert!(e.contains("already hosts pytorch"), "{e}");
        for t in ["b", "c", "d"] {
            add(&mut reg, &req(Some(t), 0.5, 1)).unwrap();
        }
        let e = add(&mut reg, &req(Some("e"), 0.5, 1)).unwrap_err();
        assert!(e.contains("already runs 4"), "{e}");
    }

    #[test]
    fn sizes_and_ids_are_checked() {
        let reg = Registry::default();
        let m = machine();
        let at = "t";
        assert!(plan_add(&reg, &req(None, 0.2, 2), &m, at).is_err());
        assert!(plan_add(&reg, &req(None, 1.0, 0), &m, at).is_err());
        let mut r = req(None, 1.0, 2);
        r.workers = Some(0);
        assert!(plan_add(&reg, &r, &m, at)
            .unwrap_err()
            .contains("at least one worker"));
        r.workers = Some(9);
        assert!(plan_add(&reg, &r, &m, at).is_err());
        r.workers = Some(2);
        r.id = Some("Main Node".into());
        assert!(plan_add(&reg, &r, &m, at).is_err());
        r.id = Some("main".into());
        assert!(plan_add(&reg, &r, &m, at).is_err());
        r.id = Some("gpu-box".into());
        assert_eq!(plan_add(&reg, &r, &m, at).unwrap().id, "gpu-box");
        assert_eq!(slug("PyTorch 2.5 (CUDA)"), "pytorch-2-5-cuda");
        assert_eq!(slug("///"), "node");
    }

    #[test]
    fn a_patch_is_checked_against_the_other_nodes_only() {
        let mut reg = Registry::default();
        add(&mut reg, &req(Some("a"), 2.0, 3)).unwrap();
        add(&mut reg, &req(None, 1.0, 2)).unwrap();
        // Growing `a` to 3 cores: 3 + 1 = 4 of 5, fine. To 4: the main node
        // would have none.
        let p = |c: f64| NodePatch {
            cpu_cores: Some(c),
            ..Default::default()
        };
        assert_eq!(
            plan_patch(&reg, "a", &p(3.0), &machine())
                .unwrap()
                .cpu_millis,
            3000
        );
        assert!(plan_patch(&reg, "a", &p(4.0), &machine()).is_err());
        let w = NodePatch {
            workers: Some(0),
            ..Default::default()
        };
        assert!(plan_patch(&reg, "jobs", &w, &machine()).is_err());
        assert_eq!(plan_patch(&reg, "a", &w, &machine()).unwrap().workers, 0);
        assert!(plan_patch(&reg, "nope", &w, &machine()).is_err());
    }

    #[test]
    fn the_main_node_lends_what_the_others_leave() {
        let host = HostResources {
            logical_cpus: 10,
            memory_bytes: Some(16 * GIB),
        };
        let b = Budget::default(); // 50% / 50%
                                   // Nothing reserved: untouched, percentages and all.
        assert_eq!(minus_reserved(b.clone(), &Reserved::default(), &host), b);
        let r = Reserved {
            cpu_millis: 2000,
            memory_bytes: 3 * GIB,
            disk_bytes: 10 * GIB,
        };
        let left = minus_reserved(b.clone(), &r, &host);
        let l = left.total(&host).unwrap();
        assert_eq!((l.cpu_millis, l.memory_bytes), (3000, 5 * GIB));
        assert_eq!(left.disk_bytes, b.disk_bytes - 10 * GIB);
        // Over-reserved (the limit was lowered under its nodes): a floor,
        // never zero and never negative.
        let over = Reserved {
            cpu_millis: 9000,
            memory_bytes: 64 * GIB,
            disk_bytes: 900 * GIB,
        };
        let l = minus_reserved(b, &over, &host).total(&host).unwrap();
        assert!(l.cpu_millis > 0 && l.memory_bytes > 0);
    }

    #[test]
    fn compose_gives_each_worker_its_slice_and_labels() {
        let mut reg = Registry::default();
        let mut r = req(None, 2.0, 4);
        r.workers = Some(2);
        let n = add(&mut reg, &r).unwrap();
        let y = compose_yaml(&n, "abcd1234", "zakuroai/compute:cpu");
        assert!(y.contains("name: zk-node-jobs\n"), "{y}");
        assert!(
            y.contains("container_name: \"zc-share-abcd1234-w1\""),
            "{y}"
        );
        assert!(y.contains("- \"127.0.0.1:4001:4001\""), "{y}");
        // 2 cores / 4 GB over 2 workers.
        assert!(y.contains("cpus: 1\n") || y.contains("cpus: 1.0\n"), "{y}");
        assert!(y.contains(&format!("mem_limit: {}\n", 2 * GIB)), "{y}");
        assert!(y.contains("zakuro.node: \"jobs\""), "{y}");
        assert!(
            y.contains(&format!("zakuro.budget: \"1000m,{}\"", 2 * GIB)),
            "{y}"
        );
        assert!(!y.contains("0.0.0.0"), "never published beyond loopback");
        // An environment node with workers keeps half for the environment.
        let mut e = req(Some("pytorch"), 1.0, 2);
        e.workers = Some(1);
        let n = add(&mut reg, &e).unwrap();
        assert_eq!(n.deploy_slice(), "50%");
        assert!(compose_yaml(&n, "ffff0000", "img").contains(&format!("mem_limit: {}\n", GIB)));
        // And one with none has an empty project and the whole node.
        let mut e = req(Some("jupyter"), 0.5, 1);
        e.workers = Some(0);
        let n = plan_add(&Registry::default(), &e, &machine(), "t").unwrap();
        assert_eq!(n.deploy_slice(), "100%");
        assert!(compose_yaml(&n, "ffff0000", "img").contains("services: {}"));
    }

    #[test]
    fn a_nodes_policy_is_its_share_and_its_binding() {
        let mut reg = Registry::default();
        let env = add(&mut reg, &req(Some("pytorch"), 1.5, 3)).unwrap();
        let mut p = crate::policy::Policy::default();
        apply_policy(&mut p, &env);
        assert_eq!(
            (p.budget.cpu.as_str(), p.budget.disk.as_str()),
            ("1.5", "10G")
        );
        assert_eq!(p.budget.memory, (3 * GIB).to_string());
        assert!(p.workloads.environments && !p.workloads.spaces && !p.workloads.hub_serving);
        p.validate().unwrap();
        let jobs = add(&mut reg, &req(None, 1.0, 2)).unwrap();
        let mut p = crate::policy::Policy::default();
        apply_policy(&mut p, &jobs);
        assert!(!p.workloads.environments && p.workloads.spaces && p.workloads.hub_serving);
        p.validate().unwrap();
    }

    #[test]
    fn the_registry_round_trips_and_a_missing_one_is_empty() {
        let dir = std::env::temp_dir().join(format!("zc-nodes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(Registry::load(&dir), Registry::default());
        let mut reg = Registry::default();
        add(&mut reg, &req(Some("pytorch"), 1.0, 2)).unwrap();
        reg.save(&dir).unwrap();
        let back = Registry::load(&dir);
        assert_eq!(back.nodes, reg.nodes);
        assert_eq!(back.v, 1);
        let _ = std::fs::remove_dir_all(&dir);
    }
}