Skip to main content

hyprstream_pds/
record.rs

1//! `ai.hyprstream.model` — the per-account signed-mutable-pointer record.
2//!
3//! The confirmed 3-field lexicon:
4//!
5//! ```json
6//! {
7//!   "lexicon": 1,
8//!   "id": "ai.hyprstream.model",
9//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
10//!     "type": "object",
11//!     "required": ["repo", "currentOid", "createdAt"],
12//!     "properties": {
13//!       "repo":       { "type": "string", "format": "at-uri" },
14//!       "currentOid": { "type": "string", "format": "cid" },
15//!       "createdAt":  { "type": "string", "format": "datetime" }
16//!     }
17//! }}}
18//! ```
19//!
20//! # Encoding
21//!
22//! Records are **DAG-CBOR**. The field order in the encoded map is the canonical
23//! order — **pure lexicographic byte order** (RFC 7049 §4.2.1 "core
24//! determinism", matching atproto's `@atproto/lex-cbor`). For these three keys
25//! that is `createdAt`, `currentOid`, `repo`. (NOT length-first-then-lex; that's
26//! the older RFC 7049 §3.9 form, which atproto rejects.) The encoder handles
27//! this; callers do not need to care.
28//!
29//! `currentOid` is a `format: "cid"` **string** — *not* a CID link. It references
30//! external git content by OID, so it is carried as text and validated as a CID
31//! string at construction time. (If it were a link, DAG-CBOR tag 42 would mean
32//! the referenced block is part of *this* repo's MST — which it isn't; the git
33//! blob lives in the separate git-xet / gittorrent CAS.)
34
35use anyhow::{bail, ensure, Result};
36
37use crate::cid::Cid;
38use crate::dag_cbor::DagCbor;
39use crate::list_record::validate_datetime;
40
41/// The NSID of this record type. The collection portion of an at-uri that
42/// addresses a record (`at://<repo>/<collection>/<rkey>`).
43pub const COLLECTION_NSID: &str = "ai.hyprstream.model";
44
45/// An `ai.hyprstream.model` record.
46///
47/// Construct with [`ModelRecord::new`]; encode/decode via the [`DagCbor`]
48/// conversion impls.
49#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct ModelRecord {
51    /// at-uri of the owning repo, e.g. `at://did:web:alice.example.com`.
52    /// `format: "at-uri"` per the lexicon.
53    pub repo: String,
54    /// The current object ID (git OID) the record points at, encoded as a
55    /// CID string. `format: "cid"`.
56    pub current_oid: String,
57    /// ISO-8601 UTC datetime (`format: "datetime"`), e.g.
58    /// `2026-06-23T12:34:56.000Z`. Lexicon `datetime` requires this exact shape.
59    pub created_at: String,
60}
61
62impl ModelRecord {
63    /// Validate and construct a record.
64    ///
65    /// `current_oid` must be a parseable CIDv1 string (the lexicon's `cid`
66    /// format), and `created_at` must match the atproto `datetime` shape
67    /// (UTC, milliseconds, trailing `Z`).
68    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(&current_oid)?;
78        validate_datetime(&created_at)?;
79        Ok(ModelRecord {
80            repo,
81            current_oid,
82            created_at,
83        })
84    }
85
86    /// Encode to canonical DAG-CBOR bytes (deterministic).
87    pub fn to_dag_cbor(&self) -> Vec<u8> {
88        self.to_value().encode()
89    }
90
91    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
92    pub fn cid(&self) -> Cid {
93        Cid::from_dag_cbor(&self.to_dag_cbor())
94    }
95
96    /// Build the typed [`DagCbor`] value form.
97    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    /// 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        // Required fields.
114        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        // Reject unknown extra fields (the lexicon is frozen at 3 fields).
118        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
137// ── field validators (lexicon formats) ──────────────────────────────────────
138
139fn 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    // Authority is the first path segment; we don't enforce DID-grammar here
147    // (the resolver does), only that it's non-empty and has no whitespace.
148    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    // `format: "cid"` — a CIDv1 string (base32 `b...` form) or a CIDv0
157    // (base58btc `Qm...`). We accept any CIDv1 base and CIDv0.
158    if s.is_empty() {
159        bail!("cid string must be non-empty");
160    }
161    // Best-effort: round-trip through Cid::from_bytes is not possible for a
162    // *string* form without the `cid` crate's multibase decoder. We accept the
163    // base32 `b...` form (our canonical currentOid) and the CIDv0 `Qm...` form,
164    // rejecting obviously-bogus strings.
165    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        // Determinism: same record → same bytes → same CID.
201        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        // Decode raw to confirm key order is pure-lexicographic: createdAt, currentOid, repo.
210        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        // Must be a Text string, not a Link (tag 42).
226        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            // Re-sort to keep decode's invariant happy.
238            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        // Bad at-uri.
249        assert!(ModelRecord::new(
250            "not-an-at-uri",
251            "bafyreiexampleoid1234567890abcdefghij",
252            "2026-06-23T12:34:56.789Z"
253        )
254        .is_err());
255        // Bad datetime (no Z).
256        assert!(ModelRecord::new(
257            "at://did:web:x",
258            "bafyreiexampleoid1234567890abcdefghij",
259            "2026-06-23T12:34:56.789"
260        )
261        .is_err());
262        // Bad cid.
263        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        // Reconstruct from scratch — bytes must be identical.
269        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}