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    CURRENT_LEDGER_SCHEMA_VERSION, CURRENT_PHYSICAL_FORMAT_ID, GenerationRecord, LedgerCommitError,
96    LedgerCommitStore, LedgerCompatibilityError, LedgerIntegrityError, LedgerPayloadEnvelope,
97    LedgerPayloadEnvelopeError, RecoveredLedger, SchemaMetadataRecord,
98};
99pub use physical::{
100    AuthoritativeSlot, CommitRecoveryError, CommitSlotDiagnostic, CommitSlotIndex,
101    CommitStoreDiagnostic, CommittedGenerationBytes, DualCommitStore, DualProtectedCommitStore,
102    ProtectedGenerationSlot, select_authoritative_slot,
103};
104pub use policy::AllocationPolicy;
105pub use registry::{
106    StaticMemoryDeclaration, StaticMemoryDeclarationError, StaticMemoryRangeDeclaration,
107    collect_static_memory_declarations, register_static_memory_declaration,
108    register_static_memory_manager_declaration,
109    register_static_memory_manager_declaration_with_schema, register_static_memory_manager_range,
110    register_static_memory_range_declaration, static_memory_declaration_snapshot,
111    static_memory_declarations, static_memory_range_authority, static_memory_range_declarations,
112};
113pub use runtime::{
114    RuntimeBootstrapError, RuntimeOpenError, RuntimePolicyError, bootstrap_default_memory_manager,
115    bootstrap_default_memory_manager_with_policy,
116};
117pub use schema::{SchemaMetadata, SchemaMetadataError};
118pub use session::{AllocationSession, AllocationSessionError, ValidatedAllocations};
119pub use slot::{
120    AllocationSlot, AllocationSlotDescriptor, AllocationSlotDescriptorError,
121    IC_MEMORY_AUTHORITY_OWNER, IC_MEMORY_AUTHORITY_PURPOSE, IC_MEMORY_LEDGER_LABEL,
122    IC_MEMORY_LEDGER_STABLE_KEY, IC_MEMORY_STABLE_KEY_PREFIX, MEMORY_MANAGER_DESCRIPTOR_VERSION,
123    MEMORY_MANAGER_GOVERNANCE_MAX_ID, MEMORY_MANAGER_INVALID_ID, MEMORY_MANAGER_LEDGER_ID,
124    MEMORY_MANAGER_MAX_ID, MEMORY_MANAGER_MIN_ID, MEMORY_MANAGER_SUBSTRATE,
125    MemoryManagerAuthorityRecord, MemoryManagerIdRange, MemoryManagerRangeAuthority,
126    MemoryManagerRangeAuthorityError, MemoryManagerRangeError, MemoryManagerRangeMode,
127    MemoryManagerSlotError, is_ic_memory_stable_key, memory_manager_governance_range,
128    validate_memory_manager_id,
129};
130pub use stable_cell::{
131    STABLE_CELL_HEADER_SIZE, STABLE_CELL_LAYOUT_VERSION, STABLE_CELL_MAGIC,
132    STABLE_CELL_VALUE_OFFSET, StableCellLedgerError, StableCellLedgerRecord,
133    StableCellPayloadError, decode_stable_cell_ledger_record, decode_stable_cell_payload,
134    validate_stable_cell_ledger_memory,
135};
136pub use substrate::{LedgerAnchor, StorageSubstrate};
137pub use validation::{AllocationValidationError, Validate, validate_allocations};
138
139#[doc(hidden)]
140pub mod __reexports {
141    pub use ctor;
142}
143
144/// Register a `MemoryManager` allocation declaration during static initialization.
145///
146/// This macro only registers declaration metadata. It does not open stable
147/// memory. The bootstrap owner still has to collect/seal declarations, validate
148/// them against the ledger, commit the generation, and then open memory handles.
149#[macro_export]
150macro_rules! ic_memory_declaration {
151    (key = $stable_key:literal, ty = $label:path, id = $id:expr $(,)?) => {
152        const _: () = {
153            #[allow(dead_code)]
154            type IcMemoryTypeCheck = $label;
155
156            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
157            fn __ic_memory_register_static_declaration() {
158                $crate::register_static_memory_manager_declaration(
159                    $id,
160                    env!("CARGO_PKG_NAME"),
161                    stringify!($label),
162                    $stable_key,
163                )
164                .expect("ic-memory static memory declaration failed");
165            }
166        };
167    };
168    (key = $stable_key:literal, label = $label:literal, id = $id:expr $(,)?) => {
169        const _: () = {
170            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
171            fn __ic_memory_register_static_declaration() {
172                $crate::register_static_memory_manager_declaration(
173                    $id,
174                    env!("CARGO_PKG_NAME"),
175                    $label,
176                    $stable_key,
177                )
178                .expect("ic-memory static memory declaration failed");
179            }
180        };
181    };
182}
183
184/// Declare a `MemoryManager` allocation range during static initialization.
185#[macro_export]
186macro_rules! ic_memory_range {
187    (start = $start:expr, end = $end:expr $(,)?) => {
188        $crate::ic_memory_range!(
189            start = $start,
190            end = $end,
191            mode = Reserved,
192        );
193    };
194    (start = $start:expr, end = $end:expr, mode = $mode:ident $(,)?) => {
195        const _: () = {
196            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
197            fn __ic_memory_register_static_range() {
198                $crate::register_static_memory_manager_range(
199                    $start,
200                    $end,
201                    env!("CARGO_PKG_NAME"),
202                    $crate::MemoryManagerRangeMode::$mode,
203                    None,
204                )
205                .expect("ic-memory static memory range declaration failed");
206            }
207        };
208    };
209}
210
211/// Declare and open a validated `MemoryManager` slot by stable key.
212///
213/// The macro registers declaration metadata during static initialization and
214/// returns the validated default-runtime memory handle at expression use time.
215#[macro_export]
216macro_rules! ic_memory_key {
217    ($stable_key:literal, $label:path, $id:expr $(,)?) => {{
218        $crate::ic_memory_declaration!(key = $stable_key, ty = $label, id = $id,);
219        $crate::runtime::open_default_memory_manager_memory($stable_key, $id)
220            .expect("ic-memory stable memory opened before runtime bootstrap")
221    }};
222    (key = $stable_key:literal, ty = $label:path, id = $id:expr $(,)?) => {{ $crate::ic_memory_key!($stable_key, $label, $id) }};
223    (key = $stable_key:literal, label = $label:literal, id = $id:expr $(,)?) => {{
224        $crate::ic_memory_declaration!(key = $stable_key, label = $label, id = $id,);
225        $crate::runtime::open_default_memory_manager_memory($stable_key, $id)
226            .expect("ic-memory stable memory opened before runtime bootstrap")
227    }};
228}
229
230/// Register one pre-bootstrap hook.
231#[macro_export]
232macro_rules! eager_init {
233    ($body:block) => {
234        const _: () = {
235            fn __ic_memory_registered_eager_init_body() {
236                $body
237            }
238
239            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
240            fn __ic_memory_register_eager_init() {
241                $crate::runtime::defer_eager_init(__ic_memory_registered_eager_init_body);
242            }
243        };
244    };
245}