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