canic-core 0.100.54

Canic — a canister orchestration and management toolkit for the Internet Computer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Module: ops::runtime::memory
//!
//! Responsibility: bootstrap memory registry TLS and expose memory diagnostics.
//! Does not own: memory schema declarations, stable records, or DTO schema.
//! Boundary: maps memory runtime diagnostics into ops query responses.

use crate::{
    InternalError,
    domain::memory::{
        MemoryAllocationState, MemoryCommitRecoveryErrorResponse, MemoryRangeAuthorityMode,
    },
    dto::memory::{
        MemoryAllocationRecordEntry, MemoryAllocationSizeEntry, MemoryCommitRecoveryResponse,
        MemoryCommitSlotResponse, MemoryLedgerGenerationEntry, MemoryLedgerMemoryEntry,
        MemoryLedgerResponse, MemoryRangeAuthorityEntry, MemorySchemaMetadataEntry,
    },
    memory::{self, ledger, registry::MemoryRegistryError, runtime::init_eager_tls},
    ops::runtime::RuntimeOpsError,
};
use ic_memory::{
    AllocationState, CommitRecoveryError, CommitSlotDiagnostic, CommitStoreDiagnostic,
    DiagnosticGeneration, DiagnosticMemorySize, DiagnosticRecord, MemoryManagerRangeMode,
    SchemaMetadataRecord,
};
use thiserror::Error as ThisError;

///
/// MemoryRegistryOpsError
///
/// Typed failure surface for memory registry bootstrap and diagnostics.
///

#[derive(Debug, ThisError)]
pub enum MemoryRegistryOpsError {
    // this error comes from the Canic memory runtime boundary
    #[error(transparent)]
    Registry(#[from] MemoryRegistryError),
    // this error comes from the generic ic-memory runtime boundary
    #[error(transparent)]
    Runtime(#[from] ic_memory::RuntimeBootstrapError<MemoryRegistryError>),
    // this error comes from the generic ic-memory runtime diagnostic boundary
    #[error(transparent)]
    Diagnostic(#[from] ic_memory::RuntimeDiagnosticError),
    // this error comes from entering the default ic-memory TLS runtime
    #[error(transparent)]
    State(#[from] ic_memory::RuntimeStateError),
}

impl From<MemoryRegistryOpsError> for InternalError {
    fn from(err: MemoryRegistryOpsError) -> Self {
        RuntimeOpsError::MemoryRegistryOps(err).into()
    }
}

///
/// MemoryRegistryOps
///
/// Operations-layer facade for memory registry bootstrap and diagnostics.
///

pub struct MemoryRegistryOps;

impl MemoryRegistryOps {
    // Run eager TLS touches after the registry validates stable-memory slots.
    pub fn init_eager_tls() {
        init_eager_tls();
    }

    // Initialize the stable-memory registry for this crate and summarize the layout.
    pub(crate) fn init_registry() -> Result<(), InternalError> {
        memory::bootstrap_default_memory_manager().map_err(MemoryRegistryOpsError::from)?;
        Ok(())
    }

    // Run the full synchronous Canic memory bootstrap and return the committed layout.
    pub fn bootstrap_registry() -> Result<(), InternalError> {
        Self::init_registry()?;
        Self::init_eager_tls();
        Ok(())
    }

    pub fn is_initialized() -> Result<bool, InternalError> {
        crate::memory::runtime::is_memory_bootstrap_ready()
            .map_err(MemoryRegistryOpsError::from)
            .map_err(Into::into)
    }

    #[cfg(target_arch = "wasm32")]
    pub fn ensure_bootstrap() -> Result<(), InternalError> {
        if Self::is_initialized()? {
            return Ok(());
        }

        Self::bootstrap_registry()
    }

    // Read the committed ABI ledger using the restricted diagnostic path.
    pub fn ledger_snapshot() -> Result<MemoryLedgerResponse, InternalError> {
        let snapshot = ledger::try_snapshot().map_err(MemoryRegistryOpsError::from)?;

        let authorities = snapshot
            .authorities
            .into_iter()
            .map(memory_range_authority_entry_response)
            .collect();

        let records: Vec<MemoryAllocationRecordEntry> = snapshot
            .export
            .records
            .into_iter()
            .map(memory_allocation_record_response)
            .collect();
        let memories = memory_ledger_memory_entries(&records);
        let generations = snapshot
            .export
            .generations
            .into_iter()
            .map(memory_ledger_generation_response)
            .collect();

        Ok(MemoryLedgerResponse {
            ledger_schema_version: crate::memory::ledger::MEMORY_LEDGER_SCHEMA_VERSION,
            physical_format_id: crate::memory::ledger::MEMORY_PHYSICAL_FORMAT_ID,
            current_generation: snapshot.export.current_generation,
            commit_recovery: commit_recovery_response(snapshot.export.commit_recovery),
            authorities,
            memories,
            records,
            generations,
        })
    }
}

const fn memory_range_authority_mode(mode: MemoryManagerRangeMode) -> MemoryRangeAuthorityMode {
    match mode {
        MemoryManagerRangeMode::Reserved => MemoryRangeAuthorityMode::Reserved,
        MemoryManagerRangeMode::Allowed => MemoryRangeAuthorityMode::Allowed,
    }
}

fn commit_recovery_response(
    diagnostic: Option<CommitStoreDiagnostic>,
) -> MemoryCommitRecoveryResponse {
    let diagnostic = diagnostic.unwrap_or(CommitStoreDiagnostic {
        slot0: CommitSlotDiagnostic::Empty,
        slot1: CommitSlotDiagnostic::Empty,
        recovery: Err(CommitRecoveryError::NoValidGeneration),
    });
    let (authoritative_generation, recovery_error) = match diagnostic.recovery {
        Ok(generation) => (Some(generation), None),
        Err(error) => (None, Some(commit_recovery_error_response(error))),
    };
    MemoryCommitRecoveryResponse {
        slot0: commit_slot_response(diagnostic.slot0),
        slot1: commit_slot_response(diagnostic.slot1),
        authoritative_generation,
        recovery_error,
    }
}

fn memory_allocation_record_response(record: DiagnosticRecord) -> MemoryAllocationRecordEntry {
    let memory_size = record.memory_size.map(memory_allocation_size_response);
    let allocation = record.allocation;
    let allocation_state = allocation.state();
    MemoryAllocationRecordEntry {
        memory_manager_id: allocation.slot().memory_manager_id().ok(),
        stable_key: allocation.stable_key().as_str().to_string(),
        state: memory_allocation_state_response(allocation_state),
        memory_size,
        first_generation: allocation.first_generation(),
        last_seen_generation: allocation.last_seen_generation(),
        retired_generation: allocation_retired_generation(allocation_state),
        schema_history: allocation
            .schema_history()
            .iter()
            .map(memory_schema_metadata_response)
            .collect(),
    }
}

fn memory_ledger_memory_entries(
    records: &[MemoryAllocationRecordEntry],
) -> Vec<MemoryLedgerMemoryEntry> {
    records
        .iter()
        .filter_map(memory_ledger_memory_entry_response)
        .collect()
}

fn memory_ledger_memory_entry_response(
    record: &MemoryAllocationRecordEntry,
) -> Option<MemoryLedgerMemoryEntry> {
    Some(MemoryLedgerMemoryEntry {
        memory_manager_id: record.memory_manager_id?,
        stable_key: record.stable_key.clone(),
        state: record.state,
        size: record.memory_size?,
    })
}

fn memory_range_authority_entry_response(
    authority: ic_memory::MemoryManagerAuthorityRecord,
) -> MemoryRangeAuthorityEntry {
    let range = authority.range();
    MemoryRangeAuthorityEntry {
        owner: authority.authority().to_string(),
        start: range.start(),
        end: range.end(),
        mode: memory_range_authority_mode(authority.mode()),
        purpose: authority.purpose().unwrap_or_default().to_string(),
    }
}

const fn memory_allocation_size_response(size: DiagnosticMemorySize) -> MemoryAllocationSizeEntry {
    MemoryAllocationSizeEntry {
        wasm_pages: size.wasm_pages,
        bytes: size.bytes,
    }
}

const fn memory_allocation_state_response(state: AllocationState) -> MemoryAllocationState {
    match state {
        AllocationState::Reserved => MemoryAllocationState::Reserved,
        AllocationState::Active => MemoryAllocationState::Active,
        AllocationState::Retired { .. } => MemoryAllocationState::Retired,
    }
}

const fn allocation_retired_generation(state: AllocationState) -> Option<u64> {
    match state {
        AllocationState::Retired { generation } => Some(generation),
        AllocationState::Reserved | AllocationState::Active => None,
    }
}

const fn memory_schema_metadata_response(
    record: &SchemaMetadataRecord,
) -> MemorySchemaMetadataEntry {
    MemorySchemaMetadataEntry {
        generation: record.generation(),
        schema_version: record.schema().schema_version(),
        schema_fingerprint: None,
    }
}

fn memory_ledger_generation_response(
    generation: DiagnosticGeneration,
) -> MemoryLedgerGenerationEntry {
    let generation = generation.generation;
    MemoryLedgerGenerationEntry {
        generation: generation.generation(),
        parent_generation: Some(generation.parent_generation()),
        runtime_fingerprint: generation.runtime_fingerprint().map(str::to_string),
        declaration_count: generation.declaration_count(),
        committed_at: generation.committed_at(),
    }
}

const fn commit_slot_response(slot: CommitSlotDiagnostic) -> MemoryCommitSlotResponse {
    match slot {
        CommitSlotDiagnostic::Empty => MemoryCommitSlotResponse {
            present: false,
            generation: None,
            valid: false,
        },
        CommitSlotDiagnostic::Valid { generation } => MemoryCommitSlotResponse {
            present: true,
            generation: Some(generation),
            valid: true,
        },
        CommitSlotDiagnostic::Invalid { generation } => MemoryCommitSlotResponse {
            present: true,
            generation: Some(generation),
            valid: false,
        },
    }
}

const fn commit_recovery_error_response(
    err: CommitRecoveryError,
) -> MemoryCommitRecoveryErrorResponse {
    match err {
        CommitRecoveryError::NoValidGeneration => {
            MemoryCommitRecoveryErrorResponse::NoValidGeneration
        }
        CommitRecoveryError::InvalidCommitSlots { .. } => {
            MemoryCommitRecoveryErrorResponse::InvalidCommitSlots
        }
        CommitRecoveryError::AmbiguousGeneration { .. } => {
            MemoryCommitRecoveryErrorResponse::AmbiguousGeneration
        }
        CommitRecoveryError::GenerationOverflow { .. } => {
            MemoryCommitRecoveryErrorResponse::GenerationOverflow
        }
        CommitRecoveryError::UnexpectedGeneration { .. } => {
            MemoryCommitRecoveryErrorResponse::UnexpectedGeneration
        }
        _ => MemoryCommitRecoveryErrorResponse::Unknown,
    }
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use ic_memory::{
        AllocationDeclaration, AllocationHistory, AllocationLedger, AllocationSlotDescriptor,
        SchemaMetadata,
    };

    #[test]
    fn ledger_snapshot_reads_the_bootstrapped_ic_memory_runtime() {
        MemoryRegistryOps::init_registry().expect("bootstrap canonical memory runtime");

        let snapshot = MemoryRegistryOps::ledger_snapshot().expect("runtime diagnostic export");

        assert!(snapshot.current_generation > 0);
        assert!(
            snapshot
                .authorities
                .iter()
                .any(|authority| authority.owner == "canic-core")
        );
        assert!(
            snapshot
                .memories
                .iter()
                .any(|memory| memory.memory_manager_id >= 30)
        );
    }

    #[test]
    fn commit_slot_response_maps_ic_memory_012_variants_exactly() {
        assert_eq!(
            commit_slot_response(CommitSlotDiagnostic::Empty),
            MemoryCommitSlotResponse {
                present: false,
                generation: None,
                valid: false,
            }
        );
        assert_eq!(
            commit_slot_response(CommitSlotDiagnostic::Valid { generation: 7 }),
            MemoryCommitSlotResponse {
                present: true,
                generation: Some(7),
                valid: true,
            }
        );
        assert_eq!(
            commit_slot_response(CommitSlotDiagnostic::Invalid { generation: 8 }),
            MemoryCommitSlotResponse {
                present: true,
                generation: Some(8),
                valid: false,
            }
        );
    }

    #[test]
    fn commit_recovery_response_maps_invalid_slots_without_unknown_fallback() {
        let response = commit_recovery_response(Some(CommitStoreDiagnostic {
            slot0: CommitSlotDiagnostic::Invalid { generation: 3 },
            slot1: CommitSlotDiagnostic::Empty,
            recovery: Err(CommitRecoveryError::InvalidCommitSlots {
                slot0_invalid: true,
                slot1_invalid: false,
            }),
        }));

        assert_eq!(response.authoritative_generation, None);
        assert_eq!(
            response.recovery_error,
            Some(MemoryCommitRecoveryErrorResponse::InvalidCommitSlots)
        );
    }

    #[test]
    fn memory_allocation_record_response_includes_live_backing_memory_size() {
        let declaration = AllocationDeclaration::new(
            "app.users.v1",
            AllocationSlotDescriptor::memory_manager(100).expect("usable slot"),
            None,
            SchemaMetadata::default(),
        )
        .expect("declaration");
        let ledger = AllocationLedger::new_committed(0, AllocationHistory::default())
            .expect("genesis ledger")
            .stage_reservation_generation(&[declaration], None)
            .expect("reservation generation");
        let record = DiagnosticRecord {
            allocation: ledger.allocation_history().records()[0].clone(),
            memory_size: Some(DiagnosticMemorySize::from_wasm_pages(3)),
        };

        let response = memory_allocation_record_response(record);

        assert_eq!(
            response.memory_size,
            Some(MemoryAllocationSizeEntry {
                wasm_pages: 3,
                bytes: 196_608,
            })
        );
        assert_eq!(
            memory_ledger_memory_entry_response(&response),
            Some(MemoryLedgerMemoryEntry {
                memory_manager_id: 100,
                stable_key: "app.users.v1".to_string(),
                state: MemoryAllocationState::Reserved,
                size: MemoryAllocationSizeEntry {
                    wasm_pages: 3,
                    bytes: 196_608,
                },
            })
        );
    }
}