Skip to main content

hyprstream_pds/placement/
group.rs

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