Skip to main content

ic_memory/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(rustdoc::broken_intra_doc_links)]
3#![doc = include_str!("../README.md")]
4
5//! Stable-memory allocation-governance primitives for Internet Computer
6//! canister upgrades.
7//!
8//! `ic-memory` prevents stable-memory slot drift.
9//!
10//! Once a stable key is committed to a physical allocation slot, future binaries
11//! must either reopen that same stable key on that same slot or declare a new
12//! stable key.
13//!
14//! The crate records and validates durable ownership in both directions: an
15//! active stable key cannot move to a different physical slot, and an active
16//! physical slot cannot be reused by a different stable key.
17//!
18//! The intended integration flow is:
19//!
20//! 1. Recover the persisted allocation ledger.
21//! 2. Declare the stable stores expected by the current binary.
22//! 3. Validate those declarations against ledger history and any framework
23//!    policy.
24//! 4. Commit the next generation.
25//! 5. Only then open stable-memory handles through a validated allocation
26//!    session.
27//!
28//! This crate owns allocation invariants, not framework policy. Namespace
29//! rules, controller authorization, endpoint lifecycle, schema migrations, and
30//! application validation belong to the framework or application.
31//!
32//! For the default `MemoryManager` runtime, registered `ic-memory` range claims
33//! are generic allocation policy and are enforced before caller-supplied
34//! policy. A framework such as Canic that wants higher-level range semantics
35//! should adapt to this contract deliberately: either register the ranges it
36//! wants `ic-memory` to enforce, or omit user ranges and enforce application
37//! space through its own [`AllocationPolicy`].
38//!
39//! Use these primitives before opening stable-memory handles. Integrations
40//! should recover the historical ledger, declare the stores expected by the
41//! current binary, validate declarations against history and policy, commit a
42//! new generation, and only then publish a validated allocation session that can
43//! open slots through a storage substrate.
44//!
45//! [`AllocationBootstrap`] is the golden path for whichever layer owns a given
46//! ledger store. Canic may own bootstrap for a framework canister and compose
47//! IcyDB/application declarations through its registry; IcyDB may own bootstrap
48//! directly for generated database stores; or a standalone application canister
49//! may own bootstrap itself. Exactly one owner should bootstrap one ledger
50//! store. Multiple layers in the same canister must either compose declarations
51//! into that owner or use distinct ledger stores and allocation domains.
52//!
53//! `ic-stable-structures` `MemoryManager` IDs are the first-class supported
54//! physical slot substrate. That ID domain is `u8`: IDs `0..=254` are usable,
55//! and ID `255` is always the `ic-stable-structures` unallocated sentinel.
56//! The crate still keeps narrow internal abstractions for storage adapters and
57//! diagnostics, but the native IC path is
58//! `MemoryManager` ID 0 -> `ic-stable-structures::Cell<StableCellLedgerRecord,
59//! _>` -> [`LedgerCommitStore`] -> [`CommittedGenerationBytes`] ->
60//! [`LedgerPayloadEnvelope`] -> [`RecoveredLedger`] -> [`ValidatedAllocations`].
61//!
62//! `ic-memory` is not a replacement for `ic-stable-structures` collections and
63//! does not wrap typed stores such as `StableBTreeMap`.
64
65pub mod bootstrap;
66pub mod declaration;
67pub mod diagnostics;
68pub mod key;
69pub mod ledger;
70pub mod physical;
71pub mod policy;
72pub mod registry;
73pub mod runtime;
74pub mod schema;
75pub mod session;
76pub mod slot;
77pub mod stable_cell;
78pub mod substrate;
79pub mod validation;
80
81pub use ic_stable_structures as stable_structures;
82
83pub use bootstrap::{
84    AllocationBootstrap, BootstrapCommit, BootstrapError, BootstrapReservationError,
85    BootstrapRetirementError,
86};
87pub use declaration::{
88    AllocationDeclaration, DeclarationCollector, DeclarationSnapshot, DeclarationSnapshotError,
89};
90pub use diagnostics::{DiagnosticExport, DiagnosticGeneration, DiagnosticRecord};
91pub use key::{StableKey, StableKeyError};
92pub use ledger::{
93    AllocationHistory, AllocationLedger, AllocationRecord, AllocationReservationError,
94    AllocationRetirement, AllocationRetirementError, AllocationStageError, AllocationState,
95    GenerationRecord, LedgerCommitError, LedgerCommitStore, LedgerIntegrityError,
96    LedgerPayloadEnvelope, LedgerPayloadEnvelopeError, RecoveredLedger, SchemaMetadataRecord,
97};
98pub use physical::{
99    AuthoritativeSlot, CommitRecoveryError, CommitSlotDiagnostic, CommitSlotIndex,
100    CommitStoreDiagnostic, CommittedGenerationBytes, DualCommitStore, DualProtectedCommitStore,
101    ProtectedGenerationSlot, select_authoritative_slot,
102};
103pub use policy::AllocationPolicy;
104pub use registry::{
105    StaticMemoryDeclaration, StaticMemoryDeclarationError, StaticMemoryRangeDeclaration,
106    collect_static_memory_declarations, register_static_memory_declaration,
107    register_static_memory_manager_declaration,
108    register_static_memory_manager_declaration_with_schema, register_static_memory_manager_range,
109    register_static_memory_range_declaration, static_memory_declaration_snapshot,
110    static_memory_declarations, static_memory_range_authority, static_memory_range_declarations,
111};
112pub use runtime::{
113    RuntimeBootstrapError, RuntimeOpenError, RuntimePolicyError, bootstrap_default_memory_manager,
114    bootstrap_default_memory_manager_with_policy,
115};
116pub use schema::{SchemaMetadata, SchemaMetadataError};
117pub use session::{AllocationSession, AllocationSessionError, ValidatedAllocations};
118pub use slot::{
119    AllocationSlot, AllocationSlotDescriptor, IC_MEMORY_AUTHORITY_OWNER,
120    IC_MEMORY_AUTHORITY_PURPOSE, IC_MEMORY_LEDGER_LABEL, IC_MEMORY_LEDGER_STABLE_KEY,
121    IC_MEMORY_STABLE_KEY_PREFIX, MEMORY_MANAGER_GOVERNANCE_MAX_ID, MEMORY_MANAGER_INVALID_ID,
122    MEMORY_MANAGER_LEDGER_ID, MEMORY_MANAGER_MAX_ID, MEMORY_MANAGER_MIN_ID,
123    MemoryManagerAuthorityRecord, MemoryManagerIdRange, MemoryManagerRangeAuthority,
124    MemoryManagerRangeAuthorityError, MemoryManagerRangeError, MemoryManagerRangeMode,
125    MemoryManagerSlotError, is_ic_memory_stable_key, memory_manager_governance_range,
126    validate_memory_manager_id,
127};
128pub use stable_cell::{
129    STABLE_CELL_HEADER_SIZE, STABLE_CELL_LAYOUT_VERSION, STABLE_CELL_MAGIC,
130    STABLE_CELL_VALUE_OFFSET, StableCellLedgerError, StableCellLedgerRecord,
131    StableCellPayloadError, decode_stable_cell_ledger_record, decode_stable_cell_payload,
132    validate_stable_cell_ledger_memory,
133};
134pub use substrate::{LedgerAnchor, StorageSubstrate};
135pub use validation::{AllocationValidationError, Validate, validate_allocations};
136
137#[doc(hidden)]
138pub mod __reexports {
139    pub use ctor;
140}
141
142/// Register a `MemoryManager` allocation declaration during static initialization.
143///
144/// This macro only registers declaration metadata. It does not open stable
145/// memory. The bootstrap owner still has to collect/seal declarations, validate
146/// them against the ledger, commit the generation, and then open memory handles.
147#[macro_export]
148macro_rules! ic_memory_declaration {
149    (key = $stable_key:literal, ty = $label:path, id = $id:expr $(,)?) => {
150        const _: () = {
151            #[allow(dead_code)]
152            type IcMemoryTypeCheck = $label;
153
154            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
155            fn __ic_memory_register_static_declaration() {
156                $crate::register_static_memory_manager_declaration(
157                    $id,
158                    env!("CARGO_PKG_NAME"),
159                    stringify!($label),
160                    $stable_key,
161                )
162                .expect("ic-memory static memory declaration failed");
163            }
164        };
165    };
166    (key = $stable_key:literal, label = $label:literal, id = $id:expr $(,)?) => {
167        const _: () = {
168            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
169            fn __ic_memory_register_static_declaration() {
170                $crate::register_static_memory_manager_declaration(
171                    $id,
172                    env!("CARGO_PKG_NAME"),
173                    $label,
174                    $stable_key,
175                )
176                .expect("ic-memory static memory declaration failed");
177            }
178        };
179    };
180}
181
182/// Declare a `MemoryManager` allocation range during static initialization.
183#[macro_export]
184macro_rules! ic_memory_range {
185    (start = $start:expr, end = $end:expr $(,)?) => {
186        $crate::ic_memory_range!(
187            start = $start,
188            end = $end,
189            mode = Reserved,
190        );
191    };
192    (start = $start:expr, end = $end:expr, mode = $mode:ident $(,)?) => {
193        const _: () = {
194            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
195            fn __ic_memory_register_static_range() {
196                $crate::register_static_memory_manager_range(
197                    $start,
198                    $end,
199                    env!("CARGO_PKG_NAME"),
200                    $crate::MemoryManagerRangeMode::$mode,
201                    None,
202                )
203                .expect("ic-memory static memory range declaration failed");
204            }
205        };
206    };
207}
208
209/// Declare and open a validated `MemoryManager` slot by stable key.
210///
211/// The macro registers declaration metadata during static initialization and
212/// returns the validated default-runtime memory handle at expression use time.
213#[macro_export]
214macro_rules! ic_memory_key {
215    ($stable_key:literal, $label:path, $id:expr $(,)?) => {{
216        $crate::ic_memory_declaration!(key = $stable_key, ty = $label, id = $id,);
217        $crate::runtime::open_default_memory_manager_memory($stable_key, $id)
218            .expect("ic-memory failed to open validated stable memory; bootstrap must run first and the stable key/id must match the validated declaration")
219    }};
220    (key = $stable_key:literal, ty = $label:path, id = $id:expr $(,)?) => {{ $crate::ic_memory_key!($stable_key, $label, $id) }};
221    (key = $stable_key:literal, label = $label:literal, id = $id:expr $(,)?) => {{
222        $crate::ic_memory_declaration!(key = $stable_key, label = $label, id = $id,);
223        $crate::runtime::open_default_memory_manager_memory($stable_key, $id)
224            .expect("ic-memory failed to open validated stable memory; bootstrap must run first and the stable key/id must match the validated declaration")
225    }};
226}
227
228/// Register one pre-bootstrap hook.
229#[macro_export]
230macro_rules! eager_init {
231    ($body:block) => {
232        const _: () = {
233            fn __ic_memory_registered_eager_init_body() {
234                $body
235            }
236
237            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
238            fn __ic_memory_register_eager_init() {
239                $crate::runtime::defer_eager_init(__ic_memory_registered_eager_init_body);
240            }
241        };
242    };
243}