hyprstream_pds/placement/mod.rs
1//! `ai.hyprstream.placement.*` — the P1 placement-directory lexicons.
2//!
3//! Four DAG-CBOR record types form the consent-scoped placement directory that
4//! sits alongside [`crate::record::ModelRecord`] (`ai.hyprstream.model`):
5//!
6//! - [`node::NodeRecord`] (`ai.hyprstream.placement.node`) — a schedulable node
7//! advertised by an account: its labels, capacities, and group consents.
8//! - [`workload::WorkloadRecord`] (`ai.hyprstream.placement.workload`) — a
9//! workload→node placement decision.
10//! - [`group::GroupRecord`] (`ai.hyprstream.placement.group`) — an atproto *list*
11//! record naming a consent group.
12//! - [`group_item::GroupItemRecord`] (`ai.hyprstream.placement.groupItem`) — an
13//! atproto *listitem* record adding a node (subject) to a group.
14//!
15//! # Encoding
16//!
17//! Like `ai.hyprstream.model`, every record is **DAG-CBOR** with canonical
18//! map-key order — **pure lexicographic byte order** (RFC 7049 §4.2.1 "core
19//! determinism", not length-first). The encoder applies that ordering, so
20//! callers construct fields in any order. Each record has a frozen
21//! field set: decoding rejects unknown fields. Optional fields are *omitted*
22//! from the encoded map when absent (never encoded as `null`).
23//!
24//! All format-bearing fields are validated at construction time, mirroring
25//! `record.rs`: `at-uri` fields must start with `at://`, `did` fields must start
26//! with `did:` (both `did:web` and `did:key` are accepted), and `datetime`
27//! fields must match the atproto ISO-8601 shape (UTC, milliseconds, trailing
28//! `Z`).
29
30use anyhow::{ensure, Result};
31
32use crate::dag_cbor::DagCbor;
33
34pub mod group;
35pub mod group_item;
36pub mod node;
37pub mod workload;
38
39pub use group::GroupRecord;
40pub use group_item::GroupItemRecord;
41pub use node::NodeRecord;
42pub use workload::WorkloadRecord;
43
44// ── shared field accessors ──────────────────────────────────────────────────
45
46/// Read a required string field, attributing errors to `nsid`.
47pub(crate) fn map_get_str<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a str> {
48 value
49 .get(key)
50 .ok_or_else(|| anyhow::anyhow!("{nsid}: missing required field {key:?}"))?
51 .as_str()
52}
53
54/// Read an optional string field. Returns `None` when the field is omitted; an
55/// error if it is present but not a text string.
56pub(crate) fn map_get_opt_str<'a>(value: &'a DagCbor, key: &str) -> Result<Option<&'a str>> {
57 match value.get(key) {
58 None => Ok(None),
59 Some(v) => Ok(Some(v.as_str()?)),
60 }
61}
62
63// ── field validators (lexicon formats) ──────────────────────────────────────
64
65/// `format: "at-uri"` — must start with `at://` and carry a non-empty,
66/// whitespace-free authority. (DID grammar is enforced by the resolver.)
67pub(crate) fn validate_at_uri(s: &str) -> Result<()> {
68 ensure!(
69 s.starts_with("at://"),
70 "at-uri must start with \"at://\": {s:?}"
71 );
72 let rest = &s[5..];
73 ensure!(!rest.is_empty(), "at-uri must have an authority: {s:?}");
74 ensure!(
75 !rest.chars().any(char::is_whitespace),
76 "at-uri must not contain whitespace: {s:?}"
77 );
78 Ok(())
79}
80
81/// A DID string — must start with `did:` and carry a non-empty, whitespace-free
82/// method-specific identifier. Both `did:web:…` and `did:key:…` are accepted.
83pub(crate) fn validate_did(s: &str) -> Result<()> {
84 ensure!(s.starts_with("did:"), "did must start with \"did:\": {s:?}");
85 let rest = &s[4..];
86 ensure!(!rest.is_empty(), "did must have a method: {s:?}");
87 ensure!(
88 !rest.chars().any(char::is_whitespace),
89 "did must not contain whitespace: {s:?}"
90 );
91 // method:identifier — both segments non-empty.
92 let mut parts = rest.splitn(2, ':');
93 let method = parts.next().unwrap_or("");
94 let id = parts.next().unwrap_or("");
95 ensure!(
96 !method.is_empty() && !id.is_empty(),
97 "did must be \"did:<method>:<id>\": {s:?}"
98 );
99 Ok(())
100}
101
102/// `format: "datetime"` — atproto ISO-8601 UTC, millisecond precision, `Z`.
103pub(crate) fn validate_datetime(s: &str) -> Result<()> {
104 ensure!(s.ends_with('Z'), "datetime must end with 'Z' (UTC): {s:?}");
105 let pre = &s[..s.len() - 1];
106 ensure!(pre.len() >= 20, "datetime too short: {s:?}");
107 let bytes = pre.as_bytes();
108 ensure!(
109 bytes[4] == b'-'
110 && bytes[7] == b'-'
111 && bytes[10] == b'T'
112 && bytes[13] == b':'
113 && bytes[16] == b':',
114 "datetime must be ISO-8601 (YYYY-MM-DDTHH:MM:SS): {s:?}"
115 );
116 ensure!(
117 bytes.get(19) == Some(&b'.'),
118 "datetime must have millisecond precision (.mmm): {s:?}"
119 );
120 Ok(())
121}
122
123/// A required free-form string that must not be empty (`field` names it for the
124/// error message).
125pub(crate) fn validate_nonempty(s: &str, field: &str) -> Result<()> {
126 ensure!(!s.is_empty(), "{field} must not be empty");
127 Ok(())
128}