icydb 0.284.3

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Module: lib
//!
//! Responsibility: public facade crate surface and generated-code wiring.
//! Does not own: core execution, storage internals, or schema mutation semantics.
//! Boundary: re-exports stable runtime and generated actor-wiring surfaces.

//! # icydb
//!
//! `icydb` is the **public facade crate** for the IcyDB runtime.
//! It is the recommended dependency for downstream canister projects.
//!
//! This crate exposes:
//! - the stable runtime surface used inside canister actor code,
//! - accepted-schema-bound database request and response types,
//! - and a small set of entry points that wire generated actor code.
//!
//! Low-level execution, storage, and engine internals live in
//! `icydb-core` and are re-exposed selectively through stable facade modules.
//!
//! ## Crate layout
//!
//! - `build` *(host builds)*
//!   Host-side build-script facade for generated actor glue. Downstream
//!   canister `build.rs` files should use this module rather than depending on
//!   lower-level implementation crates directly.
//!
//! - `model`
//!   Application-model declarations, macros, reusable types, validation, and
//!   normalization. Runtime-enabled downstream crates should use this
//!   re-export instead of adding a second IcyDB package dependency.
//!
//! - `traits` / `types` / `value`
//!   Stable runtime building blocks used by generated code.
//!
//! - `metrics` *(internal)*
//!   Runtime metrics internals exposed for generated administration endpoints.
//!
//! - `Error` / `ErrorKind` / `ErrorOrigin`
//!   Shared error types for generated code and runtime boundaries.
//!
//! - `db`
//!   The public database façade: sessions, SQL/dynamic reads, structural
//!   mutations, and accepted-schema-bound typed adapters.
//!
//! Generated SQL endpoints are controller-gated by default. A declaration may
//! instead install one synchronous application read guard; neither form is an
//! anonymous public read endpoint template.
//!
//! The operational lane contract lives in
//! `docs/contracts/READ_ADMISSION.md`.
//! Endpoint migration recipes live in `docs/guides/read-intent.md`.
//!
//! ## Preludes
//!
//! - `prelude`
//!   Opinionated runtime prelude for canister actor code.
//!   Intended to be glob-imported in `lib.rs` to keep endpoints concise.
//!
//! ## Internal boundaries
//!
//! Generated code targets explicit facade surfaces (`traits`, `db`, and
//! `__macro`) instead of a broad internal-export module.

// Generated actor glue resolves this package through its canonical crate name.
extern crate self as icydb;

pub use icydb_core::types::{ParseU256Error, U256};
/// Application-model authoring through the public IcyDB facade.
///
/// Runtime-enabled consumers should normally depend only on `icydb` and use
/// `icydb::model::prelude`. Schema-only tooling may still depend directly on
/// the independently published `icydb-model` package.
pub use icydb_model as model;
pub use icydb_model_macros::{request_execution, test};

/// Scalar values and entity-bound identities for application inputs and outputs.
#[doc(inline)]
pub use icydb_core::types;

pub mod value {
    pub use icydb_core::value::{InputValue, OutputValue, PublicEnumValue, PublicValue, ValueTag};
}

#[doc(hidden)]
#[cfg(feature = "metrics")]
pub mod metrics {
    pub use icydb_core::metrics::{
        ConvergenceMetrics, EntityMetrics, InstructionMetrics, MetricsReport,
        SchemaLifecycleMetrics, metrics_reset_all,
    };

    /// Read the current metrics window and exact bounded journal debt.
    ///
    /// Returns a typed error when the database's committed journal controls
    /// cannot be observed. Query reads do not advance recovery or record work.
    pub fn metrics_report() -> Result<MetricsReport, crate::Error> {
        Ok(icydb_core::metrics::metrics_report()?)
    }
}

// facade modules
#[cfg(not(target_arch = "wasm32"))]
pub mod build {
    //! Host-side build-script facade for generated actor glue.
    //!
    //! This module is the advertised downstream build-script API. Add `icydb`
    //! to `[build-dependencies]`, then call `icydb::build::build_canister!()`
    //! from `build.rs`. Model-graph code generation is owned by `icydb-model`.
    //! This module is host-only and is not part of Wasm runtime builds.

    pub use crate::build_canister;

    /// Emit one generated private actor module for a build script.
    ///
    /// This function is expansion support for [`build_canister!`].
    ///
    /// # Errors
    ///
    /// Returns an environment or filesystem error when Cargo does not provide
    /// `OUT_DIR` or the generated actor cannot be written.
    ///
    /// # Panics
    ///
    /// Panics if model validation fails, the canonical path is not a canister,
    /// or the consuming package's IcyDB dependency cannot be resolved.
    #[doc(hidden)]
    pub fn __emit_canister_for_build_script(
        canister_path: &str,
        build_script: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("cargo:rerun-if-changed={build_script}");
        println!("cargo:rustc-check-cfg=cfg(feature, values(\"test-admin-api\"))");
        let out_dir = std::env::var("OUT_DIR")?;
        let actor_file = std::path::PathBuf::from(out_dir).join("actor.rs");
        let actor = icydb_model::build::generate(canister_path);
        std::fs::write(actor_file, actor)?;

        Ok(())
    }
}
pub mod db;
pub mod guards;
pub mod diagnostic {
    //! Compact diagnostic identity for CLI and canister callers.

    pub use icydb_diagnostic_code::{
        Diagnostic, DiagnosticAggregateKind, DiagnosticBacklogResource, DiagnosticCode,
        DiagnosticComponentKind, DiagnosticConstraintContext, DiagnosticConstraintKind,
        DiagnosticDecodeReason, DiagnosticDetail, DiagnosticExecutionBudgetResource,
        DiagnosticExecutionBudgetScope, DiagnosticExecutionLane, DiagnosticFactSchemaMismatch,
        DiagnosticFactTag, DiagnosticFunctionKind, DiagnosticGroupBudgetResource,
        DiagnosticMutationOperation, DiagnosticOperatorKind, DiagnosticTypeFamily, ErrorClass,
        ErrorCode, ErrorOrigin, MAX_PUBLIC_DIAGNOSTIC_FACTS, MAX_PUBLIC_QUERY_FIELD_BYTES,
        QueryErrorKind, QueryFieldRole, QueryFieldSchemaMismatch, QueryProjectionCode,
        QueryReadAdmissionCode, RuntimeBoundaryCode, RuntimeErrorKind, SchemaDdlAdmissionCode,
        SchemaMigrationCode, SqlFeatureCode, SqlLoweringCode, SqlSurfaceMismatchCode,
        SqlWriteBoundaryCode, pack_u32_pair, unpack_u32_pair,
        validate_known_diagnostic_fact_schema, validate_query_field_schema,
        validate_raw_diagnostic_fact_schema,
    };
}
mod error;
pub mod traits;
pub use error::{
    ConstraintValidationFindingOutput, ConstraintValuePath, ConstraintValuePathComponent,
    DiagnosticFact, Error, ErrorKind, ErrorOrigin, QueryErrorKind, QueryFieldDiagnostic,
    RuntimeErrorKind,
};
pub use guards::{
    ReadAuthorizationContext, ReadAuthorizationDecision, ReadAuthorizationGuard,
    ReadAuthorizationSurface,
};
pub use icydb_diagnostic_code::ErrorCode;

// Macro/runtime wiring surface used by generated code.
// This is intentionally narrow and not semver-stable.
#[doc(hidden)]
pub mod __macro {
    pub use crate::db::{
        TypedEntityDescriptor, TypedFieldDescriptor, TypedFieldType, ensure_default_memory_manager,
        execute_generated_storage_report,
    };
    pub use crate::guards::{authorize_schema_read, authorize_sql_read};
    #[cfg(feature = "sql")]
    pub use icydb_core::db::sql_statement_dispatch;
    pub use icydb_core::db::{
        CompositePrimaryKeyValue, DataStore, DbSession as CoreDbSession, EntityKey, EntityKeyBytes,
        EntityKeyBytesError, IndexStore, JournalTailStore, KeyValueCodec, PrimaryKeyDecode,
        PrimaryKeyEncode, PrimaryKeyEncodeError, PrimaryKeyValue, SchemaStore,
        StoreAllocationIdentities, StoreAllocationIdentity, StoreRegistry,
        StoreRuntimeStorageCapabilities, validate_entity_key_bytes_buffer,
    };
    pub use icydb_core::db::{open_memory, with_selected_commit_memory};
    pub use icydb_core::error::{ErrorClass, ErrorOrigin, InternalError};
    pub use icydb_core::traits::{CanisterKind, Path};
    pub use icydb_core::value::Value;
    pub use icydb_schema::ScalarType;
}

//
// Actor Prelude
// using _ brings traits into scope and avoids name conflicts
//

pub mod wire;

pub mod prelude {
    pub use crate::db::{
        query,
        query::{
            CollectionOperator, CompareOperator, FieldCompareOperator, FieldRef, FilterExpr,
            FilterValue, JunctionOperator, OrderExpr, OrderTerm, SetOperator, StateOperator, asc,
            count, count_by, desc, exists, field, first, last, max, max_by, min, min_by, sum,
        },
    };
    pub use crate::{
        db,
        traits::{EntitySource as _, Inner as _, Path as _},
        types::*,
        value::{InputValue, OutputValue},
    };

    pub use serde::{Deserialize, Serialize};
}

//
// -------------------------- CODE -----------------------------------
//

//
// Consts
//

// Workspace version re-export for downstream tooling/tests.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

//
// Macros
//

/// Generate one canister's private actor module from its authored schema type.
///
/// Resolves the type through its canonical model [`Path`](model::Path), so
/// relative and imported type paths use the same registered identity.
/// Track shared declaration files with Cargo `rerun-if-changed` directives.
///
/// # Panics
///
/// Panics if model validation fails, the type is not a registered canister,
/// or the consuming package's IcyDB dependency cannot be resolved.
#[cfg(not(target_arch = "wasm32"))]
#[macro_export]
macro_rules! build_canister {
    ($canister_ty:ty) => {{
        $crate::build::__emit_canister_for_build_script(
            <$canister_ty as $crate::model::Path>::PATH,
            file!(),
        )
    }};
}

#[doc(hidden)]
#[macro_export]
#[expect(
    clippy::crate_in_macro_def,
    reason = "generated actor bindings must live in the consuming canister crate"
)]
macro_rules! __icydb_start_actor {
    () => {
        #[doc(hidden)]
        struct __IcydbStartRootMarker;

        #[doc(hidden)]
        const fn __icydb_start_root_binding(_: __IcydbStartRootMarker) {}

        const _: fn(__IcydbStartRootMarker) = crate::__icydb_start_root_binding;

        #[allow(
            dead_code,
            reason = "generated actor members are feature-dependent in downstream canisters"
        )]
        mod __icydb_generated {
            #[doc(hidden)]
            pub(crate) const __ICYDB_START_BINDING: () = ();

            include!(concat!(env!("OUT_DIR"), "/actor.rs"));
        }

        #[allow(
            unused_imports,
            reason = "minimal downstream canisters may use only a subset of generated actor conveniences"
        )]
        use __icydb_generated::{db, db_with_request_root, startup_state};
        pub use __icydb_generated::icydb_memory_requests;
    };
}

#[doc(hidden)]
#[cfg(feature = "sql")]
#[macro_export]
macro_rules! __icydb_with_sql_items {
    ($($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(feature = "metrics")]
#[macro_export]
macro_rules! __icydb_with_metrics_items {
    ($($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(not(feature = "metrics"))]
#[macro_export]
macro_rules! __icydb_with_metrics_items {
    ($($item:item)*) => {};
}

#[doc(hidden)]
#[cfg(not(feature = "sql"))]
#[macro_export]
macro_rules! __icydb_with_sql_items {
    ($($item:item)*) => {};
}

#[doc(hidden)]
#[cfg(feature = "migration")]
#[macro_export]
macro_rules! __icydb_with_migration_items {
    ($($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(not(feature = "migration"))]
#[macro_export]
macro_rules! __icydb_with_migration_items {
    ($($item:item)*) => {};
}

#[doc(hidden)]
#[cfg(feature = "sql")]
#[macro_export]
macro_rules! __icydb_with_sql_endpoint {
    ($endpoint:literal; $($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(feature = "metrics")]
#[macro_export]
macro_rules! __icydb_with_metrics_endpoint {
    ($endpoint:literal; $($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(not(feature = "metrics"))]
#[macro_export]
macro_rules! __icydb_with_metrics_endpoint {
    ($endpoint:literal; $($item:item)*) => {
        compile_error!(concat!(
            "endpoint declaration `",
            $endpoint,
            "` requires the `icydb/metrics` Cargo feature"
        ));
    };
}

#[doc(hidden)]
#[cfg(feature = "migration")]
#[macro_export]
macro_rules! __icydb_with_migration_endpoint {
    ($endpoint:literal; $($item:item)*) => { $($item)* };
}

#[doc(hidden)]
#[cfg(not(feature = "migration"))]
#[macro_export]
macro_rules! __icydb_with_migration_endpoint {
    ($endpoint:literal; $($item:item)*) => {
        compile_error!(concat!(
            "endpoint declaration `",
            $endpoint,
            "` requires the `icydb/migration` Cargo feature"
        ));
    };
}

#[doc(hidden)]
#[cfg(not(feature = "sql"))]
#[macro_export]
macro_rules! __icydb_with_sql_endpoint {
    ($endpoint:literal; $($item:item)*) => {
        compile_error!(concat!(
            "endpoint declaration `",
            $endpoint,
            "` requires the `icydb/sql` Cargo feature"
        ));
    };
}

#[doc(hidden)]
#[cfg(feature = "migration")]
#[macro_export]
macro_rules! __icydb_require_migration_capability {
    () => {};
}

#[doc(hidden)]
#[cfg(not(feature = "migration"))]
#[macro_export]
macro_rules! __icydb_require_migration_capability {
    () => {
        compile_error!("source migration declarations require the `icydb/migration` Cargo feature");
    };
}

/// Access the active request's database session.
///
/// Use `db!()` in ordinary generated endpoints and nested helpers. Every call
/// shares the execution counters installed at request entry. Manual IC-CDK,
/// framework, and timer entries establish that boundary with
/// [`request_execution`]; lifecycle callbacks declared by the composed
/// the host adapter's `start!` form receive it automatically.
///
/// `db!(&request_root)` is the explicit low-level integration form for a
/// framework that already owns a request root. Obtain that root from
/// [`db::with_request_execution_root`](crate::db::with_request_execution_root);
/// passing it never creates fresh counters and fails if a different root is
/// already active.
#[macro_export]
#[expect(clippy::crate_in_macro_def)]
macro_rules! db {
    () => {
        crate::db()
    };
    ($request_root:expr) => {
        crate::db_with_request_root($request_root)
    };
}

//
// Helpers
//

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use crate::build;

    struct ModelWrapper(u64);

    impl icydb_model::Inner<u64> for ModelWrapper {
        fn inner(&self) -> &u64 {
            &self.0
        }

        fn into_inner(self) -> u64 {
            self.0
        }
    }

    impl icydb_model::Path for ModelWrapper {
        const PATH: &'static str = "icydb::tests::ModelWrapper";
    }

    #[test]
    fn build_facade_exports_typed_entrypoint() {
        fn assert_model_inner<T: crate::traits::Inner<u64>>() {}

        assert_model_inner::<ModelWrapper>();
        let wrapper = ModelWrapper(7);
        assert_eq!(*crate::traits::Inner::inner(&wrapper), 7);
        assert_eq!(crate::traits::Inner::into_inner(wrapper), 7);

        std::hint::black_box(
            build_facade_macros_resolve as fn() -> Result<(), Box<dyn std::error::Error>>,
        );
    }

    fn build_facade_macros_resolve() -> Result<(), Box<dyn std::error::Error>> {
        build::build_canister!(ModelWrapper)?;

        Ok(())
    }
}