kanonak_codec/typed.rs
1//! The typed SDK-facing surface (0.3.0): the `$`-envelope as data, the explicit
2//! reference-or-embedded union, and the serde bridge from a typed model to the
3//! node contract. A generated struct composes [`KanonakNode`] via
4//! `#[serde(flatten)]`, types its object properties as [`Ref<T>`], and binds
5//! through [`to_node`] — native serde, no reflection, one contract with the
6//! dictionary path.
7
8use crate::{deserialize, CodecError, Node};
9use serde::de::DeserializeOwned;
10use serde::ser::SerializeMap;
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value as Json};
13
14/// The `$`-envelope as data — composed into a generated struct via
15/// `#[serde(flatten)]`, so an instance carries its own identity and serializes
16/// straight to the normalized-JSON wire form. `extra` holds open-world
17/// assertions outside the type-model, keyed by predicate URI; being the
18/// innermost flatten map, it also collects unknown wire fields on deserialize.
19#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
20pub struct KanonakNode {
21 /// The resource's canonical URI. Required to form a subject.
22 #[serde(rename = "$id", skip_serializing_if = "Option::is_none", default)]
23 pub id: Option<String>,
24
25 /// The durable class URI — the value of the synthesized type triple.
26 #[serde(rename = "$type", skip_serializing_if = "Option::is_none", default)]
27 pub type_uri: Option<String>,
28
29 /// A multi-typed node's FULL type set (0.4.0, runtime#10) — present only
30 /// when the node carries more than one type statement. Sorted by UTF-8
31 /// bytes, at least two members, no duplicates, `$type` a member; each
32 /// member emits one type statement in canonical form. Exposed ONLY as the
33 /// `$types` envelope — deliberately no unprefixed `types` accessor, because
34 /// an ontology can model a property literally named `types`; the `$` prefix
35 /// exists to avoid exactly that collision.
36 #[serde(rename = "$types", skip_serializing_if = "Option::is_none", default)]
37 pub types: Option<Vec<String>>,
38
39 /// An embedded value's authored dict-key — HASH-RELEVANT (serialized into
40 /// the canonical form). Only meaningful when the instance is used as an
41 /// embedded value; `None` for subjects.
42 #[serde(rename = "$name", skip_serializing_if = "Option::is_none", default)]
43 pub name: Option<String>,
44
45 /// Package provenance on read; ignored if echoed back on write.
46 #[serde(
47 rename = "$contentHash",
48 skip_serializing_if = "Option::is_none",
49 default
50 )]
51 pub content_hash: Option<String>,
52
53 /// Package provenance on read; ignored if echoed back on write.
54 #[serde(rename = "$version", skip_serializing_if = "Option::is_none", default)]
55 pub version: Option<String>,
56
57 /// Open-world assertions outside the type-model, keyed by predicate URI.
58 /// Rides the wire as sibling fields (flatten semantics).
59 #[serde(flatten)]
60 pub extra: Map<String, Json>,
61}
62
63/// Implemented by generated typed structs (over their flattened
64/// [`KanonakNode`]) so the runtime can read/write an instance's envelope —
65/// what lets [`Ref::to_resource`] resolve identity and
66/// [`Ref::embed_named`] carry the authored dict-key.
67pub trait KanonakResource {
68 fn kanonak_node(&self) -> &KanonakNode;
69 fn kanonak_node_mut(&mut self) -> &mut KanonakNode;
70}
71
72/// An object property's value: EXACTLY ONE of a reference to a named resource
73/// (its canonical URI) or an embedded node (the value itself, carried inline —
74/// derived identity, no `$id`). The typed twin of the wire form's
75/// `{"$ref": uri}` vs embedded-node distinction; the choice between the arms
76/// is authorial and hash-relevant, so it is explicit here, never inferred.
77///
78/// The embedded payload is BOXED (0.6.0, runtime#27). A single-valued
79/// property ranging over its own class — a parent/child hierarchy, the most
80/// ordinary shape an ontology declares — makes `struct Objective { supports:
81/// Option<Ref<Objective>> }`, which has infinite size if the payload is
82/// inline (E0072) and so cannot be generated. The wire form never had that
83/// limit; `Box` is the indirection Rust needs to match it. Construct with
84/// [`Ref::embed`] / [`Ref::embed_named`] and read with [`Ref::value`] /
85/// [`Ref::uri`] and the box is invisible; only a direct `Ref::Embedded(x)`
86/// pattern sees it (`Ref::Embedded(b) => &**b`).
87#[derive(Debug, Clone, PartialEq)]
88pub enum Ref<T> {
89 /// A reference to a named resource by its canonical URI.
90 Reference(String),
91 /// An embedded value, carried inline (boxed — see the type's docs).
92 Embedded(Box<T>),
93}
94
95impl<T> Ref<T> {
96 /// A reference to a named resource by its canonical URI.
97 pub fn to(uri: impl Into<String>) -> Self {
98 Ref::Reference(uri.into())
99 }
100
101 /// A reference to a named resource by the instance itself — resolved
102 /// through the target's envelope `id`. The target must already carry its
103 /// identity; an embedded (id-less) value cannot be referenced.
104 pub fn to_resource(target: &impl KanonakResource) -> Result<Self, CodecError> {
105 match target.kanonak_node().id.as_deref() {
106 Some(id) if !id.is_empty() => Ok(Ref::Reference(id.to_string())),
107 _ => Err(CodecError::Malformed(
108 "Ref::to_resource requires a resource with a non-empty envelope id — \
109 to carry the value inline instead, use Ref::embed."
110 .into(),
111 )),
112 }
113 }
114
115 /// An embedded value, carried inline (derived identity, no `$id`).
116 pub fn embed(value: T) -> Self {
117 Ref::Embedded(Box::new(value))
118 }
119
120 /// An embedded value with its authored dict-key name (hash-relevant).
121 pub fn embed_named(mut value: T, name: impl Into<String>) -> Self
122 where
123 T: KanonakResource,
124 {
125 value.kanonak_node_mut().name = Some(name.into());
126 Ref::Embedded(Box::new(value))
127 }
128
129 /// True when this is the reference arm.
130 pub fn is_reference(&self) -> bool {
131 matches!(self, Ref::Reference(_))
132 }
133
134 /// The referenced resource's canonical URI — the reference arm (else `None`).
135 pub fn uri(&self) -> Option<&str> {
136 match self {
137 Ref::Reference(uri) => Some(uri),
138 Ref::Embedded(_) => None,
139 }
140 }
141
142 /// The embedded value — the embedded arm (else `None`).
143 pub fn value(&self) -> Option<&T> {
144 match self {
145 Ref::Embedded(value) => Some(value),
146 Ref::Reference(_) => None,
147 }
148 }
149
150 /// The embedded value, mutably — the embedded arm (else `None`).
151 pub fn value_mut(&mut self) -> Option<&mut T> {
152 match self {
153 Ref::Embedded(value) => Some(value),
154 Ref::Reference(_) => None,
155 }
156 }
157
158 /// Consume the embedded arm, returning its value (else `None`).
159 pub fn into_value(self) -> Option<T> {
160 match self {
161 Ref::Embedded(value) => Some(*value),
162 Ref::Reference(_) => None,
163 }
164 }
165}
166
167impl<T: Serialize> Serialize for Ref<T> {
168 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
169 match self {
170 Ref::Reference(uri) => {
171 let mut map = serializer.serialize_map(Some(1))?;
172 map.serialize_entry("$ref", uri)?;
173 map.end()
174 }
175 Ref::Embedded(value) => value.serialize(serializer),
176 }
177 }
178}
179
180impl<'de, T: DeserializeOwned> Deserialize<'de> for Ref<T> {
181 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
182 let value = Json::deserialize(deserializer)?;
183 if let Some(uri) = value.get("$ref").and_then(|r| r.as_str()) {
184 return Ok(Ref::Reference(uri.to_string()));
185 }
186 serde_json::from_value(value)
187 .map(|v| Ref::Embedded(Box::new(v)))
188 .map_err(serde::de::Error::custom)
189 }
190}
191
192/// A typed instance's codec node (the dictionary contract). The bridge is
193/// native serde: the instance serializes to its normalized-JSON wire form
194/// (envelope-as-data + [`Ref<T>`] values), and the wire form maps onto the
195/// node contract through the SAME split [`deserialize`] defines — one
196/// contract, not two.
197pub fn to_node<T: Serialize>(typed: &T, schema: &Json) -> Result<Node, CodecError> {
198 let wire = serde_json::to_value(typed)
199 .map_err(|e| CodecError::Malformed(format!("typed value failed to serialize: {}", e)))?;
200 match wire.as_object() {
201 Some(map) => deserialize(map, schema),
202 None => Err(CodecError::Malformed(
203 "a typed instance must serialize to a JSON object (the wire node form)".into(),
204 )),
205 }
206}