hyprstream_pds/placement/
group_item.rs1use 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
28pub const COLLECTION_NSID: &str = "ai.hyprstream.placement.groupItem";
30
31#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct GroupItemRecord {
34 pub group: String,
36 pub subject: String,
38 pub created_at: String,
40}
41
42impl GroupItemRecord {
43 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 pub fn to_dag_cbor(&self) -> Vec<u8> {
64 self.to_value().encode()
65 }
66
67 pub fn cid(&self) -> Cid {
69 Cid::from_dag_cbor(&self.to_dag_cbor())
70 }
71
72 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 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 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 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 assert!(GroupItemRecord::new("nope", "did:web:n", "2026-06-23T12:34:56.789Z").is_err());
158 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 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}