Skip to main content

hyprstream_pds/placement/
workload.rs

1//! `ai.hyprstream.placement.workload` — a workload→node placement decision.
2//!
3//! ```json
4//! {
5//!   "lexicon": 1,
6//!   "id": "ai.hyprstream.placement.workload",
7//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
8//!     "type": "object",
9//!     "required": ["repo", "workload", "node", "createdAt"],
10//!     "properties": {
11//!       "repo":      { "type": "string", "format": "at-uri" },
12//!       "workload":  { "type": "string" },
13//!       "node":      { "type": "string" },
14//!       "group":     { "type": "string" },
15//!       "createdAt": { "type": "string", "format": "datetime" }
16//!     }
17//! }}}
18//! ```
19//!
20//! `workload` is a model at-uri or shard id (free-form string). `node` is the
21//! DID of the placed node. `group` is the optional consent group the placement
22//! was made under.
23
24use anyhow::{bail, Result};
25
26use super::{
27    map_get_opt_str, map_get_str, validate_at_uri, validate_datetime, validate_did,
28    validate_nonempty,
29};
30use crate::cid::Cid;
31use crate::dag_cbor::DagCbor;
32
33/// The NSID of this record type.
34pub const COLLECTION_NSID: &str = "ai.hyprstream.placement.workload";
35
36/// An `ai.hyprstream.placement.workload` record.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct WorkloadRecord {
39    /// at-uri of the owning repo. `format: "at-uri"`.
40    pub repo: String,
41    /// The workload identifier: a model at-uri or a shard id.
42    pub workload: String,
43    /// The DID of the node the workload is placed on.
44    pub node: String,
45    /// Optional consent group the placement was made under.
46    pub group: Option<String>,
47    /// ISO-8601 UTC datetime. `format: "datetime"`.
48    pub created_at: String,
49}
50
51impl WorkloadRecord {
52    /// Validate and construct a record.
53    pub fn new(
54        repo: impl Into<String>,
55        workload: impl Into<String>,
56        node: impl Into<String>,
57        group: Option<String>,
58        created_at: impl Into<String>,
59    ) -> Result<Self> {
60        let repo = repo.into();
61        let workload = workload.into();
62        let node = node.into();
63        let created_at = created_at.into();
64        validate_at_uri(&repo)?;
65        validate_nonempty(&workload, "workload")?;
66        validate_did(&node)?;
67        if let Some(g) = &group {
68            validate_nonempty(g, "group")?;
69        }
70        validate_datetime(&created_at)?;
71        Ok(WorkloadRecord {
72            repo,
73            workload,
74            node,
75            group,
76            created_at,
77        })
78    }
79
80    /// Encode to canonical DAG-CBOR bytes (deterministic).
81    pub fn to_dag_cbor(&self) -> Vec<u8> {
82        self.to_value().encode()
83    }
84
85    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
86    pub fn cid(&self) -> Cid {
87        Cid::from_dag_cbor(&self.to_dag_cbor())
88    }
89
90    /// Build the typed [`DagCbor`] value form. The optional `group` field is
91    /// omitted from the map when absent.
92    pub fn to_value(&self) -> DagCbor {
93        let mut pairs: Vec<(&str, DagCbor)> = vec![
94            ("repo", DagCbor::Text(self.repo.clone())),
95            ("workload", DagCbor::Text(self.workload.clone())),
96            ("node", DagCbor::Text(self.node.clone())),
97            ("createdAt", DagCbor::Text(self.created_at.clone())),
98        ];
99        if let Some(group) = &self.group {
100            pairs.push(("group", DagCbor::Text(group.clone())));
101        }
102        DagCbor::str_map(pairs)
103    }
104
105    /// Decode canonical DAG-CBOR bytes into a record, validating all fields.
106    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
107        let value = DagCbor::decode(bytes)?;
108        Self::from_value(&value)
109    }
110
111    pub fn from_value(value: &DagCbor) -> Result<Self> {
112        let map = value.as_map()?;
113        let repo = map_get_str(value, "repo", COLLECTION_NSID)?.to_owned();
114        let workload = map_get_str(value, "workload", COLLECTION_NSID)?.to_owned();
115        let node = map_get_str(value, "node", COLLECTION_NSID)?.to_owned();
116        let group = map_get_opt_str(value, "group")?.map(str::to_owned);
117        let created_at = map_get_str(value, "createdAt", COLLECTION_NSID)?.to_owned();
118        // Reject unknown extra fields (frozen field set: 4 required + 1 optional).
119        for (k, _v) in map {
120            match k.as_str()? {
121                "repo" | "workload" | "node" | "group" | "createdAt" => {}
122                other => {
123                    bail!("{COLLECTION_NSID}: unknown field {other:?} (lexicon is 5 fields)")
124                }
125            }
126        }
127        Self::new(repo, workload, node, group, created_at)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    #![allow(
134        clippy::unwrap_used,
135        clippy::expect_used,
136        clippy::indexing_slicing,
137        clippy::panic
138    )]
139    use super::*;
140
141    fn sample() -> WorkloadRecord {
142        WorkloadRecord::new(
143            "at://did:web:alice.example.com",
144            "at://did:web:alice.example.com/ai.hyprstream.model/3kxy",
145            "did:web:node1.example.com",
146            Some("at://did:web:alice.example.com/ai.hyprstream.placement.group/3kxz".into()),
147            "2026-06-23T12:34:56.789Z",
148        )
149        .expect("valid sample")
150    }
151
152    #[test]
153    fn record_round_trip_same_cid() {
154        let r = sample();
155        let bytes = r.to_dag_cbor();
156        let back = WorkloadRecord::from_dag_cbor(&bytes).expect("round-trip");
157        assert_eq!(r, back);
158        assert_eq!(r.cid(), back.cid());
159        assert_eq!(r.to_dag_cbor(), back.to_dag_cbor());
160    }
161
162    #[test]
163    fn record_optional_group_omitted() {
164        let mut r = sample();
165        r.group = None;
166        let v = r.to_value();
167        assert!(v.get("group").is_none(), "absent group must be omitted");
168        let back = WorkloadRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip");
169        assert_eq!(r, back);
170    }
171
172    #[test]
173    fn record_fields_canonical_order() {
174        let r = sample();
175        let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
176        let map = v.as_map().expect("map");
177        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
178        // canonical (lexicographic byte) key order.
179        assert_eq!(keys, vec!["createdAt", "group", "node", "repo", "workload"]);
180    }
181
182    #[test]
183    fn record_rejects_extra_fields() {
184        let mut extra = sample().to_value();
185        if let DagCbor::Map(ref mut v) = extra {
186            v.push((DagCbor::Text("extra".into()), DagCbor::Unsigned(1)));
187            v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
188        }
189        assert!(WorkloadRecord::from_value(&extra).is_err());
190    }
191
192    #[test]
193    fn record_validates_formats() {
194        // Bad repo at-uri.
195        assert!(
196            WorkloadRecord::new("nope", "w", "did:web:n", None, "2026-06-23T12:34:56.789Z")
197                .is_err()
198        );
199        // Empty workload.
200        assert!(WorkloadRecord::new(
201            "at://did:web:x",
202            "",
203            "did:web:n",
204            None,
205            "2026-06-23T12:34:56.789Z"
206        )
207        .is_err());
208        // Bad node DID.
209        assert!(WorkloadRecord::new(
210            "at://did:web:x",
211            "w",
212            "not-a-did",
213            None,
214            "2026-06-23T12:34:56.789Z"
215        )
216        .is_err());
217        // Empty optional group.
218        assert!(WorkloadRecord::new(
219            "at://did:web:x",
220            "w",
221            "did:web:n",
222            Some("".into()),
223            "2026-06-23T12:34:56.789Z"
224        )
225        .is_err());
226        // Bad datetime.
227        assert!(WorkloadRecord::new("at://did:web:x", "w", "did:web:n", None, "2026").is_err());
228    }
229}