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