icydb-model 0.213.33

IcyDB application-model authoring, validation, and code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::{Error, prelude::*};
use icydb_schema::{ScalarLiteral, SchemaContractError, TypeSourceKey};
use std::{any::Any, collections::BTreeMap};

#[cfg(not(target_arch = "wasm32"))]
use sha2::{Digest, Sha256};

///
/// SchemaNode
///

#[remain::sorted]
#[derive(Clone, Debug, Serialize)]
pub enum SchemaNode {
    Canister(Canister),
    Entity(Entity),
    Enum(Enum),
    List(List),
    Map(Map),
    Newtype(Newtype),
    Normalizer(Normalizer),
    Record(Record),
    Set(Set),
    Store(Store),
    Tuple(Tuple),
    Validator(Validator),
}

impl SchemaNode {
    const fn def(&self) -> &Def {
        match self {
            Self::Canister(n) => n.def(),
            Self::Entity(n) => n.def(),
            Self::Enum(n) => n.def(),
            Self::List(n) => n.def(),
            Self::Map(n) => n.def(),
            Self::Newtype(n) => n.def(),
            Self::Normalizer(n) => n.def(),
            Self::Record(n) => n.def(),
            Self::Set(n) => n.def(),
            Self::Store(n) => n.def(),
            Self::Tuple(n) => n.def(),
            Self::Validator(n) => n.def(),
        }
    }
}

impl MacroNode for SchemaNode {
    fn as_any(&self) -> &dyn Any {
        match self {
            Self::Canister(n) => n.as_any(),
            Self::Entity(n) => n.as_any(),
            Self::Enum(n) => n.as_any(),
            Self::List(n) => n.as_any(),
            Self::Map(n) => n.as_any(),
            Self::Newtype(n) => n.as_any(),
            Self::Normalizer(n) => n.as_any(),
            Self::Record(n) => n.as_any(),
            Self::Set(n) => n.as_any(),
            Self::Store(n) => n.as_any(),
            Self::Tuple(n) => n.as_any(),
            Self::Validator(n) => n.as_any(),
        }
    }
}

impl ValidateNode for SchemaNode {}

impl VisitableNode for SchemaNode {
    fn drive<V: Visitor>(&self, v: &mut V) {
        match self {
            Self::Canister(n) => n.accept(v),
            Self::Entity(n) => n.accept(v),
            Self::Enum(n) => n.accept(v),
            Self::List(n) => n.accept(v),
            Self::Map(n) => n.accept(v),
            Self::Newtype(n) => n.accept(v),
            Self::Normalizer(n) => n.accept(v),
            Self::Record(n) => n.accept(v),
            Self::Set(n) => n.accept(v),
            Self::Store(n) => n.accept(v),
            Self::Tuple(n) => n.accept(v),
            Self::Validator(n) => n.accept(v),
        }
    }
}

///
/// Schema
///

#[derive(Clone, Debug, Serialize)]
pub struct Schema {
    nodes: BTreeMap<String, SchemaNode>,
    #[serde(skip)]
    state: SchemaState,
    #[serde(skip)]
    registration_error: Option<SchemaGraphError>,
}

impl Schema {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            nodes: BTreeMap::new(),
            state: SchemaState::Collecting,
            registration_error: None,
        }
    }

    /// Register one constructor-produced node while the graph is collecting.
    ///
    /// Duplicate and late registration are retained as graph errors rather
    /// than replacing an earlier declaration. [`crate::build::get_schema`]
    /// reports the first retained error before exposing a sealed snapshot.
    pub fn insert_node(&mut self, node: SchemaNode) {
        let path = node.def().path();
        if self.state.is_sealed() {
            self.record_registration_error(SchemaGraphError::LateRegistration(path));
            return;
        }
        if self.nodes.contains_key(path.as_str()) {
            self.record_registration_error(SchemaGraphError::DuplicateRegistration(path));
            return;
        }
        self.nodes.insert(path, node);
    }

    /// Seal the complete graph after whole-graph validation.
    ///
    /// # Errors
    ///
    /// Returns the first duplicate or late-registration failure retained while
    /// constructors populated the graph.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn seal(&mut self) -> Result<SchemaGraphDigest, SchemaGraphError> {
        if let Some(error) = self.registration_error.clone() {
            return Err(error);
        }
        if let SchemaState::Sealed(digest) = self.state {
            return Ok(digest);
        }

        let mut hasher = Sha256::new();
        for (path, node) in &self.nodes {
            hash_bounded_bytes(&mut hasher, path.as_bytes());
            let encoded =
                serde_json::to_vec(node).map_err(|_| SchemaGraphError::SnapshotEncoding)?;
            hash_bounded_bytes(&mut hasher, encoded.as_slice());
        }
        let digest = SchemaGraphDigest(hasher.finalize().into());
        self.state = SchemaState::Sealed(digest);

        Ok(digest)
    }

    /// Return whether whole-graph validation has sealed this graph.
    #[must_use]
    pub const fn is_sealed(&self) -> bool {
        self.state.is_sealed()
    }

    /// Return the immutable digest of a sealed graph.
    #[must_use]
    pub const fn digest(&self) -> Option<SchemaGraphDigest> {
        #[cfg(not(target_arch = "wasm32"))]
        match self.state {
            SchemaState::Collecting => None,
            SchemaState::Sealed(digest) => Some(digest),
        }
        #[cfg(target_arch = "wasm32")]
        {
            None
        }
    }

    fn record_registration_error(&mut self, error: SchemaGraphError) {
        if self.registration_error.is_none() {
            self.registration_error = Some(error);
        }
    }

    // get_node
    #[must_use]
    pub fn get_node<'a>(&'a self, path: &str) -> Option<&'a SchemaNode> {
        self.nodes.get(path)
    }

    // try_get_node
    pub fn try_get_node<'a>(&'a self, path: &str) -> Result<&'a SchemaNode, Error> {
        let node = self
            .get_node(path)
            .ok_or_else(|| NodeError::PathNotFound(path.to_string()))?;

        Ok(node)
    }

    // cast_node
    pub fn cast_node<'a, T: 'static>(&'a self, path: &str) -> Result<&'a T, Error> {
        let node = self.try_get_node(path)?;

        node.as_any()
            .downcast_ref::<T>()
            .ok_or_else(|| NodeError::IncorrectNodeType(path.to_string()).into())
    }

    // check_node_as
    pub(crate) fn check_node_as<T: 'static>(&self, path: &str) -> Result<(), Error> {
        self.cast_node::<T>(path).map(|_| ())
    }

    // get_nodes
    pub fn get_nodes<T: 'static>(&self) -> impl Iterator<Item = (&str, &T)> {
        self.nodes
            .iter()
            .filter_map(|(key, node)| node.as_any().downcast_ref::<T>().map(|n| (key.as_str(), n)))
    }

    // filter_nodes
    // Generic method to filter key, and nodes of any type with a predicate
    pub fn filter_nodes<'a, T: 'static>(
        &'a self,
        predicate: impl Fn(&T) -> bool + 'a,
    ) -> impl Iterator<Item = (&'a str, &'a T)> + 'a {
        self.nodes.iter().filter_map(move |(key, node)| {
            node.as_any()
                .downcast_ref::<T>()
                .filter(|target| predicate(target))
                .map(|target| (key.as_str(), target))
        })
    }

    /// Borrow all schema nodes indexed by path.
    #[must_use]
    pub const fn nodes(&self) -> &BTreeMap<String, SchemaNode> {
        &self.nodes
    }

    /// Resolve one authored unit-enum literal through immutable source keys.
    ///
    /// # Errors
    ///
    /// Returns an invalid-enum-literal error when the path is not an enum, the
    /// variant is absent, or either maintained source key is malformed.
    pub fn enum_unit_literal(
        &self,
        enum_path: &str,
        variant_name: &str,
    ) -> Result<ScalarLiteral, SchemaContractError> {
        let r#enum = self
            .get_node(enum_path)
            .and_then(|node| node.as_any().downcast_ref::<Enum>())
            .ok_or(SchemaContractError::InvalidEnumLiteral)?;
        let variant = r#enum
            .variants()
            .iter()
            .find(|variant| variant.ident() == variant_name && variant.value().is_none())
            .ok_or(SchemaContractError::InvalidEnumLiteral)?;
        Ok(ScalarLiteral::EnumUnit {
            enum_type: TypeSourceKey::try_new(r#enum.source_key())?,
            variant: TypeSourceKey::try_new(variant.source_key())?,
        })
    }
}

impl Default for Schema {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidateNode for Schema {}

impl VisitableNode for Schema {
    fn drive<V: Visitor>(&self, v: &mut V) {
        for node in self.nodes.values() {
            node.accept(v);
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn hash_bounded_bytes(hasher: &mut Sha256, bytes: &[u8]) {
    hasher.update((bytes.len() as u64).to_be_bytes());
    hasher.update(bytes);
}

///
/// SchemaGraphDigest
///
/// Deterministic identity of one validated, sealed host authoring graph.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchemaGraphDigest([u8; 32]);

impl SchemaGraphDigest {
    /// Return the digest bytes.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; 32] {
        self.0
    }
}

///
/// SchemaState
///
/// Construction phase of one host authoring graph.
///

#[derive(Clone, Copy, Debug, Default)]
enum SchemaState {
    #[default]
    Collecting,
    #[cfg(not(target_arch = "wasm32"))]
    Sealed(SchemaGraphDigest),
}

impl SchemaState {
    const fn is_sealed(self) -> bool {
        #[cfg(not(target_arch = "wasm32"))]
        {
            matches!(self, Self::Sealed(_))
        }
        #[cfg(target_arch = "wasm32")]
        {
            false
        }
    }
}

///
/// SchemaGraphError
///
/// Deterministic graph-construction failure retained until sealing.
///

#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
pub enum SchemaGraphError {
    /// A second constructor declared the same complete Rust path.
    #[error("duplicate authoring-graph registration for '{0}'")]
    DuplicateRegistration(String),

    /// A constructor attempted to mutate an already sealed graph.
    #[error("late authoring-graph registration for '{0}'")]
    LateRegistration(String),

    /// The validated graph could not be encoded for deterministic identity.
    #[error("authoring graph could not be encoded for deterministic identity")]
    SnapshotEncoding,
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use crate::node::{Def, Schema, SchemaGraphError, SchemaNode, Validator};

    fn validator(path: &'static str, ident: &'static str) -> SchemaNode {
        SchemaNode::Validator(Validator::new(Def::new(path, ident)))
    }

    #[test]
    fn sealing_is_deterministic_and_idempotent() {
        let mut left = Schema::new();
        left.insert_node(validator("test::beta", "Beta"));
        left.insert_node(validator("test::alpha", "Alpha"));

        let mut right = Schema::new();
        right.insert_node(validator("test::alpha", "Alpha"));
        right.insert_node(validator("test::beta", "Beta"));

        let left_digest = left.seal().expect("left graph should seal");
        let right_digest = right.seal().expect("right graph should seal");

        assert_eq!(left_digest, right_digest);
        assert_eq!(
            left.seal().expect("sealed graph should reuse its digest"),
            left_digest,
        );
    }

    #[test]
    fn sealing_digest_changes_with_graph_content() {
        let mut before = Schema::new();
        before.insert_node(validator("test", "Before"));

        let mut after = Schema::new();
        after.insert_node(validator("test", "After"));

        assert_ne!(
            before.seal().expect("before graph should seal"),
            after.seal().expect("after graph should seal"),
        );
    }

    #[test]
    fn duplicate_registration_fails_without_replacing_the_first_node() {
        let mut schema = Schema::new();
        schema.insert_node(validator("test", "Duplicate"));
        schema.insert_node(validator("test", "Duplicate"));

        assert_eq!(
            schema.seal(),
            Err(SchemaGraphError::DuplicateRegistration(
                "test::Duplicate".to_string(),
            )),
        );
        assert_eq!(schema.nodes().len(), 1);
    }

    #[test]
    fn late_registration_fails_without_mutating_the_snapshot() {
        let mut schema = Schema::new();
        schema.insert_node(validator("test", "BeforeSeal"));
        let digest = schema.seal().expect("initial graph should seal");

        schema.insert_node(validator("test", "AfterSeal"));

        assert_eq!(
            schema.seal(),
            Err(SchemaGraphError::LateRegistration(
                "test::AfterSeal".to_string(),
            )),
        );
        assert_eq!(schema.digest(), Some(digest));
        assert_eq!(schema.nodes().len(), 1);
    }
}