icydb-schema 0.165.2

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use crate::node::{
    validate_app_memory_id, validate_memory_id_in_range, validate_memory_id_not_reserved,
    validate_stable_key, validate_stable_key_segment,
};
use crate::prelude::*;

///
/// Store
///
/// Schema node describing stable IC BTreeMap memories that store:
/// - primary entity data
/// - all index data for that entity
/// - persisted schema metadata for that store
///

#[derive(Clone, Debug, Serialize)]
pub struct Store {
    def: Def,
    ident: &'static str,
    name: &'static str,
    canister: &'static str,
    data_memory_id: u8,
    index_memory_id: u8,
    schema_memory_id: u8,
}

impl Store {
    #[must_use]
    pub const fn new(
        def: Def,
        ident: &'static str,
        store_name: &'static str,
        canister: &'static str,
        data_memory_id: u8,
        index_memory_id: u8,
        schema_memory_id: u8,
    ) -> Self {
        Self {
            def,
            ident,
            name: store_name,
            canister,
            data_memory_id,
            index_memory_id,
            schema_memory_id,
        }
    }

    #[must_use]
    pub const fn def(&self) -> &Def {
        &self.def
    }

    #[must_use]
    pub const fn ident(&self) -> &'static str {
        self.ident
    }

    #[must_use]
    pub const fn store_name(&self) -> &'static str {
        self.name
    }

    #[must_use]
    pub const fn canister(&self) -> &'static str {
        self.canister
    }

    #[must_use]
    pub const fn data_memory_id(&self) -> u8 {
        self.data_memory_id
    }

    #[must_use]
    pub const fn index_memory_id(&self) -> u8 {
        self.index_memory_id
    }

    #[must_use]
    pub const fn schema_memory_id(&self) -> u8 {
        self.schema_memory_id
    }

    #[must_use]
    pub fn data_allocation(&self, memory_namespace: &str) -> StableMemoryAllocation {
        self.allocation(memory_namespace, StoreMemoryRole::Data)
    }

    /// Build the data-memory allocation descriptor with accepted row-layout
    /// schema metadata attached for diagnostics.
    #[must_use]
    pub fn data_allocation_with_schema_metadata(
        &self,
        memory_namespace: &str,
        schema_metadata: StableMemoryAllocationMetadata,
    ) -> StableMemoryAllocation {
        self.allocation_with_schema_metadata(
            memory_namespace,
            StoreMemoryRole::Data,
            schema_metadata,
        )
    }

    #[must_use]
    pub fn index_allocation(&self, memory_namespace: &str) -> StableMemoryAllocation {
        self.allocation(memory_namespace, StoreMemoryRole::Index)
    }

    /// Build the index-memory allocation descriptor with accepted index-catalog
    /// schema metadata attached for diagnostics.
    #[must_use]
    pub fn index_allocation_with_schema_metadata(
        &self,
        memory_namespace: &str,
        schema_metadata: StableMemoryAllocationMetadata,
    ) -> StableMemoryAllocation {
        self.allocation_with_schema_metadata(
            memory_namespace,
            StoreMemoryRole::Index,
            schema_metadata,
        )
    }

    #[must_use]
    pub fn schema_allocation(&self, memory_namespace: &str) -> StableMemoryAllocation {
        self.allocation(memory_namespace, StoreMemoryRole::Schema)
    }

    /// Build the schema-memory allocation descriptor with accepted catalog
    /// schema metadata attached for diagnostics.
    #[must_use]
    pub fn schema_allocation_with_schema_metadata(
        &self,
        memory_namespace: &str,
        schema_metadata: StableMemoryAllocationMetadata,
    ) -> StableMemoryAllocation {
        self.allocation_with_schema_metadata(
            memory_namespace,
            StoreMemoryRole::Schema,
            schema_metadata,
        )
    }

    #[must_use]
    pub fn allocation(
        &self,
        memory_namespace: &str,
        role: StoreMemoryRole,
    ) -> StableMemoryAllocation {
        let memory_id = match role {
            StoreMemoryRole::Data => self.data_memory_id,
            StoreMemoryRole::Index => self.index_memory_id,
            StoreMemoryRole::Schema => self.schema_memory_id,
        };

        StableMemoryAllocation::without_schema_metadata(
            memory_id,
            stable_memory_key(memory_namespace, self.store_name(), role.as_str()),
        )
    }

    fn allocation_with_schema_metadata(
        &self,
        memory_namespace: &str,
        role: StoreMemoryRole,
        schema_metadata: StableMemoryAllocationMetadata,
    ) -> StableMemoryAllocation {
        let memory_id = match role {
            StoreMemoryRole::Data => self.data_memory_id,
            StoreMemoryRole::Index => self.index_memory_id,
            StoreMemoryRole::Schema => self.schema_memory_id,
        };

        StableMemoryAllocation::with_schema_metadata(
            memory_id,
            stable_memory_key(memory_namespace, self.store_name(), role.as_str()),
            schema_metadata,
        )
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StoreMemoryRole {
    Data,
    Index,
    Schema,
}

impl StoreMemoryRole {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Data => "data",
            Self::Index => "index",
            Self::Schema => "schema",
        }
    }
}

/// Diagnostic schema metadata associated with a stable-memory allocation.
///
/// This metadata does not participate in durable allocation identity. The
/// durable identity remains `memory_id + stable_key`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StableMemoryAllocationMetadata {
    schema_version: Option<u32>,
    schema_fingerprint: Option<String>,
}

impl StableMemoryAllocationMetadata {
    const fn new(schema_version: Option<u32>, schema_fingerprint: Option<String>) -> Self {
        Self {
            schema_version,
            schema_fingerprint,
        }
    }

    /// Build allocation metadata from an accepted schema/catalog authority.
    #[must_use]
    pub const fn from_accepted_schema_contract(
        schema_version: u32,
        schema_fingerprint: String,
    ) -> Self {
        Self::new(Some(schema_version), Some(schema_fingerprint))
    }

    /// Build absent allocation metadata for allocations with no accepted
    /// schema/catalog authority.
    #[must_use]
    pub const fn absent() -> Self {
        Self::new(None, None)
    }

    /// Accepted schema/catalog version, when known.
    #[must_use]
    pub const fn schema_version(&self) -> Option<u32> {
        self.schema_version
    }

    /// Accepted schema/catalog fingerprint, when known.
    #[must_use]
    pub const fn schema_fingerprint(&self) -> Option<&str> {
        match &self.schema_fingerprint {
            Some(value) => Some(value.as_str()),
            None => None,
        }
    }
}

/// Stable-memory allocation descriptor.
///
/// `memory_id + stable_key` is the durable allocation identity.
/// `schema_version + schema_fingerprint` is diagnostic metadata only.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StableMemoryAllocation {
    memory_id: u8,
    stable_key: String,
    schema_metadata: StableMemoryAllocationMetadata,
}

impl StableMemoryAllocation {
    /// Build an allocation descriptor without schema metadata.
    #[must_use]
    pub const fn without_schema_metadata(memory_id: u8, stable_key: String) -> Self {
        Self::with_schema_metadata(
            memory_id,
            stable_key,
            StableMemoryAllocationMetadata::absent(),
        )
    }

    /// Build an allocation descriptor with diagnostic schema metadata.
    ///
    /// The metadata must come from accepted schema/catalog authority. Generated
    /// model fallback metadata is not an allocation metadata authority.
    #[must_use]
    pub const fn with_schema_metadata(
        memory_id: u8,
        stable_key: String,
        schema_metadata: StableMemoryAllocationMetadata,
    ) -> Self {
        Self {
            memory_id,
            stable_key,
            schema_metadata,
        }
    }

    /// Stable-memory manager ID.
    #[must_use]
    pub const fn memory_id(&self) -> u8 {
        self.memory_id
    }

    /// Durable stable-memory key.
    #[must_use]
    pub const fn stable_key(&self) -> &str {
        self.stable_key.as_str()
    }

    /// Diagnostic schema/catalog metadata.
    #[must_use]
    pub const fn schema_metadata(&self) -> &StableMemoryAllocationMetadata {
        &self.schema_metadata
    }

    /// Accepted schema/catalog version, when known.
    #[must_use]
    pub const fn schema_version(&self) -> Option<u32> {
        self.schema_metadata.schema_version()
    }

    /// Accepted schema/catalog fingerprint, when known.
    #[must_use]
    pub const fn schema_fingerprint(&self) -> Option<&str> {
        self.schema_metadata.schema_fingerprint()
    }

    /// Compare durable allocation identity only.
    ///
    /// Schema metadata is intentionally ignored because metadata changes are
    /// diagnostics, not memory replacement.
    #[must_use]
    pub fn same_identity_as(&self, other: &Self) -> bool {
        self.memory_id == other.memory_id && self.stable_key == other.stable_key
    }
}

#[must_use]
pub fn stable_memory_key(memory_namespace: &str, store_name: &str, role: &str) -> String {
    format!("icydb.{memory_namespace}.{store_name}.{role}.v1")
}

impl MacroNode for Store {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ValidateNode for Store {
    fn validate(&self) -> Result<(), ErrorTree> {
        let mut errs = ErrorTree::new();
        let schema = schema_read();

        match schema.cast_node::<Canister>(self.canister()) {
            Ok(canister) => {
                validate_stable_key_segment(&mut errs, "store store_name", self.store_name());

                // Validate data memory ID
                validate_memory_id_in_range(
                    &mut errs,
                    "data_memory_id",
                    self.data_memory_id(),
                    canister.memory_min(),
                    canister.memory_max(),
                );
                validate_app_memory_id(&mut errs, "data_memory_id", self.data_memory_id());
                validate_memory_id_not_reserved(&mut errs, "data_memory_id", self.data_memory_id());
                validate_stable_key(
                    &mut errs,
                    "data stable key",
                    self.data_allocation(canister.memory_namespace())
                        .stable_key(),
                );

                // Validate index memory ID
                validate_memory_id_in_range(
                    &mut errs,
                    "index_memory_id",
                    self.index_memory_id(),
                    canister.memory_min(),
                    canister.memory_max(),
                );
                validate_app_memory_id(&mut errs, "index_memory_id", self.index_memory_id());
                validate_memory_id_not_reserved(
                    &mut errs,
                    "index_memory_id",
                    self.index_memory_id(),
                );
                validate_stable_key(
                    &mut errs,
                    "index stable key",
                    self.index_allocation(canister.memory_namespace())
                        .stable_key(),
                );

                // Validate schema memory ID
                validate_memory_id_in_range(
                    &mut errs,
                    "schema_memory_id",
                    self.schema_memory_id(),
                    canister.memory_min(),
                    canister.memory_max(),
                );
                validate_app_memory_id(&mut errs, "schema_memory_id", self.schema_memory_id());
                validate_memory_id_not_reserved(
                    &mut errs,
                    "schema_memory_id",
                    self.schema_memory_id(),
                );
                validate_stable_key(
                    &mut errs,
                    "schema stable key",
                    self.schema_allocation(canister.memory_namespace())
                        .stable_key(),
                );

                // Ensure the per-store memories are distinct.
                if self.data_memory_id() == self.index_memory_id() {
                    err!(
                        errs,
                        "data_memory_id and index_memory_id must differ (both are {})",
                        self.data_memory_id(),
                    );
                }
                if self.data_memory_id() == self.schema_memory_id() {
                    err!(
                        errs,
                        "data_memory_id and schema_memory_id must differ (both are {})",
                        self.data_memory_id(),
                    );
                }
                if self.index_memory_id() == self.schema_memory_id() {
                    err!(
                        errs,
                        "index_memory_id and schema_memory_id must differ (both are {})",
                        self.index_memory_id(),
                    );
                }
            }
            Err(e) => errs.add(e),
        }

        errs.result()
    }
}

impl VisitableNode for Store {
    fn route_key(&self) -> String {
        self.def().path()
    }

    fn drive<V: Visitor>(&self, v: &mut V) {
        self.def().accept(v);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn store_stable_keys_use_durable_icydb_shape() {
        let store = Store::new(
            Def::new("demo::rpg", "CharacterStore"),
            "CHARACTER_STORE",
            "characters",
            "demo::rpg::Canister",
            110,
            111,
            112,
        );

        assert_eq!(
            store.data_allocation("demo_rpg").stable_key(),
            "icydb.demo_rpg.characters.data.v1",
        );
        assert_eq!(
            store.index_allocation("demo_rpg").stable_key(),
            "icydb.demo_rpg.characters.index.v1",
        );
        assert_eq!(
            store.schema_allocation("demo_rpg").stable_key(),
            "icydb.demo_rpg.characters.schema.v1",
        );
    }

    #[test]
    fn store_allocations_default_to_absent_schema_metadata() {
        let store = Store::new(
            Def::new("demo::rpg", "CharacterStore"),
            "CHARACTER_STORE",
            "characters",
            "demo::rpg::Canister",
            110,
            111,
            112,
        );

        for allocation in [
            store.data_allocation("demo_rpg"),
            store.index_allocation("demo_rpg"),
            store.schema_allocation("demo_rpg"),
        ] {
            assert_eq!(allocation.schema_version(), None);
            assert_eq!(allocation.schema_fingerprint(), None);
            assert_eq!(
                allocation.schema_metadata(),
                &StableMemoryAllocationMetadata::absent()
            );
        }
    }

    #[test]
    fn allocation_metadata_is_role_specific_and_diagnostic_only() {
        let store = Store::new(
            Def::new("demo::rpg", "CharacterStore"),
            "CHARACTER_STORE",
            "characters",
            "demo::rpg::Canister",
            110,
            111,
            112,
        );
        let data = store.data_allocation_with_schema_metadata(
            "demo_rpg",
            StableMemoryAllocationMetadata::from_accepted_schema_contract(
                7,
                "data-row-layout".to_string(),
            ),
        );
        let index = store.index_allocation_with_schema_metadata(
            "demo_rpg",
            StableMemoryAllocationMetadata::from_accepted_schema_contract(
                8,
                "index-catalog".to_string(),
            ),
        );
        let schema = store.schema_allocation_with_schema_metadata(
            "demo_rpg",
            StableMemoryAllocationMetadata::from_accepted_schema_contract(
                10,
                "schema-catalog".to_string(),
            ),
        );
        let data_after_reconcile = store.data_allocation_with_schema_metadata(
            "demo_rpg",
            StableMemoryAllocationMetadata::from_accepted_schema_contract(
                9,
                "data-row-layout-v2".to_string(),
            ),
        );

        assert_eq!(data.schema_version(), Some(7));
        assert_eq!(data.schema_fingerprint(), Some("data-row-layout"));
        assert_eq!(index.schema_version(), Some(8));
        assert_eq!(index.schema_fingerprint(), Some("index-catalog"));
        assert_eq!(schema.schema_version(), Some(10));
        assert_eq!(schema.schema_fingerprint(), Some("schema-catalog"));
        assert!(data.same_identity_as(&data_after_reconcile));
        assert!(!data.same_identity_as(&index));
        assert!(!data.same_identity_as(&schema));
    }
}