1use anyhow::{bail, ensure, Result};
36
37use crate::cid::Cid;
38use crate::dag_cbor::DagCbor;
39use crate::list_record::validate_datetime;
40
41pub const COLLECTION_NSID: &str = "ai.hyprstream.model";
44
45#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct ModelRecord {
51 pub repo: String,
54 pub current_oid: String,
57 pub created_at: String,
60}
61
62impl ModelRecord {
63 pub fn new(
69 repo: impl Into<String>,
70 current_oid: impl Into<String>,
71 created_at: impl Into<String>,
72 ) -> Result<Self> {
73 let repo = repo.into();
74 let current_oid = current_oid.into();
75 let created_at = created_at.into();
76 validate_at_uri(&repo)?;
77 validate_cid_string(¤t_oid)?;
78 validate_datetime(&created_at)?;
79 Ok(ModelRecord {
80 repo,
81 current_oid,
82 created_at,
83 })
84 }
85
86 pub fn to_dag_cbor(&self) -> Vec<u8> {
88 self.to_value().encode()
89 }
90
91 pub fn cid(&self) -> Cid {
93 Cid::from_dag_cbor(&self.to_dag_cbor())
94 }
95
96 pub fn to_value(&self) -> DagCbor {
98 DagCbor::str_map([
99 ("repo", DagCbor::Text(self.repo.clone())),
100 ("currentOid", DagCbor::Text(self.current_oid.clone())),
101 ("createdAt", DagCbor::Text(self.created_at.clone())),
102 ])
103 }
104
105 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")?.to_owned();
115 let current_oid = map_get_str(value, "currentOid")?.to_owned();
116 let created_at = map_get_str(value, "createdAt")?.to_owned();
117 for (k, _v) in map {
119 match k.as_str()? {
120 "repo" | "currentOid" | "createdAt" => {}
121 other => {
122 bail!("ai.hyprstream.model: unknown field {other:?} (lexicon is 3 fields)")
123 }
124 }
125 }
126 Self::new(repo, current_oid, created_at)
127 }
128}
129
130fn map_get_str<'a>(value: &'a DagCbor, key: &str) -> Result<&'a str> {
131 value
132 .get(key)
133 .ok_or_else(|| anyhow::anyhow!("ai.hyprstream.model: missing required field {key:?}"))?
134 .as_str()
135}
136
137fn validate_at_uri(s: &str) -> Result<()> {
140 ensure!(
141 s.starts_with("at://"),
142 "at-uri must start with \"at://\": {s:?}"
143 );
144 let rest = &s[5..];
145 ensure!(!rest.is_empty(), "at-uri must have an authority: {s:?}");
146 ensure!(
149 !rest.chars().any(char::is_whitespace),
150 "at-uri must not contain whitespace: {s:?}"
151 );
152 Ok(())
153}
154
155fn validate_cid_string(s: &str) -> Result<()> {
156 if s.is_empty() {
159 bail!("cid string must be non-empty");
160 }
161 let ok = (s.starts_with('b') && s.len() > 8)
166 || (s.starts_with("z") && s.len() > 8)
167 || (s.starts_with("Qm") && s.len() > 8);
168 ensure!(
169 ok,
170 "cid string must be a CIDv1 (b/z…) or CIDv0 (Qm…): {s:?}"
171 );
172 Ok(())
173}
174
175#[cfg(test)]
176mod tests {
177 #![allow(
178 clippy::unwrap_used,
179 clippy::expect_used,
180 clippy::indexing_slicing,
181 clippy::panic
182 )]
183 use super::*;
184
185 fn sample() -> ModelRecord {
186 ModelRecord::new(
187 "at://did:web:alice.example.com",
188 "bafyreiexampleoid1234567890abcdefghij",
189 "2026-06-23T12:34:56.789Z",
190 )
191 .expect("valid sample")
192 }
193
194 #[test]
195 fn record_round_trip_same_cid() {
196 let r = sample();
197 let bytes = r.to_dag_cbor();
198 let back = ModelRecord::from_dag_cbor(&bytes).expect("round-trip");
199 assert_eq!(r, back);
200 assert_eq!(r.cid(), back.cid());
202 assert_eq!(r.to_dag_cbor(), back.to_dag_cbor());
203 }
204
205 #[test]
206 fn record_fields_canonical_order() {
207 let r = sample();
208 let bytes = r.to_dag_cbor();
209 let v = DagCbor::decode(&bytes).expect("decode");
211 let map = v.as_map().expect("map");
212 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
213 assert_eq!(
214 keys,
215 vec!["createdAt", "currentOid", "repo"],
216 "DAG-CBOR map keys must be pure-lexicographic byte order"
217 );
218 }
219
220 #[test]
221 fn record_current_oid_is_string_not_link() {
222 let r = sample();
223 let v = r.to_value();
224 let current_oid = v.get("currentOid").expect("field present");
225 assert!(
227 matches!(current_oid, DagCbor::Text(_)),
228 "currentOid is a cid-string, not a link"
229 );
230 }
231
232 #[test]
233 fn record_rejects_extra_fields() {
234 let mut extra = sample().to_value();
235 if let DagCbor::Map(ref mut v) = extra {
236 v.push((DagCbor::Text("extra".into()), DagCbor::Unsigned(1)));
237 v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
239 }
240 assert!(
241 ModelRecord::from_value(&extra).is_err(),
242 "extra fields must be rejected"
243 );
244 }
245
246 #[test]
247 fn record_validates_formats() {
248 assert!(ModelRecord::new(
250 "not-an-at-uri",
251 "bafyreiexampleoid1234567890abcdefghij",
252 "2026-06-23T12:34:56.789Z"
253 )
254 .is_err());
255 assert!(ModelRecord::new(
257 "at://did:web:x",
258 "bafyreiexampleoid1234567890abcdefghij",
259 "2026-06-23T12:34:56.789"
260 )
261 .is_err());
262 assert!(ModelRecord::new("at://did:web:x", "x", "2026-06-23T12:34:56.789Z").is_err());
264 }
265
266 #[test]
267 fn record_deterministic_across_rebuild() {
268 let r1 = sample();
270 let r2 = ModelRecord::new(
271 r1.repo.clone(),
272 r1.current_oid.clone(),
273 r1.created_at.clone(),
274 )
275 .expect("rebuild");
276 assert_eq!(
277 r1.to_dag_cbor(),
278 r2.to_dag_cbor(),
279 "record bytes must be deterministic"
280 );
281 assert_eq!(r1.cid(), r2.cid());
282 }
283}