icydb-core 0.178.6

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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use crate::db::{
    data::DataStore,
    index::{IndexState, IndexStore},
    journal::JournalTailStore,
    schema::SchemaStore,
};
use candid::CandidType;
use serde::Deserialize;
use std::{cell::RefCell, thread::LocalKey};

///
/// StoreHandle
///
/// StoreHandle binds the row, index, and schema stores for one generated schema
/// `Store` path.
/// It is the stable access token passed across commit, recovery, executor, and
/// diagnostics boundaries instead of exposing registry internals directly.
///

#[derive(Clone, Copy, Debug)]
pub struct StoreHandle {
    data: &'static LocalKey<RefCell<DataStore>>,
    index: &'static LocalKey<RefCell<IndexStore>>,
    schema: &'static LocalKey<RefCell<SchemaStore>>,
    journal: Option<&'static LocalKey<RefCell<JournalTailStore>>>,
    allocations: StoreAllocationIdentities,
    capabilities: StoreRuntimeStorageCapabilities,
}

/// Diagnostic storage mode carried by a runtime storage capability descriptor.
///
/// Policy code should branch on capability axes instead of this display value.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreRuntimeStorageMode {
    /// Durable stable-memory storage.
    #[default]
    Stable,
    /// Volatile in-process heap storage.
    Heap,
    /// Journaled cached-stable durable storage.
    Journaled,
}

impl StoreRuntimeStorageMode {
    /// Return the user-facing storage mode label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Stable => "stable",
            Self::Heap => "heap",
            Self::Journaled => "journaled",
        }
    }
}

/// Whether a store owns durable allocation identity.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreAllocationIdentityCapability {
    /// Stable allocation identity is present.
    #[default]
    Present,
    /// Stable allocation identity is absent.
    Absent,
}

impl StoreAllocationIdentityCapability {
    /// Return the user-facing capability label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Present => "present",
            Self::Absent => "absent",
        }
    }
}

/// Store durability class.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreDurability {
    /// Store contents participate in durable storage semantics.
    #[default]
    Durable,
    /// Store contents are live-only and volatile.
    Volatile,
}

impl StoreDurability {
    /// Return the user-facing durability label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Durable => "durable",
            Self::Volatile => "volatile",
        }
    }
}

/// Store recovery capability.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreRecoveryCapability {
    /// Store contents can be recovered through stable commit replay.
    #[default]
    StableCommitReplay,
    /// Store contents can be recovered from canonical stable BTrees plus a
    /// committed journal tail.
    StableBasePlusJournalReplay,
    /// Store contents are not recovered.
    None,
}

impl StoreRecoveryCapability {
    /// Return the user-facing recovery label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::StableCommitReplay => "stable-replay",
            Self::StableBasePlusJournalReplay => "stable-base-plus-journal-replay",
            Self::None => "none",
        }
    }
}

/// Store commit participation class.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreCommitParticipation {
    /// Store mutations participate in the durable commit path.
    #[default]
    Durable,
    /// Store mutations are live-only side effects.
    LiveOnly,
}

impl StoreCommitParticipation {
    /// Return the user-facing commit-participation label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Durable => "durable",
            Self::LiveOnly => "live-only",
        }
    }
}

/// Store schema metadata persistence class.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreSchemaMetadataCapability {
    /// Schema metadata has durable accepted-history semantics.
    #[default]
    DurableAcceptedHistory,
    /// Schema metadata is rebuilt live and is not durable history.
    LiveRebuiltMetadata,
    /// Schema metadata is canonical stable history plus committed journal tail.
    CanonicalStableHistoryPlusJournalTail,
}

impl StoreSchemaMetadataCapability {
    /// Return the user-facing schema-metadata capability label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DurableAcceptedHistory => "durable-accepted-history",
            Self::LiveRebuiltMetadata => "live-rebuilt-metadata",
            Self::CanonicalStableHistoryPlusJournalTail => {
                "canonical-stable-history-plus-journal-tail"
            }
        }
    }
}

/// Strong relation source capability for a store.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreRelationSourceCapability {
    /// Source rows can own durable relation integrity.
    #[default]
    DurableSource,
    /// Source rows can participate in live relation validation.
    LiveSource,
}

/// Strong relation target capability for a store.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreRelationTargetCapability {
    /// Target rows can be referenced by durable source rows.
    #[default]
    DurableTarget,
    /// Target rows are volatile and cannot satisfy durable source integrity.
    VolatileTarget,
}

/// Whether the store can participate in live validation.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum StoreLiveValidationCapability {
    /// Live validation is supported.
    #[default]
    Supported,
}

/// Runtime storage capability descriptor carried by one registered store.
///
/// Capabilities describe storage policy. They are not allocation identity.
#[derive(CandidType, Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct StoreRuntimeStorageCapabilities {
    storage_mode: StoreRuntimeStorageMode,
    allocation_identity: StoreAllocationIdentityCapability,
    durability: StoreDurability,
    recovery: StoreRecoveryCapability,
    commit_participation: StoreCommitParticipation,
    schema_metadata: StoreSchemaMetadataCapability,
    relation_source: StoreRelationSourceCapability,
    relation_target: StoreRelationTargetCapability,
    live_validation: StoreLiveValidationCapability,
}

impl StoreRuntimeStorageCapabilities {
    /// Capability descriptor for stable-memory stores.
    #[must_use]
    pub const fn stable() -> Self {
        Self {
            storage_mode: StoreRuntimeStorageMode::Stable,
            allocation_identity: StoreAllocationIdentityCapability::Present,
            durability: StoreDurability::Durable,
            recovery: StoreRecoveryCapability::StableCommitReplay,
            commit_participation: StoreCommitParticipation::Durable,
            schema_metadata: StoreSchemaMetadataCapability::DurableAcceptedHistory,
            relation_source: StoreRelationSourceCapability::DurableSource,
            relation_target: StoreRelationTargetCapability::DurableTarget,
            live_validation: StoreLiveValidationCapability::Supported,
        }
    }

    /// Capability descriptor for heap stores.
    #[must_use]
    pub const fn heap() -> Self {
        Self {
            storage_mode: StoreRuntimeStorageMode::Heap,
            allocation_identity: StoreAllocationIdentityCapability::Absent,
            durability: StoreDurability::Volatile,
            recovery: StoreRecoveryCapability::None,
            commit_participation: StoreCommitParticipation::LiveOnly,
            schema_metadata: StoreSchemaMetadataCapability::LiveRebuiltMetadata,
            relation_source: StoreRelationSourceCapability::LiveSource,
            relation_target: StoreRelationTargetCapability::VolatileTarget,
            live_validation: StoreLiveValidationCapability::Supported,
        }
    }

    /// Capability descriptor for journaled cached-stable stores.
    #[must_use]
    pub const fn journaled() -> Self {
        Self {
            storage_mode: StoreRuntimeStorageMode::Journaled,
            allocation_identity: StoreAllocationIdentityCapability::Present,
            durability: StoreDurability::Durable,
            recovery: StoreRecoveryCapability::StableBasePlusJournalReplay,
            commit_participation: StoreCommitParticipation::Durable,
            schema_metadata: StoreSchemaMetadataCapability::CanonicalStableHistoryPlusJournalTail,
            relation_source: StoreRelationSourceCapability::DurableSource,
            relation_target: StoreRelationTargetCapability::DurableTarget,
            live_validation: StoreLiveValidationCapability::Supported,
        }
    }

    /// Diagnostic storage mode. Policy code should use the capability axes.
    #[must_use]
    pub const fn storage_mode(self) -> StoreRuntimeStorageMode {
        self.storage_mode
    }

    /// Allocation identity capability.
    #[must_use]
    pub const fn allocation_identity(self) -> StoreAllocationIdentityCapability {
        self.allocation_identity
    }

    /// Durability capability.
    #[must_use]
    pub const fn durability(self) -> StoreDurability {
        self.durability
    }

    /// Recovery capability.
    #[must_use]
    pub const fn recovery(self) -> StoreRecoveryCapability {
        self.recovery
    }

    /// Commit participation capability.
    #[must_use]
    pub const fn commit_participation(self) -> StoreCommitParticipation {
        self.commit_participation
    }

    /// Schema metadata persistence capability.
    #[must_use]
    pub const fn schema_metadata(self) -> StoreSchemaMetadataCapability {
        self.schema_metadata
    }

    /// Relation source capability.
    #[must_use]
    pub const fn relation_source(self) -> StoreRelationSourceCapability {
        self.relation_source
    }

    /// Relation target capability.
    #[must_use]
    pub const fn relation_target(self) -> StoreRelationTargetCapability {
        self.relation_target
    }

    /// Live validation capability.
    #[must_use]
    pub const fn live_validation(self) -> StoreLiveValidationCapability {
        self.live_validation
    }
}

///
/// StoreAllocationIdentity
///
/// Durable allocation identity for one physical stable-memory role.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StoreAllocationIdentity {
    memory_id: u8,
    stable_key: &'static str,
}

impl StoreAllocationIdentity {
    /// Build one stable allocation identity descriptor.
    #[must_use]
    pub const fn new(memory_id: u8, stable_key: &'static str) -> Self {
        Self {
            memory_id,
            stable_key,
        }
    }

    /// 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) -> &'static str {
        self.stable_key
    }
}

///
/// StoreAllocationIdentities
///
/// Durable allocation identities for one logical store's data, index, and
/// schema memories.
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct StoreAllocationIdentities {
    data: Option<StoreAllocationIdentity>,
    index: Option<StoreAllocationIdentity>,
    schema: Option<StoreAllocationIdentity>,
    journal: Option<StoreAllocationIdentity>,
}

impl StoreAllocationIdentities {
    /// Build an absent allocation identity bundle.
    #[must_use]
    pub const fn absent() -> Self {
        Self {
            data: None,
            index: None,
            schema: None,
            journal: None,
        }
    }

    /// Build one allocation identity bundle.
    #[must_use]
    pub const fn new(
        data: StoreAllocationIdentity,
        index: StoreAllocationIdentity,
        schema: StoreAllocationIdentity,
    ) -> Self {
        Self {
            data: Some(data),
            index: Some(index),
            schema: Some(schema),
            journal: None,
        }
    }

    /// Build one journaled cached-stable allocation identity bundle.
    #[must_use]
    pub const fn new_journaled(
        data: StoreAllocationIdentity,
        index: StoreAllocationIdentity,
        schema: StoreAllocationIdentity,
        journal: StoreAllocationIdentity,
    ) -> Self {
        Self {
            data: Some(data),
            index: Some(index),
            schema: Some(schema),
            journal: Some(journal),
        }
    }

    /// Return data-memory allocation identity.
    #[must_use]
    pub const fn data(self) -> Option<StoreAllocationIdentity> {
        self.data
    }

    /// Return index-memory allocation identity.
    #[must_use]
    pub const fn index(self) -> Option<StoreAllocationIdentity> {
        self.index
    }

    /// Return schema-memory allocation identity.
    #[must_use]
    pub const fn schema(self) -> Option<StoreAllocationIdentity> {
        self.schema
    }

    /// Return journal-tail allocation identity.
    #[must_use]
    pub const fn journal(self) -> Option<StoreAllocationIdentity> {
        self.journal
    }

    /// Return the allocation capability represented by this triplet, or
    /// `None` if the triplet is partially populated and therefore invalid.
    #[must_use]
    pub const fn allocation_identity_capability(self) -> Option<StoreAllocationIdentityCapability> {
        match (self.data, self.index, self.schema) {
            (Some(_), Some(_), Some(_)) => Some(StoreAllocationIdentityCapability::Present),
            (None, None, None) if self.journal.is_none() => {
                Some(StoreAllocationIdentityCapability::Absent)
            }
            _ => None,
        }
    }

    /// Return whether this allocation shape matches the concrete storage
    /// capability descriptor.
    #[must_use]
    pub const fn matches_storage_capabilities(
        self,
        capabilities: StoreRuntimeStorageCapabilities,
    ) -> bool {
        match capabilities.storage_mode() {
            StoreRuntimeStorageMode::Stable => {
                self.data.is_some()
                    && self.index.is_some()
                    && self.schema.is_some()
                    && self.journal.is_none()
            }
            StoreRuntimeStorageMode::Heap => {
                self.data.is_none()
                    && self.index.is_none()
                    && self.schema.is_none()
                    && self.journal.is_none()
            }
            StoreRuntimeStorageMode::Journaled => {
                self.data.is_some()
                    && self.index.is_some()
                    && self.schema.is_some()
                    && self.journal.is_some()
            }
        }
    }
}

impl StoreHandle {
    /// Build a store handle with an explicit allocation identity decision.
    #[must_use]
    pub const fn new(
        data: &'static LocalKey<RefCell<DataStore>>,
        index: &'static LocalKey<RefCell<IndexStore>>,
        schema: &'static LocalKey<RefCell<SchemaStore>>,
        allocations: StoreAllocationIdentities,
        capabilities: StoreRuntimeStorageCapabilities,
    ) -> Self {
        Self {
            data,
            index,
            schema,
            journal: None,
            allocations,
            capabilities,
        }
    }

    /// Build a journaled store handle with an explicit journal-tail store.
    #[must_use]
    pub const fn new_journaled(
        data: &'static LocalKey<RefCell<DataStore>>,
        index: &'static LocalKey<RefCell<IndexStore>>,
        schema: &'static LocalKey<RefCell<SchemaStore>>,
        journal: &'static LocalKey<RefCell<JournalTailStore>>,
        allocations: StoreAllocationIdentities,
        capabilities: StoreRuntimeStorageCapabilities,
    ) -> Self {
        Self {
            data,
            index,
            schema,
            journal: Some(journal),
            allocations,
            capabilities,
        }
    }

    /// Borrow the row store immutably.
    pub fn with_data<R>(&self, f: impl FnOnce(&DataStore) -> R) -> R {
        #[cfg(feature = "diagnostics")]
        {
            crate::db::physical_access::measure_physical_access_operation(|| {
                self.data.with_borrow(f)
            })
        }

        #[cfg(not(feature = "diagnostics"))]
        {
            self.data.with_borrow(f)
        }
    }

    /// Borrow the row store mutably.
    pub fn with_data_mut<R>(&self, f: impl FnOnce(&mut DataStore) -> R) -> R {
        self.data.with_borrow_mut(f)
    }

    /// Borrow the index store immutably.
    pub fn with_index<R>(&self, f: impl FnOnce(&IndexStore) -> R) -> R {
        #[cfg(feature = "diagnostics")]
        {
            crate::db::physical_access::measure_physical_access_operation(|| {
                self.index.with_borrow(f)
            })
        }

        #[cfg(not(feature = "diagnostics"))]
        {
            self.index.with_borrow(f)
        }
    }

    /// Borrow the index store mutably.
    pub fn with_index_mut<R>(&self, f: impl FnOnce(&mut IndexStore) -> R) -> R {
        self.index.with_borrow_mut(f)
    }

    /// Borrow the schema store immutably.
    pub fn with_schema<R>(&self, f: impl FnOnce(&SchemaStore) -> R) -> R {
        self.schema.with_borrow(f)
    }

    /// Borrow the schema store mutably.
    pub fn with_schema_mut<R>(&self, f: impl FnOnce(&mut SchemaStore) -> R) -> R {
        self.schema.with_borrow_mut(f)
    }

    /// Return the explicit lifecycle state of the bound index store.
    #[must_use]
    pub(in crate::db) fn index_state(&self) -> IndexState {
        self.with_index(IndexStore::state)
    }

    /// Mark the bound index store as Building.
    pub(in crate::db) fn mark_index_building(&self) {
        self.with_index_mut(IndexStore::mark_building);
    }

    /// Mark the bound index store as Ready.
    pub(in crate::db) fn mark_index_ready(&self) {
        self.with_index_mut(IndexStore::mark_ready);
    }

    /// Return the raw row-store accessor.
    #[must_use]
    pub const fn data_store(&self) -> &'static LocalKey<RefCell<DataStore>> {
        self.data
    }

    /// Return the raw index-store accessor.
    #[must_use]
    pub const fn index_store(&self) -> &'static LocalKey<RefCell<IndexStore>> {
        self.index
    }

    /// Return the raw schema-store accessor.
    #[must_use]
    pub const fn schema_store(&self) -> &'static LocalKey<RefCell<SchemaStore>> {
        self.schema
    }

    /// Return the raw journal-tail store accessor when this store is journaled.
    #[must_use]
    pub const fn journal_tail_store(&self) -> Option<&'static LocalKey<RefCell<JournalTailStore>>> {
        self.journal
    }

    /// Return the data-memory allocation identity when generated wiring
    /// supplied it.
    #[must_use]
    pub const fn data_allocation(&self) -> Option<StoreAllocationIdentity> {
        self.allocations.data()
    }

    /// Return the index-memory allocation identity when generated wiring
    /// supplied it.
    #[must_use]
    pub const fn index_allocation(&self) -> Option<StoreAllocationIdentity> {
        self.allocations.index()
    }

    /// Return the schema-memory allocation identity when generated wiring
    /// supplied it.
    #[must_use]
    pub const fn schema_allocation(&self) -> Option<StoreAllocationIdentity> {
        self.allocations.schema()
    }

    /// Return the journal-tail allocation identity when generated wiring
    /// supplied it.
    #[must_use]
    pub const fn journal_allocation(&self) -> Option<StoreAllocationIdentity> {
        self.allocations.journal()
    }

    /// Return this store's explicit runtime storage capabilities.
    #[must_use]
    pub const fn storage_capabilities(&self) -> StoreRuntimeStorageCapabilities {
        self.capabilities
    }
}