Skip to main content

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#[derive(Debug, Clone, PartialEq)]
78pub enum Ref<T> {
79    /// A reference to a named resource by its canonical URI.
80    Reference(String),
81    /// An embedded value, carried inline.
82    Embedded(T),
83}
84
85impl<T> Ref<T> {
86    /// A reference to a named resource by its canonical URI.
87    pub fn to(uri: impl Into<String>) -> Self {
88        Ref::Reference(uri.into())
89    }
90
91    /// A reference to a named resource by the instance itself — resolved
92    /// through the target's envelope `id`. The target must already carry its
93    /// identity; an embedded (id-less) value cannot be referenced.
94    pub fn to_resource(target: &impl KanonakResource) -> Result<Self, CodecError> {
95        match target.kanonak_node().id.as_deref() {
96            Some(id) if !id.is_empty() => Ok(Ref::Reference(id.to_string())),
97            _ => Err(CodecError::Malformed(
98                "Ref::to_resource requires a resource with a non-empty envelope id — \
99                 to carry the value inline instead, use Ref::embed."
100                    .into(),
101            )),
102        }
103    }
104
105    /// An embedded value, carried inline (derived identity, no `$id`).
106    pub fn embed(value: T) -> Self {
107        Ref::Embedded(value)
108    }
109
110    /// An embedded value with its authored dict-key name (hash-relevant).
111    pub fn embed_named(mut value: T, name: impl Into<String>) -> Self
112    where
113        T: KanonakResource,
114    {
115        value.kanonak_node_mut().name = Some(name.into());
116        Ref::Embedded(value)
117    }
118
119    /// True when this is the reference arm.
120    pub fn is_reference(&self) -> bool {
121        matches!(self, Ref::Reference(_))
122    }
123}
124
125impl<T: Serialize> Serialize for Ref<T> {
126    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127        match self {
128            Ref::Reference(uri) => {
129                let mut map = serializer.serialize_map(Some(1))?;
130                map.serialize_entry("$ref", uri)?;
131                map.end()
132            }
133            Ref::Embedded(value) => value.serialize(serializer),
134        }
135    }
136}
137
138impl<'de, T: DeserializeOwned> Deserialize<'de> for Ref<T> {
139    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
140        let value = Json::deserialize(deserializer)?;
141        if let Some(uri) = value.get("$ref").and_then(|r| r.as_str()) {
142            return Ok(Ref::Reference(uri.to_string()));
143        }
144        serde_json::from_value(value)
145            .map(Ref::Embedded)
146            .map_err(serde::de::Error::custom)
147    }
148}
149
150/// A typed instance's codec node (the dictionary contract). The bridge is
151/// native serde: the instance serializes to its normalized-JSON wire form
152/// (envelope-as-data + [`Ref<T>`] values), and the wire form maps onto the
153/// node contract through the SAME split [`deserialize`] defines — one
154/// contract, not two.
155pub fn to_node<T: Serialize>(typed: &T, schema: &Json) -> Result<Node, CodecError> {
156    let wire = serde_json::to_value(typed)
157        .map_err(|e| CodecError::Malformed(format!("typed value failed to serialize: {}", e)))?;
158    match wire.as_object() {
159        Some(map) => deserialize(map, schema),
160        None => Err(CodecError::Malformed(
161            "a typed instance must serialize to a JSON object (the wire node form)".into(),
162        )),
163    }
164}