Skip to main content

icydb_model/
lib.rs

1//! IcyDB application-model authoring and code generation.
2//!
3//! This package owns application declarations, the host-only authoring graph,
4//! explicit application validation and normalization, and lowering into the
5//! public [`icydb_schema`] proposal contract. It is not database authority.
6
7extern crate self as icydb_model;
8
9pub mod application;
10pub mod base;
11pub mod build;
12pub mod error;
13pub mod fragment;
14// Declarations remain available on Wasm, while their whole-graph validation
15// helpers are deliberately host-only work. Usage varies by feature profile,
16// so these Wasm allowances must not require dead code to be present.
17#[cfg_attr(
18    target_arch = "wasm32",
19    allow(
20        dead_code,
21        reason = "Wasm retains declaration nodes while host code owns whole-graph traversal"
22    )
23)]
24pub mod node;
25pub mod normalize;
26#[cfg_attr(
27    target_arch = "wasm32",
28    expect(dead_code, reason = "whole-graph schema validation is host-owned")
29)]
30mod schema_validate;
31mod typed_adapter;
32pub mod types;
33pub mod validate;
34#[cfg_attr(
35    target_arch = "wasm32",
36    allow(
37        dead_code,
38        reason = "Wasm retains declarations while host code owns graph visitation"
39    )
40)]
41mod visit;
42pub mod visitor;
43
44// Maximum length for entity schema identifiers.
45pub const MAX_ENTITY_NAME_LEN: usize = 64;
46
47// Maximum length for field schema identifiers.
48pub const MAX_FIELD_NAME_LEN: usize = 64;
49
50// Maximum length for derived index identifiers.
51pub const MAX_INDEX_NAME_LEN: usize =
52    MAX_ENTITY_NAME_LEN + (MAX_INDEX_FIELDS * (1 + MAX_FIELD_NAME_LEN));
53
54use crate::{build::BuildError, node::NodeError};
55use thiserror::Error as ThisError;
56
57/// Shared schema-building prelude used by validators, macros, and tests.
58pub mod prelude {
59    pub(crate) use crate::build::schema_read;
60    pub use crate::{
61        EntitySource as _, Inner as _, NormalizeAndValidate as _, Path as _, base, canister,
62        entity, enum_, err,
63        error::ErrorTree,
64        list, map, newtype,
65        node::*,
66        normalizer, record,
67        schema::*,
68        set, store, tuple,
69        types::{Cardinality, Primitive},
70        validator,
71        visitor::{
72            Issue, Normalize as _, NormalizeAuto, NormalizeCustom, Normalizer as _, Validate as _,
73            ValidateAuto, ValidateCustom, Validator as _, Visitable as _, VisitorContext,
74        },
75    };
76    pub(crate) use crate::{
77        node::{MacroNode, ValidateNode, VisitableNode},
78        visit::Visitor,
79    };
80
81    pub use serde::{Deserialize, Serialize};
82}
83
84pub use application::NormalizeAndValidate;
85pub use icydb_model_macros::{
86    Add, AddAssign, Deref, DerefMut, Display, Div, DivAssign, Inner, Mul, MulAssign, Neg, Product,
87    Rem, RemAssign, Sub, SubAssign, Sum, canister, entity, enum_, list, map, newtype, normalizer,
88    record, set, store, tuple, validator,
89};
90pub use icydb_schema::MAX_INDEX_FIELDS;
91pub use normalize::normalize;
92#[doc(hidden)]
93pub use typed_adapter::{
94    TypedAdapterContext, TypedEnumDescriptor, TypedEnumSelection, TypedInputValue, TypedNamedType,
95    TypedOutputValue, TypedScalarValue, TypedValueError,
96};
97pub use validate::validate;
98
99/// Fully-qualified path identity for generated application declarations.
100pub trait Path {
101    /// Stable Rust declaration path.
102    const PATH: &'static str;
103}
104
105/// Schema-authored entity source identity emitted for runtime-enabled models.
106///
107/// This is application vocabulary only. It cannot establish accepted-schema
108/// presence, freshness, or authority; runtime APIs resolve the source against
109/// their pinned accepted snapshot.
110pub trait EntitySource {
111    /// Exact authored entity source name.
112    const ENTITY: &'static str;
113}
114
115/// Borrowed and consuming access to one-field application wrappers.
116pub trait Inner<T> {
117    /// Borrow the wrapped value.
118    fn inner(&self) -> &T;
119
120    /// Consume the wrapper and return its value.
121    fn into_inner(self) -> T;
122}
123
124/// Exact public proposal vocabulary consumed by application-model lowering.
125pub mod schema {
126    pub use icydb_schema::*;
127}
128
129/// Dependencies intentionally exposed to generated model code.
130#[doc(hidden)]
131pub mod __reexports {
132
133    #[cfg(not(target_arch = "wasm32"))]
134    pub use ctor;
135    pub use icydb_model_macros;
136    pub use remain;
137    pub use serde;
138}
139
140///
141/// Error
142///
143/// Top-level schema error boundary spanning build-time validation and node
144/// lookup/type errors.
145///
146#[derive(Debug, ThisError)]
147pub enum Error {
148    #[error(transparent)]
149    BuildError(#[from] BuildError),
150
151    #[error(transparent)]
152    NodeError(#[from] NodeError),
153}
154
155//
156// TESTS
157//
158
159#[cfg(test)]
160mod tests {
161    use super::{Error, build::BuildError, error::ErrorTree, node::NodeError};
162
163    #[test]
164    fn build_errors_remain_in_build_boundary() {
165        let schema_error = Error::from(BuildError::Validation(ErrorTree::from(
166            "missing schema relation target",
167        )));
168
169        match schema_error {
170            Error::BuildError(BuildError::Validation(tree)) => {
171                assert!(
172                    tree.messages()
173                        .iter()
174                        .any(|message| message == "missing schema relation target"),
175                    "build validation errors must remain wrapped as build-boundary failures",
176                );
177            }
178            Error::BuildError(BuildError::Graph(error)) => {
179                panic!("unexpected graph error: {error}");
180            }
181            Error::NodeError(_) => {
182                panic!("build validation failures must not be remapped into node-boundary errors");
183            }
184        }
185    }
186
187    #[test]
188    fn node_errors_remain_in_node_boundary() {
189        let schema_error = Error::from(NodeError::PathNotFound("entity.user_id".to_string()));
190
191        match schema_error {
192            Error::NodeError(NodeError::PathNotFound(path)) => {
193                assert_eq!(path, "entity.user_id");
194            }
195            Error::NodeError(NodeError::IncorrectNodeType(path)) => {
196                panic!("unexpected node error kind after conversion for path {path}");
197            }
198            Error::BuildError(_) => {
199                panic!("node errors must not be remapped into build-boundary failures");
200            }
201        }
202    }
203}