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 member;
89mod primary;
90mod schema;
91mod session;
92mod store;
93mod store_key;
94mod time;
95mod types;
96mod u256;
97mod ulid;
98#[cfg(feature = "wire")]
99mod wire;
100
101#[cfg(all(feature = "build", not(target_arch = "wasm32")))]
102mod build;
103
104#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
105pub mod testing;
106
107pub use canister_session::{CanisterSession, MountedStore, StoreBatch};
108pub use date::Date;
109pub use decimal::{Decimal, ParseDecimalError};
110pub use defaults::{InsertInput, LiteralDefault};
111pub use float::{Float32, Float64};
112pub use ic_db_macros::{canister, entity, enum_, list, map, newtype, record, set, store};
113pub use ic_platform_types::{Account, Principal, Subaccount};
114pub use key::IndexValue;
115pub use managed::ManagedTimestamp;
116pub use primary::{Id, PrimaryKey};
117pub use schema::{EntitySchema, FieldSchema, FieldType, IndexSchema, ReferenceSchema, Schema};
118pub use session::{DatabaseSession, InsertOutcome, QuerySession, UniqueKey};
119pub use store::{
120    Aggregate, Batch, Column, Comparison, CopyStatus, CopyStep, GroupCount, GroupCursor,
121    GroupOrder, GroupPage, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle,
122    JobOutcome, JobStep, Page, QueryCursor, QueryOperand, QueryPage, SchemaTransition,
123    SelectColumns, SelectedQuery, Selection, SortDirection, SummaryMeasure,
124};
125pub use store_key::MAX_INDEX_KEY_BYTES;
126pub use time::{Duration, TimeParseError, Timestamp};
127pub use types::{TypeBody, TypeLink, TypeSchema, Value, ValueSchema, VariantSchema};
128pub use u256::U256;
129pub use ulid::{
130    SeededUlidGenerator, Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, UlidParseError,
131};
132
133#[doc(hidden)]
134#[cfg(any(not(feature = "build"), target_arch = "wasm32"))]
135#[macro_export]
136macro_rules! __register_schema {
137    ($($declaration:tt)*) => {};
138}
139
140#[doc(hidden)]
141#[cfg(not(feature = "wire"))]
142#[macro_export]
143macro_rules! __wire_as {
144    ($value:ty, $layout:ty) => {};
145}
146
147/// Include the schema assembly generated by this package’s build script.
148/// Invoke once at the crate root alongside the declarations compiled by
149/// `ic_db::build_schema!`. Consumers import the resulting types from that crate.
150#[macro_export]
151macro_rules! include_schema {
152    () => {
153        ::core::include!(::core::concat!(::core::env!("OUT_DIR"), "/schema.rs"));
154    };
155}
156
157/// Logical database owner. Deployment and memory grants belong to the host.
158pub trait Canister {
159    #[doc(hidden)]
160    const DECLARATION: &'static str;
161}
162
163/// Logical store and the stable allocation it uses within its canister.
164pub trait Store {
165    /// Canister declaring this allocation.
166    type Canister: Canister;
167    /// IC Storage stable allocation key.
168    const KEY: &'static str;
169    #[doc(hidden)]
170    const DECLARATION: &'static str;
171}
172
173/// Host-facing assembly generated in the schema owner's library.
174pub trait CompiledCanister: Canister {
175    /// Stores owned by this canister, in stable key order.
176    const STORES: &'static [CompiledStore];
177}
178
179/// Validated schema and its stable allocation key.
180pub struct CompiledStore {
181    /// Key used to create and reopen the allocation.
182    pub key: &'static str,
183    /// Obtain the admitted schema for this allocation.
184    pub schema: fn() -> Schema,
185}
186
187/// Owned binary bytes. The database codec enforces authored limits and row bounds.
188pub type Blob = Vec<u8>;
189
190/// Admitted database owning an exclusive lease on a named IC Storage allocation.
191pub type Database = store::Database<ic_storage::DefaultMemoryImpl>;
192/// Fluent query over an entity in the admitted database.
193pub type Query<'a, E> = store::Query<'a, E, ic_storage::DefaultMemoryImpl>;
194/// Exclusive handle to a frozen source during maintenance.
195pub type Maintenance = store::Maintenance<ic_storage::DefaultMemoryImpl>;
196/// Bounded retained aggregates in their host-governed allocation.
197pub type AggregateJobs = store::AggregateJobs<ic_storage::DefaultMemoryImpl>;
198/// In-progress transformation into an identified target allocation.
199pub type SchemaCopy = store::SchemaCopy<ic_storage::DefaultMemoryImpl>;
200/// Retired source allocation held for bounded cleanup.
201pub type RetiredSource = store::RetiredSource<ic_storage::DefaultMemoryImpl>;
202
203/// Implementation methods for the concrete database handles. Installed Wasm
204/// fault probes enable `test-support` to specialize these handles for their backing.
205#[cfg(any(doc, feature = "test-support"))]
206pub mod qualification {
207    pub use crate::store::{
208        AggregateJobs, Database, Maintenance, Query, RetiredSource, SchemaCopy,
209    };
210}
211
212/// Failure before commit begins, or a refusal to admit stored data.
213#[derive(Debug)]
214pub enum Error {
215    /// A session operation conflicts with an active borrow of the attached database.
216    BorrowConflict,
217    /// Ordinary access is closed by an admitted durable maintenance gate.
218    Maintenance,
219    /// A maintenance identity is invalid or does not match this source/active transition.
220    InvalidTransition,
221    /// The retained job handle, query, result shape or requested sequence does not match.
222    InvalidJob,
223    /// All retained job slots are occupied; cancel or clean up expired jobs explicitly.
224    JobCapacity,
225    /// An arithmetic total exceeds its accumulator or explicitly selected result range.
226    ArithmeticOverflow,
227    /// Unsupported query field/shape or unavailable ordered access path.
228    InvalidQuery,
229    /// A query requiring at most one matching entity found a second.
230    MultipleMatches,
231    /// Malformed continuation or a different database/schema/query boundary.
232    InvalidCursor,
233    /// One matching encoded row exceeds the whole requested output-byte allowance.
234    RowTooLarge,
235    /// Materializing an entity with managed timestamps requires a write batch.
236    MissingOperationTime,
237    /// A caller attempted to assign a database-managed field.
238    ManagedField,
239    /// A real change would move managed time behind its stored value.
240    TimestampRegression,
241    /// An insert input omitted a required field with no declared default.
242    MissingField(&'static str),
243    /// Invalid or unsupported compiled schema.
244    InvalidSchema,
245    /// An index operand has a different exact type from its declared field.
246    InvalidOperand,
247    /// The typed entity is not part of this admitted schema.
248    UnknownEntity,
249    /// The stored manifest belongs to another schema or format.
250    IncompatibleSchema,
251    /// Missing, malformed or internally inconsistent stored data.
252    Corrupt,
253    /// Insert requires an absent primary key.
254    Exists,
255    /// Replacement/deletion requires an existing primary key.
256    Missing,
257    /// Two batch commands address the same entity and primary key.
258    DuplicateTarget,
259    /// The intended final state violates a unique index.
260    UniqueViolation,
261    /// A reference target is absent, or a deleted target still has a dependent.
262    ReferenceViolation,
263    /// A declared resource bound or revision range is exceeded.
264    Limit,
265}
266
267impl std::fmt::Display for Error {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        write!(f, "{self:?}")
270    }
271}
272impl std::error::Error for Error {}
273
274/// Schema authoring for application design modules.
275pub mod design {
276    /// Declaration attributes, database scalar types and schema assembly.
277    ///
278    /// ```
279    /// use ic_db::design::prelude::*;
280    ///
281    /// #[newtype(item(prim = "Timestamp"))]
282    /// struct StartedAt {}
283    ///
284    /// #[list(item(is = "StartedAt"), max_items = 3)]
285    /// struct StartHistory {}
286    ///
287    /// #[canister]
288    /// struct App {}
289    ///
290    /// #[store(canister = App, key = "app.events.v1")]
291    /// struct Events {}
292    ///
293    /// #[entity(store = Events, pk(field = "id"), fields(
294    ///     field(name = "id", value(item(prim = "Nat64"))),
295    ///     field(name = "history", value(item(is = "StartHistory")))
296    /// ))]
297    /// struct Event {}
298    ///
299    /// let event = Event { id: 1, history: StartHistory(vec![StartedAt(Timestamp::from_millis(0))]) };
300    /// let schema = Schema::new(&[Event::SCHEMA]).unwrap();
301    /// assert_eq!(schema.entities()[0].name, "Event");
302    /// assert_eq!(event.history.0.len(), 1);
303    /// ```
304    pub mod prelude {
305        pub use crate::{
306            Account, Blob, Date, Decimal, Duration, Float32, Float64, Principal, Subaccount,
307            Timestamp, U256, Ulid,
308        };
309        pub use crate::{Canister, CompiledCanister, Entity, Schema, Store, Value};
310        pub use crate::{canister, entity, enum_, list, map, newtype, record, set, store};
311    }
312}
313
314/// Codec boundary emitted by `#[entity]`; hand-written implementations are unsupported.
315/// Typed references use Rust resolution; an unresolved name fails compilation:
316/// ```compile_fail
317/// use ic_db::design::prelude::*;
318/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(field="target"), fields(
319///     field(name="id",value(item(prim="Nat64"))),
320///     field(name="target",value(item(prim="Nat64")),references(entity="Missing"))))]
321/// struct Example {}
322/// ```
323/// Lookups require the declared key type; integers cannot stand in for ULIDs:
324/// ```compile_fail
325/// use ic_db::design::prelude::*;
326/// use ic_db::Database;
327/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id",value(item(prim="Ulid")))))]
328/// struct Asset {}
329/// fn wrong_key(db: &Database) { let _ = db.get::<Asset>(7_u64); }
330/// ```
331/// Integer key widths are exact, without implicit widening:
332/// ```compile_fail
333/// use ic_db::design::prelude::*;
334/// use ic_db::Database;
335/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id",value(item(prim="Nat8")))))]
336/// struct Small {}
337/// fn wrong_width(db: &Database) { let _ = db.get::<Small>(7_u64); }
338/// ```
339/// Field names come from the declaration. A missing `name` field cannot
340/// resolve to the entity's logical name, even when `Entity` is in scope.
341/// ```compile_fail
342/// use ic_db::design::prelude::*;
343/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
344/// struct Entry {}
345/// let _ = Entry::NAME;
346/// ```
347/// ```compile_fail
348/// use ic_db::design::prelude::*;
349/// #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
350/// struct Entry {}
351/// let _ = Entry::ENTITY_NAME;
352/// ```
353pub trait Entity: Sized {
354    /// Store selected by the schema author.
355    type Store: Store;
356    /// Exact supplied primary-key type, selected by the declared field.
357    type Key: PrimaryKey + Into<Id<Self>>;
358    /// Rust-resolved declaration path for host schema assembly.
359    fn declaration_path() -> &'static str;
360    /// This executable's compiled entity contract.
361    const SCHEMA: &'static EntitySchema;
362    /// Read the application's primary key without encoding or inspecting indexes.
363    fn key(&self) -> Self::Key;
364
365    /// Return this row’s entity-typed primary key.
366    fn id(&self) -> Id<Self> {
367        Id::from_key(self.key())
368    }
369
370    /// Extract keys from an already typed value for the shared mutation/index paths.
371    #[doc(hidden)]
372    fn __row_info(&self) -> __private::RowInfo;
373
374    /// Validate declared field bounds before encoding; no persistent effects.
375    /// # Errors
376    /// Refuses values outside the authored field contract.
377    fn validate(&self) -> Result<(), Error>;
378
379    /// Encode canonical stored fields within the row envelope.
380    /// # Errors
381    /// Returns a limit refusal when the row cannot be encoded within its bounds.
382    fn encode(&self) -> Result<Vec<u8>, Error>;
383
384    /// Decode an admitted row; this does not open a database or admit a schema.
385    /// # Errors
386    /// Returns corruption for malformed stored bytes.
387    fn decode(bytes: &[u8]) -> Result<Self, Error>;
388}
389
390/// Implementation support for generated code; not a second query frontend.
391#[doc(hidden)]
392pub mod __private {
393    #[cfg(all(feature = "build", not(target_arch = "wasm32")))]
394    pub use crate::build::{__build_schema, __canister, __ctor, __entity, __store};
395    #[cfg(not(feature = "wire"))]
396    pub use ic_db_macros::__StorageOnly as Wire;
397    #[cfg(feature = "wire")]
398    pub use ic_wire::{self, typescript::Wire};
399    pub use serde;
400    /// Independent of the descriptor so references can form cycles.
401    pub trait ReferenceTarget {
402        /// Schema-authored logical name of the target entity.
403        const NAME: &'static str;
404    }
405    pub use crate::codec::{Decoder, Encoder, MAX_ROW_BYTES};
406    pub use crate::key::{MemberOperand, MemberPresence, encode_index};
407    pub use crate::managed::validate_order as validate_managed_order;
408    pub use crate::primary::RowKey;
409    pub use crate::schema::{check_schema_member, handle};
410    pub use crate::ulid::insert_ulid;
411    /// Primary/index keys extracted at the small typed codec boundary.
412    pub struct RowInfo {
413        pub list_links: Vec<(u32, RowKey)>,
414        pub key: RowKey,
415        /// None means the row is outside an explicitly present-only unique index.
416        pub indexes: Vec<Option<Vec<u8>>>,
417    }
418}
419
420/// Join two generated field-name constants for a scalar record member.
421/// For example, `ic_db::field_path!(Product::PRICE, Price::AMOUNT)` is a
422/// static field name accepted by scalar literal filters and row ordering.
423#[macro_export]
424macro_rules! field_path {
425    ($record:path, $member:path $(,)?) => {{
426        const BYTES: [u8; $record.len() + 1 + $member.len()] = {
427            let mut bytes = [0; $record.len() + 1 + $member.len()];
428            let (parent, tail) = bytes.split_at_mut($record.len());
429            parent.copy_from_slice($record.as_bytes());
430            tail[0] = b'.';
431            tail.split_at_mut(1).1.copy_from_slice($member.as_bytes());
432            bytes
433        };
434        const {
435            match ::core::str::from_utf8(&BYTES) {
436                Ok(path) => path,
437                Err(_) => panic!("invalid field name"),
438            }
439        }
440    }};
441}