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