Skip to main content

ic_db/
lib.rs

1#![forbid(unsafe_code)]
2//! Experimental IC database: compiled schemas and synchronous bounded records.
3//! Schema modules can import the declaration attributes and value types from
4//! [`design::prelude`].
5//!
6//! This M1 slice supports 8/16/32/64/128-bit integers, U256, Ulid, Date, Timestamp, Duration, Decimal,
7//! finite Float32/Float64, Bool, Principal, Account/Subaccount and bounded Text/Blob, with optional
8//! values. Named records and unit/payload enums support bounded recursion via explicit
9//! indirection and ordered lists; traversals share byte, depth, structured-value
10//! and total collection-item limits. Sets/maps use strict scalar/unit-enum key order.
11//! Secondary indexes admit integers, Ulid, Date, Timestamp, Duration, Decimal, finite floats,
12//! Account/Subaccount, Principal, Bool, Text, Blob and unit enums, including optional values; primary keys
13//! require non-optional integer, U256, Ulid, Principal, Account or Subaccount fields. References use
14//! the target’s exact key type;
15//! absence has no target, while every present target must survive the batch.
16//! Atomicity relies on the enclosing IC message: after persistent mutation starts,
17//! supplier failures trap. A later application trap also rolls back the batch.
18//! Native callers must discard their runtime after a mutation panic. No SQL,
19//! endpoint exports, automatic migration or production compatibility is promised.
20//!
21//! Payload enums cannot become index keys, even when a row selects a unit variant:
22//! ```compile_fail
23//! use ic_db::design::prelude::*;
24//! #[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
25//! struct State {}
26//! #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(field="state"), fields(
27//!     field(name="id", value(item(prim="Nat64"))),
28//!     field(name="state", value(opt, item(is="State")))
29//! ))]
30//! struct Row {}
31//! ```
32//! Payload enums also lack the generated ordering required by sets/maps:
33//! ```compile_fail
34//! use ic_db::design::prelude::*;
35//! #[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
36//! struct State {}
37//! #[set(item(is="State"), max_items=3)]
38//! struct States {}
39//! ```
40
41#[cfg(feature = "logging")]
42pub mod logging;
43#[cfg(feature = "metrics")]
44pub mod metrics;
45
46// Wrap complete operation results, including early admission refusals. With
47// metrics disabled the original body executes directly.
48#[cfg(feature = "metrics")]
49macro_rules! observe_metrics {
50    ($kind:ident, $body:block) => {
51        crate::metrics::$kind(|| $body)
52    };
53}
54#[cfg(not(feature = "metrics"))]
55macro_rules! observe_metrics {
56    ($kind:ident, $body:block) => {
57        $body
58    };
59}
60
61// Both observers share the public terminal boundary. Early returns and `?`
62// inside the operation must reach enabled observers exactly once.
63macro_rules! observe {
64    ($kind:ident, $body:block) => {{
65        #[cfg(feature = "logging")]
66        {
67            crate::logging::observe(concat!("ic-db.", stringify!($kind)), || {
68                observe_metrics!($kind, $body)
69            })
70        }
71        #[cfg(not(feature = "logging"))]
72        {
73            observe_metrics!($kind, $body)
74        }
75    }};
76}
77
78mod canister_session;
79mod clock;
80#[doc(hidden)]
81mod codec;
82mod date;
83mod decimal;
84mod defaults;
85mod float;
86mod key;
87mod managed;
88mod primary;
89mod schema;
90mod session;
91mod store;
92mod store_key;
93mod time;
94mod types;
95mod ulid;
96
97#[cfg(all(feature = "build", not(target_arch = "wasm32")))]
98mod build;
99
100#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
101pub mod testing;
102
103pub use canister_session::{CanisterSession, MountedStore, StoreBatch};
104pub use date::Date;
105pub use decimal::{Decimal, ParseDecimalError};
106pub use defaults::{InsertInput, LiteralDefault};
107/// Exact unsigned 256-bit integer. IC DB owns its durable and index encodings.
108pub use ethnum::U256;
109pub use float::{Float32, Float64};
110pub use ic_db_macros::{canister, entity, enum_, list, map, newtype, record, set, store};
111pub use ic_platform_types::{Account, Principal, Subaccount};
112pub use key::IndexValue;
113pub use managed::ManagedTimestamp;
114pub use primary::PrimaryKey;
115pub use schema::{EntitySchema, FieldSchema, FieldType, IndexSchema, ReferenceSchema, Schema};
116pub use session::{DatabaseSession, QuerySession, UniqueKey};
117pub use store::{
118    Aggregate, Batch, Comparison, CopyStatus, CopyStep, GroupCount, GroupCursor, GroupOrder,
119    GroupPage, GroupValue, JobHandle, JobOutcome, JobStep, Page, QueryCursor, QueryOperand,
120    QueryPage, SchemaTransition, SortDirection,
121};
122pub use store_key::MAX_INDEX_KEY_BYTES;
123pub use time::{Duration, TimeParseError, Timestamp};
124pub use types::{TypeBody, TypeLink, TypeSchema, Value, ValueSchema, VariantSchema};
125pub use ulid::{
126    SeededUlidGenerator, Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, UlidParseError,
127};
128
129#[doc(hidden)]
130#[cfg(any(not(feature = "build"), target_arch = "wasm32"))]
131#[macro_export]
132macro_rules! __register_schema {
133    ($($declaration:tt)*) => {};
134}
135
136/// Include the schema assembly generated by this package’s build script.
137/// Invoke once at the crate root alongside the declarations compiled by
138/// `ic_db::build_schema!`. Consumers import the resulting types from that crate.
139#[macro_export]
140macro_rules! include_schema {
141    () => {
142        ::core::include!(::core::concat!(::core::env!("OUT_DIR"), "/schema.rs"));
143    };
144}
145
146/// Logical database owner. Deployment and memory grants belong to the host.
147pub trait Canister {
148    #[doc(hidden)]
149    const DECLARATION: &'static str;
150}
151
152/// Logical store and the stable allocation it uses within its canister.
153pub trait Store {
154    /// Canister declaring this allocation.
155    type Canister: Canister;
156    /// IC Storage stable allocation key.
157    const KEY: &'static str;
158    #[doc(hidden)]
159    const DECLARATION: &'static str;
160}
161
162/// Host-facing assembly generated in the schema owner's library.
163pub trait CompiledCanister: Canister {
164    /// Stores owned by this canister, in stable key order.
165    const STORES: &'static [CompiledStore];
166}
167
168/// Validated schema and its stable allocation key.
169pub struct CompiledStore {
170    /// Key used to create and reopen the allocation.
171    pub key: &'static str,
172    /// Obtain the admitted schema for this allocation.
173    pub schema: fn() -> Schema,
174}
175
176/// Owned binary bytes. The database codec enforces authored limits and row bounds.
177pub type Blob = Vec<u8>;
178
179/// Admitted database owning an exclusive lease on a named IC Storage allocation.
180pub type Database = store::Database<ic_storage::DefaultMemoryImpl>;
181/// Fluent query over an entity in the admitted database.
182pub type Query<'a, E> = store::Query<'a, E, ic_storage::DefaultMemoryImpl>;
183/// Exclusive handle to a frozen source during maintenance.
184pub type Maintenance = store::Maintenance<ic_storage::DefaultMemoryImpl>;
185/// Bounded retained aggregates in their host-governed allocation.
186pub type AggregateJobs = store::AggregateJobs<ic_storage::DefaultMemoryImpl>;
187/// In-progress transformation into an identified target allocation.
188pub type SchemaCopy = store::SchemaCopy<ic_storage::DefaultMemoryImpl>;
189/// Retired source allocation held for bounded cleanup.
190pub type RetiredSource = store::RetiredSource<ic_storage::DefaultMemoryImpl>;
191
192/// Implementation methods for the concrete database handles. Installed Wasm
193/// fault probes enable `test-support` to specialize these handles for their backing.
194#[cfg(any(doc, feature = "test-support"))]
195pub mod qualification {
196    pub use crate::store::{
197        AggregateJobs, Database, Maintenance, Query, RetiredSource, SchemaCopy,
198    };
199}
200
201/// Failure before commit begins, or a refusal to admit stored data.
202#[derive(Debug)]
203pub enum Error {
204    /// A session operation conflicts with an active borrow of the attached database.
205    BorrowConflict,
206    /// Ordinary access is closed by an admitted durable maintenance gate.
207    Maintenance,
208    /// A maintenance identity is invalid or does not match this source/active transition.
209    InvalidTransition,
210    /// The retained job handle, query, result shape or requested sequence does not match.
211    InvalidJob,
212    /// All retained job slots are occupied; cancel or clean up expired jobs explicitly.
213    JobCapacity,
214    /// An arithmetic total exceeds its accumulator or explicitly selected result range.
215    ArithmeticOverflow,
216    /// Unsupported query field/shape or unavailable ordered access path.
217    InvalidQuery,
218    /// A query requiring at most one matching entity found a second.
219    MultipleMatches,
220    /// Malformed continuation or a different database/schema/query boundary.
221    InvalidCursor,
222    /// One matching encoded row exceeds the whole requested output-byte allowance.
223    RowTooLarge,
224    /// Managed insert/replacement requires an explicitly captured batch time.
225    MissingOperationTime,
226    /// A caller attempted to assign a database-managed field.
227    ManagedField,
228    /// A real change would move managed time behind its stored value.
229    TimestampRegression,
230    /// An insert input omitted a required field with no declared default.
231    MissingField(&'static str),
232    /// Invalid or unsupported compiled schema.
233    InvalidSchema,
234    /// An index operand has a different exact type from its declared field.
235    InvalidOperand,
236    /// The typed entity is not part of this admitted schema.
237    UnknownEntity,
238    /// The stored manifest belongs to another schema or format.
239    IncompatibleSchema,
240    /// Missing, malformed or internally inconsistent stored data.
241    Corrupt,
242    /// Insert requires an absent primary key.
243    Exists,
244    /// Replacement/deletion requires an existing primary key.
245    Missing,
246    /// Two batch commands address the same entity and primary key.
247    DuplicateTarget,
248    /// The intended final state violates a unique index.
249    UniqueViolation,
250    /// A reference target is absent, or a deleted target still has a dependent.
251    ReferenceViolation,
252    /// A declared resource bound or revision range is exceeded.
253    Limit,
254}
255
256impl std::fmt::Display for Error {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        write!(f, "{self:?}")
259    }
260}
261impl std::error::Error for Error {}
262
263/// Schema authoring for application design modules.
264pub mod design {
265    /// Declaration attributes, database scalar types and schema assembly.
266    ///
267    /// ```
268    /// use ic_db::design::prelude::*;
269    ///
270    /// #[newtype(item(prim = "Timestamp"))]
271    /// struct StartedAt {}
272    ///
273    /// #[list(item(is = "StartedAt"), max_items = 3)]
274    /// struct StartHistory {}
275    ///
276    /// #[canister]
277    /// struct App {}
278    ///
279    /// #[store(canister = App, key = "app.events.v1")]
280    /// struct Events {}
281    ///
282    /// #[entity(store = Events, pk(field = "id"), fields(
283    ///     field(name = "id", value(item(prim = "Nat64"))),
284    ///     field(name = "history", value(item(is = "StartHistory")))
285    /// ))]
286    /// struct Event {}
287    ///
288    /// let event = Event { id: 1, history: StartHistory(vec![StartedAt(Timestamp::from_millis(0))]) };
289    /// let schema = Schema::new(&[Event::SCHEMA]).unwrap();
290    /// assert_eq!(schema.entities()[0].name, "Event");
291    /// assert_eq!(event.history.0.len(), 1);
292    /// ```
293    pub mod prelude {
294        pub use crate::{
295            Account, Blob, Date, Decimal, Duration, Float32, Float64, Principal, Subaccount,
296            Timestamp, U256, Ulid,
297        };
298        pub use crate::{Canister, CompiledCanister, Entity, Schema, Store, Value};
299        pub use crate::{canister, entity, enum_, list, map, newtype, record, set, store};
300    }
301}
302
303/// Codec boundary emitted by `#[entity]`; hand-written implementations are unsupported.
304/// Typed references use Rust resolution; an unresolved name fails compilation:
305/// ```compile_fail
306/// use ic_db::design::prelude::*;
307/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(field="target"), fields(
308///     field(name="id",value(item(prim="Nat64"))),
309///     field(name="target",value(item(prim="Nat64")),references(entity="Missing"))))]
310/// struct Example {}
311/// ```
312/// Lookups require the declared key type; integers cannot stand in for ULIDs:
313/// ```compile_fail
314/// use ic_db::design::prelude::*;
315/// use ic_db::Database;
316/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id",value(item(prim="Ulid")))))]
317/// struct Asset {}
318/// fn wrong_key(db: &Database) { let _ = db.get::<Asset>(7_u64); }
319/// ```
320/// Integer key widths are exact, without implicit widening:
321/// ```compile_fail
322/// use ic_db::design::prelude::*;
323/// use ic_db::Database;
324/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id",value(item(prim="Nat8")))))]
325/// struct Small {}
326/// fn wrong_width(db: &Database) { let _ = db.get::<Small>(7_u64); }
327/// ```
328/// Field names come from the declaration. A missing `name` field cannot
329/// resolve to the entity's logical name, even when `Entity` is in scope.
330/// ```compile_fail
331/// use ic_db::design::prelude::*;
332/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
333/// struct Entry {}
334/// let _ = Entry::NAME;
335/// ```
336/// ```compile_fail
337/// use ic_db::design::prelude::*;
338/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
339/// struct Entry {}
340/// let _ = Entry::ENTITY_NAME;
341/// ```
342pub trait Entity: Sized {
343    /// Store selected by the schema author.
344    type Store: Store;
345    /// Exact supplied primary-key type, selected by the declared field.
346    type Key: PrimaryKey;
347    /// Rust-resolved declaration path for host schema assembly.
348    fn declaration_path() -> &'static str;
349    /// This executable's compiled entity contract.
350    const SCHEMA: &'static EntitySchema;
351    /// Read the application's primary key without encoding or inspecting indexes.
352    fn key(&self) -> Self::Key;
353
354    /// Extract keys from an already typed value for the shared mutation/index paths.
355    #[doc(hidden)]
356    fn __row_info(&self) -> __private::RowInfo;
357
358    /// Validate declared field bounds before encoding; no persistent effects.
359    /// # Errors
360    /// Refuses values outside the authored field contract.
361    fn validate(&self) -> Result<(), Error>;
362
363    /// Encode canonical stored fields within the row envelope.
364    /// # Errors
365    /// Returns a limit refusal when the row cannot be encoded within its bounds.
366    fn encode(&self) -> Result<Vec<u8>, Error>;
367
368    /// Decode an admitted row; this does not open a database or admit a schema.
369    /// # Errors
370    /// Returns corruption for malformed stored bytes.
371    fn decode(bytes: &[u8]) -> Result<Self, Error>;
372}
373
374/// Implementation support for generated code; not a second query frontend.
375#[doc(hidden)]
376pub mod __private {
377    #[cfg(all(feature = "build", not(target_arch = "wasm32")))]
378    pub use crate::build::{__build_schema, __canister, __ctor, __entity, __store};
379    pub use serde;
380    /// Independent of the descriptor so references can form cycles.
381    pub trait ReferenceTarget {
382        /// Schema-authored logical name of the target entity.
383        const NAME: &'static str;
384    }
385    pub use crate::codec::{Decoder, Encoder, MAX_ROW_BYTES};
386    pub use crate::key::encode_index;
387    pub use crate::managed::validate_order as validate_managed_order;
388    pub use crate::primary::RowKey;
389    pub use crate::schema::{check_schema_member, handle};
390    /// Primary/index keys extracted at the small typed codec boundary.
391    pub struct RowInfo {
392        pub key: RowKey,
393        /// None means the row is outside an explicitly present-only unique index.
394        pub indexes: Vec<Option<Vec<u8>>>,
395    }
396}