Skip to main content

hyprstream_pds/placement/
node.rs

1//! `ai.hyprstream.placement.node` — a schedulable node advertised by an account.
2//!
3//! ```json
4//! {
5//!   "lexicon": 1,
6//!   "id": "ai.hyprstream.placement.node",
7//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
8//!     "type": "object",
9//!     "required": ["repo", "labels", "resources", "groups", "createdAt"],
10//!     "properties": {
11//!       "repo":      { "type": "string", "format": "at-uri" },
12//!       "labels":    { "type": "array", "items": { "type": "object",
13//!                        "required": ["key", "value"], "properties": {
14//!                          "key":   { "type": "string" },
15//!                          "value": { "type": "string" } } } },
16//!       "resources": { "type": "array", "items": { "type": "object",
17//!                        "required": ["name", "capacity"], "properties": {
18//!                          "name":     { "type": "string" },
19//!                          "capacity": { "type": "string" } } } },
20//!       "groups":    { "type": "array", "items": { "type": "string", "format": "at-uri" } },
21//!       "createdAt": { "type": "string", "format": "datetime" }
22//!     }
23//! }}}
24//! ```
25//!
26//! `groups` are at-uris of `ai.hyprstream.placement.group` records the node has
27//! consented to be placed within. `resources[].capacity` carries a Kubernetes
28//! quantity string (e.g. `"16"`, `"100m"`, `"8Gi"`).
29
30use anyhow::{bail, ensure, Result};
31
32use super::{map_get_str, validate_at_uri, validate_datetime};
33use crate::cid::Cid;
34use crate::dag_cbor::DagCbor;
35
36/// The NSID of this record type.
37pub const COLLECTION_NSID: &str = "ai.hyprstream.placement.node";
38
39/// A `{key, value}` label pair.
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct Label {
42    pub key: String,
43    pub value: String,
44}
45
46/// A `{name, capacity}` resource advertisement. `capacity` is a k8s-quantity.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct Resource {
49    pub name: String,
50    pub capacity: String,
51}
52
53/// An `ai.hyprstream.placement.node` record.
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct NodeRecord {
56    /// at-uri of the owning repo. `format: "at-uri"`.
57    pub repo: String,
58    /// Free-form `{key, value}` labels.
59    pub labels: Vec<Label>,
60    /// Advertised `{name, capacity}` resources (capacity is a k8s-quantity).
61    pub resources: Vec<Resource>,
62    /// at-uris of consented placement groups. Each is `format: "at-uri"`.
63    pub groups: Vec<String>,
64    /// ISO-8601 UTC datetime. `format: "datetime"`.
65    pub created_at: String,
66}
67
68impl NodeRecord {
69    /// Validate and construct a record.
70    pub fn new(
71        repo: impl Into<String>,
72        labels: Vec<Label>,
73        resources: Vec<Resource>,
74        groups: Vec<String>,
75        created_at: impl Into<String>,
76    ) -> Result<Self> {
77        let repo = repo.into();
78        let created_at = created_at.into();
79        validate_at_uri(&repo)?;
80        for l in &labels {
81            validate_label(l)?;
82        }
83        for r in &resources {
84            validate_resource(r)?;
85        }
86        for g in &groups {
87            validate_at_uri(g)?;
88        }
89        validate_datetime(&created_at)?;
90        Ok(NodeRecord {
91            repo,
92            labels,
93            resources,
94            groups,
95            created_at,
96        })
97    }
98
99    /// Encode to canonical DAG-CBOR bytes (deterministic).
100    pub fn to_dag_cbor(&self) -> Vec<u8> {
101        self.to_value().encode()
102    }
103
104    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
105    pub fn cid(&self) -> Cid {
106        Cid::from_dag_cbor(&self.to_dag_cbor())
107    }
108
109    /// Build the typed [`DagCbor`] value form.
110    pub fn to_value(&self) -> DagCbor {
111        let labels = DagCbor::list(self.labels.iter().map(|l| {
112            DagCbor::str_map([
113                ("key", DagCbor::Text(l.key.clone())),
114                ("value", DagCbor::Text(l.value.clone())),
115            ])
116        }));
117        let resources = DagCbor::list(self.resources.iter().map(|r| {
118            DagCbor::str_map([
119                ("name", DagCbor::Text(r.name.clone())),
120                ("capacity", DagCbor::Text(r.capacity.clone())),
121            ])
122        }));
123        let groups = DagCbor::list(self.groups.iter().map(|g| DagCbor::Text(g.clone())));
124        DagCbor::str_map([
125            ("repo", DagCbor::Text(self.repo.clone())),
126            ("labels", labels),
127            ("resources", resources),
128            ("groups", groups),
129            ("createdAt", DagCbor::Text(self.created_at.clone())),
130        ])
131    }
132
133    /// Decode canonical DAG-CBOR bytes into a record, validating all fields.
134    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
135        let value = DagCbor::decode(bytes)?;
136        Self::from_value(&value)
137    }
138
139    pub fn from_value(value: &DagCbor) -> Result<Self> {
140        let map = value.as_map()?;
141        let repo = map_get_str(value, "repo", COLLECTION_NSID)?.to_owned();
142        let labels = value
143            .get("labels")
144            .ok_or_else(|| anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"labels\""))?
145            .as_list()?
146            .iter()
147            .map(parse_label)
148            .collect::<Result<Vec<_>>>()?;
149        let resources = value
150            .get("resources")
151            .ok_or_else(|| {
152                anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"resources\"")
153            })?
154            .as_list()?
155            .iter()
156            .map(parse_resource)
157            .collect::<Result<Vec<_>>>()?;
158        let groups = value
159            .get("groups")
160            .ok_or_else(|| anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"groups\""))?
161            .as_list()?
162            .iter()
163            .map(|g| Ok(g.as_str()?.to_owned()))
164            .collect::<Result<Vec<_>>>()?;
165        let created_at = map_get_str(value, "createdAt", COLLECTION_NSID)?.to_owned();
166        // Reject unknown extra fields (the lexicon is frozen at 5 fields).
167        for (k, _v) in map {
168            match k.as_str()? {
169                "repo" | "labels" | "resources" | "groups" | "createdAt" => {}
170                other => {
171                    bail!("{COLLECTION_NSID}: unknown field {other:?} (lexicon is 5 fields)")
172                }
173            }
174        }
175        Self::new(repo, labels, resources, groups, created_at)
176    }
177}
178
179fn parse_label(value: &DagCbor) -> Result<Label> {
180    let map = value.as_map()?;
181    let key = map_get_str(value, "key", COLLECTION_NSID)?.to_owned();
182    let val = map_get_str(value, "value", COLLECTION_NSID)?.to_owned();
183    for (k, _v) in map {
184        match k.as_str()? {
185            "key" | "value" => {}
186            other => {
187                bail!("{COLLECTION_NSID}: unknown label field {other:?} (lexicon is 2 fields)")
188            }
189        }
190    }
191    Ok(Label { key, value: val })
192}
193
194fn parse_resource(value: &DagCbor) -> Result<Resource> {
195    let map = value.as_map()?;
196    let name = map_get_str(value, "name", COLLECTION_NSID)?.to_owned();
197    let capacity = map_get_str(value, "capacity", COLLECTION_NSID)?.to_owned();
198    for (k, _v) in map {
199        match k.as_str()? {
200            "name" | "capacity" => {}
201            other => {
202                bail!("{COLLECTION_NSID}: unknown resource field {other:?} (lexicon is 2 fields)")
203            }
204        }
205    }
206    Ok(Resource { name, capacity })
207}
208
209// ── nested-object validators ────────────────────────────────────────────────
210
211fn validate_label(l: &Label) -> Result<()> {
212    ensure!(!l.key.is_empty(), "label key must not be empty");
213    Ok(())
214}
215
216fn validate_resource(r: &Resource) -> Result<()> {
217    ensure!(!r.name.is_empty(), "resource name must not be empty");
218    validate_k8s_quantity(&r.capacity)?;
219    Ok(())
220}
221
222/// A Kubernetes quantity string (e.g. `"16"`, `"100m"`, `"8Gi"`, `"2.5"`). We
223/// do not fully parse the suffix grammar here; we reject the obviously-invalid
224/// forms (empty, whitespace, or a non-numeric leading character).
225fn validate_k8s_quantity(s: &str) -> Result<()> {
226    ensure!(!s.is_empty(), "k8s quantity must not be empty: {s:?}");
227    ensure!(
228        !s.chars().any(char::is_whitespace),
229        "k8s quantity must not contain whitespace: {s:?}"
230    );
231    let first = s.chars().next().unwrap_or(' ');
232    ensure!(
233        first.is_ascii_digit() || first == '.' || first == '+' || first == '-',
234        "k8s quantity must start with a digit/sign/dot: {s:?}"
235    );
236    Ok(())
237}
238
239#[cfg(test)]
240mod tests {
241    #![allow(
242        clippy::unwrap_used,
243        clippy::expect_used,
244        clippy::indexing_slicing,
245        clippy::panic
246    )]
247    use super::*;
248
249    fn sample() -> NodeRecord {
250        NodeRecord::new(
251            "at://did:web:alice.example.com",
252            vec![Label {
253                key: "zone".into(),
254                value: "us-east".into(),
255            }],
256            vec![Resource {
257                name: "nvidia.com/gpu".into(),
258                capacity: "8".into(),
259            }],
260            vec!["at://did:web:alice.example.com/ai.hyprstream.placement.group/3kxy".into()],
261            "2026-06-23T12:34:56.789Z",
262        )
263        .expect("valid sample")
264    }
265
266    #[test]
267    fn record_round_trip_same_cid() {
268        let r = sample();
269        let bytes = r.to_dag_cbor();
270        let back = NodeRecord::from_dag_cbor(&bytes).expect("round-trip");
271        assert_eq!(r, back);
272        assert_eq!(r.cid(), back.cid());
273        assert_eq!(r.to_dag_cbor(), back.to_dag_cbor());
274    }
275
276    #[test]
277    fn record_fields_canonical_order() {
278        let r = sample();
279        let bytes = r.to_dag_cbor();
280        let v = DagCbor::decode(&bytes).expect("decode");
281        let map = v.as_map().expect("map");
282        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
283        // canonical (lexicographic byte) key order.
284        assert_eq!(
285            keys,
286            vec!["createdAt", "groups", "labels", "repo", "resources"]
287        );
288    }
289
290    #[test]
291    fn record_rejects_extra_fields() {
292        let mut extra = sample().to_value();
293        if let DagCbor::Map(ref mut v) = extra {
294            v.push((DagCbor::Text("extra".into()), DagCbor::Unsigned(1)));
295            v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
296        }
297        assert!(NodeRecord::from_value(&extra).is_err());
298    }
299
300    #[test]
301    fn record_rejects_unknown_nested_label_field() {
302        let r = sample();
303        let mut v = r.to_value();
304        if let DagCbor::Map(ref mut pairs) = v {
305            for (k, val) in pairs.iter_mut() {
306                if k.as_str().ok() == Some("labels") {
307                    if let DagCbor::List(items) = val {
308                        if let Some(DagCbor::Map(obj)) = items.first_mut() {
309                            obj.push((DagCbor::Text("zzz".into()), DagCbor::Text("x".into())));
310                        }
311                    }
312                }
313            }
314        }
315        assert!(NodeRecord::from_value(&v).is_err());
316    }
317
318    #[test]
319    fn record_validates_formats() {
320        // Bad repo at-uri.
321        assert!(
322            NodeRecord::new("nope", vec![], vec![], vec![], "2026-06-23T12:34:56.789Z").is_err()
323        );
324        // Bad group at-uri.
325        assert!(NodeRecord::new(
326            "at://did:web:x",
327            vec![],
328            vec![],
329            vec!["not-an-at-uri".into()],
330            "2026-06-23T12:34:56.789Z"
331        )
332        .is_err());
333        // Bad datetime.
334        assert!(NodeRecord::new("at://did:web:x", vec![], vec![], vec![], "2026-06-23").is_err());
335        // Empty label key.
336        assert!(NodeRecord::new(
337            "at://did:web:x",
338            vec![Label {
339                key: "".into(),
340                value: "v".into()
341            }],
342            vec![],
343            vec![],
344            "2026-06-23T12:34:56.789Z"
345        )
346        .is_err());
347        // Bad k8s quantity.
348        assert!(NodeRecord::new(
349            "at://did:web:x",
350            vec![],
351            vec![Resource {
352                name: "cpu".into(),
353                capacity: "lots".into()
354            }],
355            vec![],
356            "2026-06-23T12:34:56.789Z"
357        )
358        .is_err());
359    }
360}