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