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.
16#[cfg_attr(
17    target_arch = "wasm32",
18    expect(
19        dead_code,
20        reason = "Wasm retains declaration nodes while host code owns whole-graph traversal"
21    )
22)]
23pub mod node;
24pub mod normalize;
25#[cfg_attr(
26    target_arch = "wasm32",
27    expect(dead_code, reason = "whole-graph schema validation is host-owned")
28)]
29mod schema_validate;
30mod typed_adapter;
31pub mod types;
32pub mod validate;
33#[cfg_attr(
34    target_arch = "wasm32",
35    expect(
36        dead_code,
37        reason = "Wasm retains declarations while host code owns graph visitation"
38    )
39)]
40mod visit;
41pub mod visitor;
42
43// Maximum length for entity schema identifiers.
44pub const MAX_ENTITY_NAME_LEN: usize = 64;
45
46// Maximum length for field schema identifiers.
47pub const MAX_FIELD_NAME_LEN: usize = 64;
48
49// Maximum number of fields allowed in a derived index.
50pub const MAX_INDEX_FIELDS: usize = 4;
51
52// Maximum length for derived index identifiers.
53pub const MAX_INDEX_NAME_LEN: usize =
54    MAX_ENTITY_NAME_LEN + (MAX_INDEX_FIELDS * (1 + MAX_FIELD_NAME_LEN));
55
56use crate::{build::BuildError, node::NodeError};
57use thiserror::Error as ThisError;
58
59/// Shared schema-building prelude used by validators, macros, and tests.
60pub mod prelude {
61    pub(crate) use crate::build::schema_read;
62    pub use crate::{
63        Inner as _, NormalizeAndValidate as _, Path as _, base, canister, entity, enum_, err,
64        error::ErrorTree,
65        list, map, newtype,
66        node::*,
67        normalizer, record,
68        schema::*,
69        set, store, tuple,
70        types::{Cardinality, Primitive},
71        validator,
72        visitor::{
73            Issue, Normalize as _, NormalizeAuto, NormalizeCustom, Normalizer as _, Validate as _,
74            ValidateAuto, ValidateCustom, Validator as _, Visitable as _, VisitorContext,
75        },
76    };
77    pub(crate) use crate::{
78        node::{MacroNode, ValidateNode, VisitableNode},
79        visit::Visitor,
80    };
81    pub use candid::CandidType;
82    pub use serde::{Deserialize, Serialize};
83}
84
85pub use application::NormalizeAndValidate;
86pub use icydb_model_macros::{
87    Add, AddAssign, Deref, DerefMut, Display, Div, DivAssign, Inner, Mul, MulAssign, Rem, Sub,
88    SubAssign, Sum, canister, entity, enum_, list, map, newtype, normalizer, record, set, store,
89    tuple, validator,
90};
91pub use normalize::normalize;
92#[doc(hidden)]
93pub use typed_adapter::{
94    TypedAdapterContext, TypedEnumOutput, TypedInputValue, TypedNamedType, TypedOutputValue,
95    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/// Borrowed and consuming access to one-field application wrappers.
106pub trait Inner<T> {
107    /// Borrow the wrapped value.
108    fn inner(&self) -> &T;
109
110    /// Consume the wrapper and return its value.
111    fn into_inner(self) -> T;
112}
113
114/// Exact public proposal vocabulary consumed by application-model lowering.
115pub mod schema {
116    pub use icydb_schema::*;
117}
118
119/// Dependencies intentionally exposed to generated model code.
120#[doc(hidden)]
121pub mod __reexports {
122    pub use candid;
123    #[cfg(not(target_arch = "wasm32"))]
124    pub use ctor;
125    pub use icydb_model_macros;
126    pub use remain;
127    pub use serde;
128}
129
130///
131/// Error
132///
133/// Top-level schema error boundary spanning build-time validation and node
134/// lookup/type errors.
135///
136#[derive(Debug, ThisError)]
137pub enum Error {
138    #[error(transparent)]
139    BuildError(#[from] BuildError),
140
141    #[error(transparent)]
142    NodeError(#[from] NodeError),
143}
144
145//
146// TESTS
147//
148
149#[cfg(test)]
150mod tests {
151    use super::{Error, build::BuildError, error::ErrorTree, node::NodeError};
152
153    #[test]
154    fn build_errors_remain_in_build_boundary() {
155        let schema_error = Error::from(BuildError::Validation(ErrorTree::from(
156            "missing schema relation target",
157        )));
158
159        match schema_error {
160            Error::BuildError(BuildError::Validation(tree)) => {
161                assert!(
162                    tree.messages()
163                        .iter()
164                        .any(|message| message == "missing schema relation target"),
165                    "build validation errors must remain wrapped as build-boundary failures",
166                );
167            }
168            Error::BuildError(BuildError::Graph(error)) => {
169                panic!("unexpected graph error: {error}");
170            }
171            Error::NodeError(_) => {
172                panic!("build validation failures must not be remapped into node-boundary errors");
173            }
174        }
175    }
176
177    #[test]
178    fn node_errors_remain_in_node_boundary() {
179        let schema_error = Error::from(NodeError::PathNotFound("entity.user_id".to_string()));
180
181        match schema_error {
182            Error::NodeError(NodeError::PathNotFound(path)) => {
183                assert_eq!(path, "entity.user_id");
184            }
185            Error::NodeError(NodeError::IncorrectNodeType(path)) => {
186                panic!("unexpected node error kind after conversion for path {path}");
187            }
188            Error::BuildError(_) => {
189                panic!("node errors must not be remapped into build-boundary failures");
190            }
191        }
192    }
193}