Skip to main content

hyprstream_pds/placement/
group_item.rs

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