icydb-core 0.67.0

IcyDB — A type-safe, embedded ORM and schema system 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
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
//! Module: index::entry
//! Responsibility: index-entry payload encode/decode and structural validation.
//! Does not own: commit ordering or unique-policy decisions.
//! Boundary: commit/index-store consume raw entries after prevalidation.

use crate::{
    db::{
        data::{StorageKey, StorageKeyEncodeError},
        index::RawIndexKey,
    },
    error::InternalError,
    traits::Storable,
    value::Value,
};
use canic_cdk::structures::storable::Bound;
use std::{borrow::Cow, collections::BTreeSet};
use thiserror::Error as ThisError;

///
/// Constants
///

const INDEX_ENTRY_LEN_BYTES: usize = 4;
pub(crate) const MAX_INDEX_ENTRY_KEYS: usize = 65_535;

#[expect(clippy::cast_possible_truncation)]
pub(crate) const MAX_INDEX_ENTRY_BYTES: u32 =
    (INDEX_ENTRY_LEN_BYTES + (MAX_INDEX_ENTRY_KEYS * StorageKey::STORED_SIZE_USIZE)) as u32;

///
/// IndexEntryCorruption
///

#[derive(Debug, ThisError)]
pub(crate) enum IndexEntryCorruption {
    #[error("index entry exceeds max size")]
    TooLarge { len: usize },

    #[error("index entry missing key count")]
    MissingLength,

    #[error("index entry key count exceeds limit")]
    TooManyKeys { count: usize },

    #[error("index entry length does not match key count")]
    LengthMismatch,

    #[error("index entry contains invalid key bytes")]
    InvalidKey,

    #[error("index entry contains duplicate key")]
    DuplicateKey,

    #[error("index entry contains zero keys")]
    EmptyEntry,

    #[error("unique index entry contains {keys} keys")]
    NonUniqueEntry { keys: usize },

    #[error("index entry missing expected entity key: {entity_key:?} (index {index_key:?})")]
    MissingKey {
        index_key: Box<RawIndexKey>,
        entity_key: Value,
    },
}

impl IndexEntryCorruption {
    #[must_use]
    pub(crate) fn missing_key(index_key: RawIndexKey, entity_key: StorageKey) -> Self {
        Self::MissingKey {
            index_key: Box::new(index_key),
            entity_key: entity_key.as_value(),
        }
    }
}

///
/// IndexEntryEncodeError
///

#[derive(Debug, ThisError)]
pub(crate) enum IndexEntryEncodeError {
    #[error("index entry exceeds max keys: {keys} (limit {MAX_INDEX_ENTRY_KEYS})")]
    TooManyKeys { keys: usize },

    #[cfg(test)]
    #[error("index entry contains duplicate key")]
    DuplicateKey,

    #[error("index entry key encoding failed: {0}")]
    KeyEncoding(#[from] StorageKeyEncodeError),
}

impl IndexEntryEncodeError {
    // Lift one commit-time index-entry encode failure into internal taxonomy.
    pub(crate) fn into_commit_internal_error(
        self,
        entity_path: &str,
        fields: &str,
    ) -> InternalError {
        match self {
            Self::TooManyKeys { keys } => {
                InternalError::index_entry_exceeds_max_keys(entity_path, fields, keys)
            }
            #[cfg(test)]
            Self::DuplicateKey => {
                InternalError::index_entry_duplicate_keys_unexpected(entity_path, fields)
            }
            Self::KeyEncoding(err) => {
                InternalError::index_entry_key_encoding_failed(entity_path, fields, err)
            }
        }
    }
}

///
/// IndexEntry
///

#[derive(Clone, Debug)]
pub(crate) struct IndexEntry {
    ids: BTreeSet<StorageKey>,
}

impl IndexEntry {
    #[must_use]
    pub(crate) fn new(id: StorageKey) -> Self {
        let mut ids = BTreeSet::new();
        ids.insert(id);
        Self { ids }
    }

    pub(crate) fn insert(&mut self, id: StorageKey) {
        self.ids.insert(id);
    }

    pub(crate) fn remove(&mut self, id: StorageKey) {
        self.ids.remove(&id);
    }

    #[must_use]
    pub(crate) fn contains(&self, id: StorageKey) -> bool {
        self.ids.contains(&id)
    }

    #[must_use]
    pub(crate) fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    #[must_use]
    pub(crate) fn len(&self) -> usize {
        self.ids.len()
    }

    pub(crate) fn iter_ids(&self) -> impl Iterator<Item = StorageKey> + '_ {
        self.ids.iter().copied()
    }
}

///
/// RawIndexEntry
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct RawIndexEntry(Vec<u8>);

impl RawIndexEntry {
    pub(crate) fn try_from_entry(entry: &IndexEntry) -> Result<Self, IndexEntryEncodeError> {
        // `IndexEntry` already owns the canonical sorted-unique membership set,
        // so commit-time re-encoding can stream it directly without rebuilding
        // another temporary vector or duplicate-check set.
        let count = entry.ids.len();
        if count > MAX_INDEX_ENTRY_KEYS {
            return Err(IndexEntryEncodeError::TooManyKeys { keys: count });
        }

        let mut out =
            Vec::with_capacity(INDEX_ENTRY_LEN_BYTES + count * StorageKey::STORED_SIZE_USIZE);

        let count_u32 =
            u32::try_from(count).map_err(|_| IndexEntryEncodeError::TooManyKeys { keys: count })?;
        out.extend_from_slice(&count_u32.to_be_bytes());

        for id in &entry.ids {
            out.extend_from_slice(&id.to_bytes()?);
        }

        Ok(Self(out))
    }

    pub(crate) fn try_decode(&self) -> Result<IndexEntry, IndexEntryCorruption> {
        let storage_keys = self.decode_keys_checked()?;
        let mut ids = BTreeSet::new();

        for key in storage_keys {
            ids.insert(key);
        }

        if ids.is_empty() {
            return Err(IndexEntryCorruption::EmptyEntry);
        }

        Ok(IndexEntry { ids })
    }

    #[cfg(test)]
    pub(crate) fn try_from_keys<I>(keys: I) -> Result<Self, IndexEntryEncodeError>
    where
        I: IntoIterator<Item = StorageKey>,
    {
        // Phase 1: collect and bound-check key cardinality.
        let keys: Vec<StorageKey> = keys.into_iter().collect();
        let count = keys.len();

        if count > MAX_INDEX_ENTRY_KEYS {
            return Err(IndexEntryEncodeError::TooManyKeys { keys: count });
        }

        // Enforce encode/decode symmetry: duplicates are rejected at construction,
        // not deferred to decode-time corruption validation.
        let mut unique = BTreeSet::new();
        for key in &keys {
            if !unique.insert(*key) {
                return Err(IndexEntryEncodeError::DuplicateKey);
            }
        }

        // Phase 2: encode canonical length-prefixed payload.
        let mut out =
            Vec::with_capacity(INDEX_ENTRY_LEN_BYTES + count * StorageKey::STORED_SIZE_USIZE);

        let count_u32 =
            u32::try_from(count).map_err(|_| IndexEntryEncodeError::TooManyKeys { keys: count })?;
        out.extend_from_slice(&count_u32.to_be_bytes());

        for sk in keys {
            out.extend_from_slice(&sk.to_bytes()?);
        }

        Ok(Self(out))
    }

    pub(crate) fn decode_keys(&self) -> Result<Vec<StorageKey>, IndexEntryCorruption> {
        self.decode_keys_checked()
    }

    // Decode the canonical storage-key payload while validating the raw entry
    // shape and duplicate-key invariants in the same pass.
    fn decode_keys_checked(&self) -> Result<Vec<StorageKey>, IndexEntryCorruption> {
        // Phase 1: validate frame shape before any key decode.
        let count = self.validate_frame()?;

        let bytes = self.0.as_slice();

        let mut keys = Vec::with_capacity(count);
        let mut unique = BTreeSet::new();
        let mut offset = INDEX_ENTRY_LEN_BYTES;

        // Phase 2: decode each fixed-width storage key segment and reject
        // duplicate memberships before any planner or commit path consumes it.
        for _ in 0..count {
            let end = offset + StorageKey::STORED_SIZE_USIZE;
            let sk = StorageKey::try_from(&bytes[offset..end])
                .map_err(|_| IndexEntryCorruption::InvalidKey)?;

            if !unique.insert(sk) {
                return Err(IndexEntryCorruption::DuplicateKey);
            }

            keys.push(sk);
            offset = end;
        }

        Ok(keys)
    }

    /// Validate the raw index entry structure without binding to an entity.
    pub(crate) fn validate(&self) -> Result<(), IndexEntryCorruption> {
        self.decode_keys_checked().map(|_| ())
    }

    // Validate the raw index-entry frame and return the declared key count for
    // the checked decode pass.
    fn validate_frame(&self) -> Result<usize, IndexEntryCorruption> {
        let bytes = self.0.as_slice();

        // Phase 1: frame-level checks (size, header, declared count).
        if bytes.len() > MAX_INDEX_ENTRY_BYTES as usize {
            return Err(IndexEntryCorruption::TooLarge { len: bytes.len() });
        }
        if bytes.len() < INDEX_ENTRY_LEN_BYTES {
            return Err(IndexEntryCorruption::MissingLength);
        }

        let mut len_buf = [0u8; INDEX_ENTRY_LEN_BYTES];
        len_buf.copy_from_slice(&bytes[..INDEX_ENTRY_LEN_BYTES]);
        let count = u32::from_be_bytes(len_buf) as usize;

        if count == 0 {
            return Err(IndexEntryCorruption::EmptyEntry);
        }
        if count > MAX_INDEX_ENTRY_KEYS {
            return Err(IndexEntryCorruption::TooManyKeys { count });
        }

        let expected = INDEX_ENTRY_LEN_BYTES
            + count
                .checked_mul(StorageKey::STORED_SIZE_USIZE)
                .ok_or(IndexEntryCorruption::LengthMismatch)?;

        if bytes.len() != expected {
            return Err(IndexEntryCorruption::LengthMismatch);
        }

        Ok(count)
    }

    #[must_use]
    pub(crate) fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    #[must_use]
    pub(crate) const fn len(&self) -> usize {
        self.0.len()
    }
}

impl TryFrom<&IndexEntry> for RawIndexEntry {
    type Error = IndexEntryEncodeError;

    fn try_from(entry: &IndexEntry) -> Result<Self, Self::Error> {
        Self::try_from_entry(entry)
    }
}

impl Storable for RawIndexEntry {
    fn to_bytes(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(&self.0)
    }

    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
        Self(bytes.into_owned())
    }

    fn into_bytes(self) -> Vec<u8> {
        self.0
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: MAX_INDEX_ENTRY_BYTES,
        is_fixed_size: false,
    };
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::{
        IndexEntryCorruption, IndexEntryEncodeError, MAX_INDEX_ENTRY_BYTES, MAX_INDEX_ENTRY_KEYS,
        RawIndexEntry,
    };
    use crate::{
        db::data::StorageKey,
        error::{ErrorClass, ErrorOrigin},
        traits::Storable,
    };
    use std::borrow::Cow;

    #[test]
    fn raw_index_entry_round_trip() {
        let keys = vec![StorageKey::Int(1), StorageKey::Uint(2)];

        let raw = RawIndexEntry::try_from_keys(keys.clone()).expect("encode index entry");
        let decoded = raw.decode_keys().expect("decode index entry");

        assert_eq!(decoded.len(), keys.len());
        assert!(decoded.contains(&StorageKey::Int(1)));
        assert!(decoded.contains(&StorageKey::Uint(2)));
    }

    #[test]
    fn raw_index_entry_roundtrip_via_bytes() {
        let keys = vec![StorageKey::Int(9), StorageKey::Uint(10)];

        let raw = RawIndexEntry::try_from_keys(keys.clone()).expect("encode index entry");
        let encoded = Storable::to_bytes(&raw);
        let raw = RawIndexEntry::from_bytes(encoded);
        let decoded = raw.decode_keys().expect("decode index entry");

        assert_eq!(decoded.len(), keys.len());
        assert!(decoded.contains(&StorageKey::Int(9)));
        assert!(decoded.contains(&StorageKey::Uint(10)));
    }

    #[test]
    fn raw_index_entry_rejects_empty() {
        let bytes = vec![0, 0, 0, 0];
        let raw = RawIndexEntry::from_bytes(Cow::Owned(bytes));
        assert!(matches!(
            raw.decode_keys(),
            Err(IndexEntryCorruption::EmptyEntry)
        ));
    }

    #[test]
    fn raw_index_entry_rejects_truncated_payload() {
        let key = StorageKey::Int(1);
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&1u32.to_be_bytes());
        bytes.extend_from_slice(&key.to_bytes().expect("encode"));
        bytes.truncate(bytes.len() - 1);

        let raw = RawIndexEntry::from_bytes(Cow::Owned(bytes));
        assert!(matches!(
            raw.decode_keys(),
            Err(IndexEntryCorruption::LengthMismatch)
        ));
    }

    #[test]
    fn raw_index_entry_rejects_oversized_payload() {
        let bytes = vec![0u8; MAX_INDEX_ENTRY_BYTES as usize + 1];
        let raw = RawIndexEntry::from_bytes(Cow::Owned(bytes));
        assert!(matches!(
            raw.decode_keys(),
            Err(IndexEntryCorruption::TooLarge { .. })
        ));
    }

    #[test]
    #[expect(clippy::cast_possible_truncation)]
    fn raw_index_entry_rejects_corrupted_length_field() {
        let count = (MAX_INDEX_ENTRY_KEYS + 1) as u32;
        let raw = RawIndexEntry::from_bytes(Cow::Owned(count.to_be_bytes().to_vec()));
        assert!(matches!(
            raw.decode_keys(),
            Err(IndexEntryCorruption::TooManyKeys { .. })
        ));
    }

    #[test]
    fn raw_index_entry_rejects_duplicate_keys() {
        let key = StorageKey::Int(1);
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&2u32.to_be_bytes());
        bytes.extend_from_slice(&key.to_bytes().expect("encode"));
        bytes.extend_from_slice(&key.to_bytes().expect("encode"));

        let raw = RawIndexEntry::from_bytes(Cow::Owned(bytes));
        assert!(matches!(
            raw.decode_keys(),
            Err(IndexEntryCorruption::DuplicateKey)
        ));
    }

    #[test]
    fn raw_index_entry_try_from_keys_rejects_duplicate_keys() {
        let key = StorageKey::Int(7);
        let err = RawIndexEntry::try_from_keys([key, key]).expect_err(
            "encoding should reject duplicate keys instead of deferring to decode validation",
        );

        assert!(matches!(err, IndexEntryEncodeError::DuplicateKey));
    }

    #[test]
    fn index_entry_encode_error_owns_commit_internal_mapping() {
        let err = IndexEntryEncodeError::DuplicateKey
            .into_commit_internal_error("tests::Entity", "email");

        assert_eq!(err.class, ErrorClass::InvariantViolation);
        assert_eq!(err.origin, ErrorOrigin::Index);
    }

    #[test]
    #[expect(clippy::cast_possible_truncation)]
    fn raw_index_entry_decode_fuzz_does_not_panic() {
        const RUNS: u64 = 1_000;
        const MAX_LEN: usize = 256;

        let mut seed = 0xA5A5_5A5A_u64;
        for _ in 0..RUNS {
            seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
            let len = (seed as usize) % MAX_LEN;

            let mut bytes = vec![0u8; len];
            for byte in &mut bytes {
                seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
                *byte = (seed >> 24) as u8;
            }

            let raw = RawIndexEntry::from_bytes(Cow::Owned(bytes));
            let _ = raw.decode_keys();
        }
    }
}