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