icydb-core 0.213.33

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
//! Module: db::schema::composite_catalog
//! Responsibility: canonicalize source or generated composite proposals into ID-backed accepted definitions.
//! Does not own: generated codecs, enum definitions, or accepted-schema publication.
//! Boundary: exact source/generated composite shapes -> store-local composite catalog candidate.

mod codec;
use crate::{
    db::schema::{
        AcceptedFieldKind, MAX_ACCEPTED_RECURSIVE_DEPTH, enum_catalog::AcceptedEnumCatalog,
    },
    model::field::CompositeCodec,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    num::NonZeroU32,
};

pub(in crate::db::schema) use codec::{
    decode_accepted_composite_catalog, encode_accepted_composite_catalog,
};

///
/// CompositeTypeId
///
/// Stable non-zero identity owned by one store-local accepted composite
/// catalog.
///

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct CompositeTypeId(NonZeroU32);

impl CompositeTypeId {
    #[must_use]
    pub(in crate::db) const fn new(value: u32) -> Option<Self> {
        match NonZeroU32::new(value) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }

    #[must_use]
    pub(in crate::db) const fn get(self) -> u32 {
        self.0.get()
    }
}

///
/// CompositeFieldId
///
/// Stable non-zero member identity owned by one accepted record composite.
///

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct CompositeFieldId(NonZeroU32);

impl CompositeFieldId {
    #[must_use]
    pub(in crate::db) const fn new(value: u32) -> Option<Self> {
        match NonZeroU32::new(value) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }

    #[must_use]
    pub(in crate::db) const fn get(self) -> u32 {
        self.0.get()
    }
}

///
/// AcceptedCompositeCatalog
///
/// Canonical nominal composite definitions owned by one accepted store
/// revision.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct AcceptedCompositeCatalog {
    by_id: BTreeMap<CompositeTypeId, AcceptedCompositeType>,
    id_by_path: BTreeMap<String, CompositeTypeId>,
}

impl AcceptedCompositeCatalog {
    #[cfg(test)]
    #[must_use]
    pub(in crate::db) const fn empty() -> Self {
        Self {
            by_id: BTreeMap::new(),
            id_by_path: BTreeMap::new(),
        }
    }

    /// Construct one initial composite catalog from already allocated
    /// store-local identities and canonical shapes.
    pub(in crate::db::schema) fn from_initial_definitions(
        definitions: BTreeMap<CompositeTypeId, (String, AcceptedCompositeShape)>,
        enum_catalog: &AcceptedEnumCatalog,
    ) -> Result<Self, CompositeCatalogBuildError> {
        let mut by_id = BTreeMap::new();
        let mut id_by_path = BTreeMap::new();
        for (type_id, (path, shape)) in definitions {
            if path.is_empty() || id_by_path.insert(path.clone(), type_id).is_some() {
                return Err(CompositeCatalogBuildError::FieldKindResolution);
            }
            by_id.insert(
                type_id,
                AcceptedCompositeType {
                    path,
                    codec: CompositeCodec::StructuralV1,
                    shape,
                },
            );
        }
        let catalog = Self { by_id, id_by_path };
        if !catalog.validate(enum_catalog) {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        Ok(catalog)
    }

    /// Re-declare an editable composite path under one accepted ID.
    ///
    /// Record member names are part of canonical record values and are not
    /// metadata-only. The full shape and structural codec therefore remain
    /// exact while only the nominal type path changes.
    pub(in crate::db::schema) fn with_redeclared_path(
        mut self,
        type_id: CompositeTypeId,
        path: String,
        enum_catalog: &AcceptedEnumCatalog,
    ) -> Result<Self, CompositeCatalogBuildError> {
        let accepted = self
            .by_id
            .get(&type_id)
            .ok_or(CompositeCatalogBuildError::FieldKindResolution)?;
        if path.is_empty() {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        let old_path = accepted.path.clone();
        let codec = accepted.codec;
        let shape = accepted.shape.clone();
        self.id_by_path.remove(old_path.as_str());
        if self.id_by_path.insert(path.clone(), type_id).is_some() {
            return Err(CompositeCatalogBuildError::ConflictingDefinition { path });
        }
        self.by_id
            .insert(type_id, AcceptedCompositeType { path, codec, shape });
        if !self.validate(enum_catalog) {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        Ok(self)
    }

    /// Re-declare one record's editable path and member names.
    ///
    /// Stable member IDs and their accepted contracts must remain exact. The
    /// application boundary separately proves that no persisted row or
    /// derived key can still contain the previous canonical member names.
    pub(in crate::db::schema) fn with_redeclared_record_metadata(
        mut self,
        type_id: CompositeTypeId,
        path: String,
        fields: Vec<AcceptedCompositeField>,
        enum_catalog: &AcceptedEnumCatalog,
    ) -> Result<Self, CompositeCatalogBuildError> {
        if path.is_empty() {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        let accepted = self
            .by_id
            .get(&type_id)
            .ok_or(CompositeCatalogBuildError::FieldKindResolution)?;
        let AcceptedCompositeShape::Record(accepted_fields) = &accepted.shape else {
            return Err(CompositeCatalogBuildError::ExistingTypeContractChanged { path });
        };
        if accepted_fields.len() != fields.len()
            || accepted_fields.iter().any(|accepted_field| {
                fields.iter().all(|candidate_field| {
                    candidate_field.id != accepted_field.id
                        || candidate_field.contract != accepted_field.contract
                })
            })
        {
            return Err(CompositeCatalogBuildError::ExistingTypeContractChanged { path });
        }

        let old_path = accepted.path.clone();
        let codec = accepted.codec;
        self.id_by_path.remove(old_path.as_str());
        if self.id_by_path.insert(path.clone(), type_id).is_some() {
            return Err(CompositeCatalogBuildError::ConflictingDefinition { path });
        }
        self.by_id.insert(
            type_id,
            AcceptedCompositeType {
                path,
                codec,
                shape: AcceptedCompositeShape::Record(fields),
            },
        );
        if !self.validate(enum_catalog) {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        Ok(self)
    }

    /// Remove one exact accepted composite definition.
    ///
    /// Validation rejects retained composite definitions that still refer to
    /// the removed identity. Entity-field closure remains owned by the
    /// accepted revision bundle.
    pub(in crate::db::schema) fn with_removed_type(
        mut self,
        type_id: CompositeTypeId,
        enum_catalog: &AcceptedEnumCatalog,
    ) -> Result<Self, CompositeCatalogBuildError> {
        let definition = self
            .by_id
            .remove(&type_id)
            .ok_or(CompositeCatalogBuildError::FieldKindResolution)?;
        if self.id_by_path.remove(definition.path.as_str()) != Some(type_id)
            || !self.validate(enum_catalog)
        {
            return Err(CompositeCatalogBuildError::FieldKindResolution);
        }
        Ok(self)
    }

    #[must_use]
    #[cfg(test)]
    pub(in crate::db) fn type_id(&self, path: &str) -> Option<CompositeTypeId> {
        self.id_by_path.get(path).copied()
    }

    #[must_use]
    pub(in crate::db::schema) const fn id_by_path(&self) -> &BTreeMap<String, CompositeTypeId> {
        &self.id_by_path
    }

    #[must_use]
    pub(in crate::db::schema) fn composite_type(
        &self,
        id: CompositeTypeId,
    ) -> Option<&AcceptedCompositeType> {
        self.by_id.get(&id)
    }

    #[must_use]
    pub(in crate::db::schema) fn matches_kind(
        &self,
        enum_catalog: &AcceptedEnumCatalog,
        kind: &AcceptedFieldKind,
    ) -> bool {
        self.matches_kind_at_depth(enum_catalog, kind, 0)
    }

    fn matches_kind_at_depth(
        &self,
        enum_catalog: &AcceptedEnumCatalog,
        kind: &AcceptedFieldKind,
        depth: usize,
    ) -> bool {
        if depth >= MAX_ACCEPTED_RECURSIVE_DEPTH {
            return false;
        }
        let nested_depth = depth.saturating_add(1);
        match kind {
            AcceptedFieldKind::Composite { type_id } => self.by_id.contains_key(type_id),
            AcceptedFieldKind::Relation { key_kind, .. }
            | AcceptedFieldKind::List(key_kind)
            | AcceptedFieldKind::Set(key_kind) => {
                self.matches_kind_at_depth(enum_catalog, key_kind, nested_depth)
            }
            AcceptedFieldKind::Map { key, value } => {
                self.matches_kind_at_depth(enum_catalog, key, nested_depth)
                    && self.matches_kind_at_depth(enum_catalog, value, nested_depth)
            }
            _ => enum_catalog.matches_accepted_kind(kind),
        }
    }

    pub(in crate::db::schema) fn validate(&self, enum_catalog: &AcceptedEnumCatalog) -> bool {
        self.by_id.len() == self.id_by_path.len()
            && enum_catalog.composite_references_are_resolved(self)
            && self.id_by_path.iter().all(|(path, type_id)| {
                self.by_id
                    .get(type_id)
                    .is_some_and(|definition| definition.path == *path)
            })
            && self.by_id.iter().all(|(type_id, definition)| {
                self.id_by_path.get(definition.path.as_str()) == Some(type_id)
                    && definition.validate(self, enum_catalog)
            })
            && self.contract_graph_is_acyclic(enum_catalog)
    }

    fn contract_graph_is_acyclic(&self, enum_catalog: &AcceptedEnumCatalog) -> bool {
        let mut visited = BTreeSet::new();
        let mut active = BTreeSet::new();
        self.by_id.keys().copied().all(|type_id| {
            validate_composite_type_graph(self, enum_catalog, type_id, &mut visited, &mut active, 0)
        })
    }
}

///
/// AcceptedCompositeType
///
/// One exact nominal composite definition owned by accepted schema.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::schema) struct AcceptedCompositeType {
    path: String,
    codec: CompositeCodec,
    shape: AcceptedCompositeShape,
}

impl AcceptedCompositeType {
    #[must_use]
    pub(in crate::db::schema) const fn path(&self) -> &str {
        self.path.as_str()
    }

    #[must_use]
    pub(in crate::db::schema) const fn codec(&self) -> CompositeCodec {
        self.codec
    }

    #[must_use]
    pub(in crate::db::schema) const fn shape(&self) -> &AcceptedCompositeShape {
        &self.shape
    }

    fn validate(
        &self,
        composite_catalog: &AcceptedCompositeCatalog,
        enum_catalog: &AcceptedEnumCatalog,
    ) -> bool {
        !self.path.is_empty()
            && match &self.shape {
                AcceptedCompositeShape::Record(fields) => {
                    fields.windows(2).all(|pair| pair[0].name < pair[1].name)
                        && unique_values(fields.iter().map(|field| field.id))
                        && fields.iter().all(|field| {
                            !field.name.is_empty()
                                && composite_catalog
                                    .matches_kind(enum_catalog, &field.contract.kind)
                        })
                }
                AcceptedCompositeShape::Tuple(elements) => elements
                    .iter()
                    .all(|element| composite_catalog.matches_kind(enum_catalog, &element.kind)),
                AcceptedCompositeShape::Newtype(inner) => {
                    composite_catalog.matches_kind(enum_catalog, &inner.kind)
                }
            }
    }
}

///
/// AcceptedCompositeShape
///
/// Exact member layout owned by one accepted nominal composite definition.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::schema) enum AcceptedCompositeShape {
    /// Named members in canonical field-name order.
    Record(Vec<AcceptedCompositeField>),
    /// Positional members in declaration order.
    Tuple(Vec<AcceptedCompositeElement>),
    /// One nominally wrapped member.
    Newtype(AcceptedCompositeElement),
}

///
/// AcceptedCompositeField
///
/// One named record member and its inseparable accepted value contract.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::schema) struct AcceptedCompositeField {
    id: CompositeFieldId,
    name: String,
    contract: AcceptedCompositeElement,
}

impl AcceptedCompositeField {
    /// Construct one canonical record member.
    #[must_use]
    pub(in crate::db::schema) const fn new(
        id: CompositeFieldId,
        name: String,
        contract: AcceptedCompositeElement,
    ) -> Self {
        Self { id, name, contract }
    }

    #[must_use]
    pub(in crate::db::schema) const fn id(&self) -> CompositeFieldId {
        self.id
    }

    #[must_use]
    pub(in crate::db::schema) fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub(in crate::db::schema) const fn contract(&self) -> &AcceptedCompositeElement {
        &self.contract
    }
}

///
/// AcceptedCompositeElement
///
/// One positional payload kind and its accepted explicit-null policy.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::schema) struct AcceptedCompositeElement {
    kind: AcceptedFieldKind,
    nullable: bool,
}

impl AcceptedCompositeElement {
    /// Construct one canonical positional or wrapped member.
    #[must_use]
    pub(in crate::db::schema) const fn new(kind: AcceptedFieldKind, nullable: bool) -> Self {
        Self { kind, nullable }
    }

    #[must_use]
    pub(in crate::db::schema) const fn kind(&self) -> &AcceptedFieldKind {
        &self.kind
    }

    #[must_use]
    pub(in crate::db::schema) const fn nullable(&self) -> bool {
        self.nullable
    }
}

/// Typed rejection while constructing or editing an accepted composite catalog.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::schema) enum CompositeCatalogBuildError {
    ConflictingDefinition { path: String },
    ExistingTypeContractChanged { path: String },
    FieldKindResolution,
}

fn unique_values<T: Ord>(values: impl Iterator<Item = T>) -> bool {
    let mut seen = BTreeSet::new();
    values.into_iter().all(|value| seen.insert(value))
}

fn validate_composite_type_graph(
    composite_catalog: &AcceptedCompositeCatalog,
    enum_catalog: &AcceptedEnumCatalog,
    type_id: CompositeTypeId,
    visited: &mut BTreeSet<CompositeTypeId>,
    active: &mut BTreeSet<CompositeTypeId>,
    depth: usize,
) -> bool {
    if depth >= MAX_ACCEPTED_RECURSIVE_DEPTH {
        return false;
    }
    if visited.contains(&type_id) {
        return true;
    }
    if !active.insert(type_id) {
        return false;
    }
    let Some(definition) = composite_catalog.by_id.get(&type_id) else {
        return false;
    };
    let mut references = BTreeSet::new();
    let valid_shape = match &definition.shape {
        AcceptedCompositeShape::Record(fields) => fields.iter().all(|field| {
            enum_catalog.collect_composite_references(&field.contract.kind, &mut references)
        }),
        AcceptedCompositeShape::Tuple(elements) => elements.iter().all(|element| {
            enum_catalog.collect_composite_references(&element.kind, &mut references)
        }),
        AcceptedCompositeShape::Newtype(inner) => {
            enum_catalog.collect_composite_references(&inner.kind, &mut references)
        }
    };
    if !valid_shape {
        return false;
    }
    for referenced_type in references {
        if !composite_catalog.by_id.contains_key(&referenced_type)
            || !validate_composite_type_graph(
                composite_catalog,
                enum_catalog,
                referenced_type,
                visited,
                active,
                depth.saturating_add(1),
            )
        {
            return false;
        }
    }
    active.remove(&type_id);
    visited.insert(type_id);
    true
}