icydb 0.252.11

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
//! Module: error
//!
//! Responsibility: public typed error payloads and facade error category mapping.
//! Does not own: internal error construction or accepted constraint authority.
//! Boundary: maps core diagnostics to canister-facing Candid error records.

#[cfg(test)]
mod tests;

use std::fmt;

use candid::CandidType;
use icydb_core::db::QueryError;
use icydb_core::error::{ErrorOrigin as CoreErrorOrigin, InternalError};
use serde::Deserialize;

use crate::db::DatabaseBootstrapError;

pub use icydb_core::error::{
    ConstraintValidationFindingOutput, ConstraintValuePath, ConstraintValuePathComponent,
};

//
// DiagnosticFact
//

/// One bounded numeric parameter attached to a public IcyDB error.
///
/// The leaf error code owns the reason. Facts contain only production-safe
/// numeric parameters interpreted together with that code.
#[derive(CandidType, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
pub struct DiagnosticFact {
    tag: u8,
    value: u64,
}

impl DiagnosticFact {
    const fn from_numeric(tag: icydb_diagnostic_code::DiagnosticFactTag, value: u64) -> Self {
        Self {
            tag: tag.raw(),
            value,
        }
    }

    /// Return the stable numeric fact-tag identity.
    #[must_use]
    pub const fn tag(&self) -> u8 {
        self.tag
    }

    /// Return the numeric fact value.
    #[must_use]
    pub const fn value(&self) -> u64 {
        self.value
    }
}

//
// QueryFieldDiagnostic
//

/// One bounded rejected query-field reference attached to a planning error.
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct QueryFieldDiagnostic {
    role: u8,
    field: String,
}

impl QueryFieldDiagnostic {
    fn from_core(role: icydb_diagnostic_code::QueryFieldRole, field: &str) -> Self {
        Self {
            role: role.raw(),
            field: field.to_owned(),
        }
    }

    /// Return the raw compact role identity.
    #[must_use]
    pub const fn role(&self) -> u8 {
        self.role
    }

    /// Return the known typed role, or `None` for malformed decoded context.
    #[must_use]
    pub const fn known_role(&self) -> Option<icydb_diagnostic_code::QueryFieldRole> {
        icydb_diagnostic_code::QueryFieldRole::known(self.role)
    }

    /// Borrow the exact post-normalization rejected field reference.
    #[must_use]
    pub const fn field(&self) -> &str {
        self.field.as_str()
    }
}

//
// Error
//

#[cfg_attr(doc, doc = "Error\n\nPublic error payload.")]
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct Error {
    code: u16,
    class: u8,
    origin: u8,
    facts: Vec<DiagnosticFact>,
    query_field: Option<QueryFieldDiagnostic>,
}

impl Error {
    /// Build a compact public error from one diagnostic code and origin.
    #[must_use]
    pub const fn from_code(
        code: icydb_diagnostic_code::DiagnosticCode,
        origin: ErrorOrigin,
    ) -> Self {
        Self::from_error_code(code.error_code(), origin)
    }

    /// Build a public error from one numeric wire code and origin.
    #[must_use]
    pub const fn from_error_code(
        code: icydb_diagnostic_code::ErrorCode,
        origin: ErrorOrigin,
    ) -> Self {
        Self {
            code: code.raw(),
            class: code.class().wire_code(),
            origin: origin.wire_code(),
            facts: Vec::new(),
            query_field: None,
        }
    }

    /// Build a compact public error from one public category and origin.
    ///
    /// This helper keeps generated endpoint code concise while the wire
    /// payload itself remains code/detail-first.
    #[must_use]
    pub const fn from_kind(kind: ErrorKind, origin: ErrorOrigin) -> Self {
        let code = kind.diagnostic_code();
        let error_code =
            icydb_diagnostic_code::ErrorCode::from_parts(code, Some(kind.diagnostic_detail()));

        Self::from_error_code(error_code, origin)
    }

    /// Build a compact public runtime-boundary error.
    #[must_use]
    pub const fn from_runtime_boundary(
        boundary: icydb_diagnostic_code::RuntimeBoundaryCode,
        origin: ErrorOrigin,
    ) -> Self {
        let detail = icydb_diagnostic_code::DiagnosticDetail::RuntimeBoundary { boundary };
        let error_code =
            icydb_diagnostic_code::ErrorCode::from_parts(detail.diagnostic_code(), Some(detail));

        Self::from_error_code(error_code, origin)
    }

    /// Build a compact public error from a full diagnostic payload.
    #[must_use]
    pub fn from_diagnostic(diagnostic: icydb_diagnostic_code::Diagnostic) -> Self {
        Self::from_error_code(diagnostic.error_code(), diagnostic.origin().into())
    }

    fn from_internal_error(err: &InternalError) -> Self {
        Self::from_diagnostic_and_facts(err.diagnostic(), err.diagnostic_facts())
    }

    pub(crate) fn from_diagnostic_and_facts(
        diagnostic: icydb_diagnostic_code::Diagnostic,
        facts: Vec<(icydb_diagnostic_code::DiagnosticFactTag, u64)>,
    ) -> Self {
        Self::from_diagnostic_facts_and_query_field(diagnostic, facts, None)
    }

    fn from_diagnostic_facts_and_query_field(
        diagnostic: icydb_diagnostic_code::Diagnostic,
        facts: Vec<(icydb_diagnostic_code::DiagnosticFactTag, u64)>,
        query_field: Option<(icydb_diagnostic_code::QueryFieldRole, &str)>,
    ) -> Self {
        if icydb_diagnostic_code::validate_known_diagnostic_fact_schema(
            diagnostic.error_code(),
            facts.as_slice(),
        )
        .is_err()
        {
            return Self::from_kind(
                ErrorKind::Runtime(RuntimeErrorKind::InvariantViolation),
                diagnostic.origin().into(),
            );
        }

        if let Some((role, field)) = query_field
            && icydb_diagnostic_code::validate_query_field_schema(
                diagnostic.error_code(),
                role.raw(),
                field,
            )
            .is_err()
        {
            return Self::from_kind(
                ErrorKind::Runtime(RuntimeErrorKind::InvariantViolation),
                diagnostic.origin().into(),
            );
        }

        let mut error = Self::from_diagnostic(diagnostic);
        error.facts = facts
            .into_iter()
            .map(|(tag, value)| DiagnosticFact::from_numeric(tag, value))
            .collect();
        error.query_field =
            query_field.map(|(role, field)| QueryFieldDiagnostic::from_core(role, field));
        error
    }

    /// Return the compact diagnostic code.
    #[must_use]
    pub const fn code(&self) -> icydb_diagnostic_code::ErrorCode {
        icydb_diagnostic_code::ErrorCode::from_raw(self.code)
    }

    /// Return the broad compact diagnostic class.
    #[must_use]
    pub const fn class(&self) -> icydb_diagnostic_code::ErrorClass {
        match icydb_diagnostic_code::ErrorClass::from_wire_code(self.class) {
            Some(class) => class,
            None => self.code().class(),
        }
    }

    /// Return the diagnostic origin.
    #[must_use]
    pub const fn origin(&self) -> ErrorOrigin {
        ErrorOrigin::from_wire_code(self.origin)
    }

    /// Return compact diagnostic identity for this error.
    #[must_use]
    pub fn diagnostic(&self) -> icydb_diagnostic_code::Diagnostic {
        self.code().diagnostic(self.origin().into())
    }

    /// Return the compact diagnostic code for this error.
    #[must_use]
    pub const fn diagnostic_code(&self) -> icydb_diagnostic_code::DiagnosticCode {
        self.code().diagnostic_code()
    }

    /// Borrow the bounded numeric facts carried by this error.
    #[must_use]
    pub const fn facts(&self) -> &[DiagnosticFact] {
        self.facts.as_slice()
    }

    /// Borrow the raw optional query-field context.
    #[must_use]
    pub const fn query_field(&self) -> Option<&QueryFieldDiagnostic> {
        self.query_field.as_ref()
    }

    /// Validate and borrow the optional query-field context.
    ///
    /// Decoded client data remains untrusted until this check succeeds.
    pub fn validated_query_field(
        &self,
    ) -> Result<
        Option<(icydb_diagnostic_code::QueryFieldRole, &str)>,
        icydb_diagnostic_code::QueryFieldSchemaMismatch,
    > {
        let Some(context) = self.query_field.as_ref() else {
            return Ok(None);
        };
        let role = icydb_diagnostic_code::validate_query_field_schema(
            self.code(),
            context.role,
            context.field.as_str(),
        )?;

        Ok(Some((role, context.field.as_str())))
    }

    pub(crate) fn core_facts(
        &self,
    ) -> Option<Vec<(icydb_diagnostic_code::DiagnosticFactTag, u64)>> {
        self.facts
            .iter()
            .map(|fact| {
                icydb_diagnostic_code::DiagnosticFactTag::known(fact.tag)
                    .map(|tag| (tag, fact.value))
            })
            .collect()
    }
}

impl From<InternalError> for Error {
    fn from(err: InternalError) -> Self {
        Self::from_internal_error(&err)
    }
}

impl From<QueryError> for Error {
    fn from(err: QueryError) -> Self {
        Self::from_diagnostic_facts_and_query_field(
            err.diagnostic(),
            err.diagnostic_facts(),
            err.query_field_context(),
        )
    }
}

impl From<DatabaseBootstrapError> for Error {
    fn from(_err: DatabaseBootstrapError) -> Self {
        Self::from_kind(
            ErrorKind::Runtime(RuntimeErrorKind::Internal),
            ErrorOrigin::Runtime,
        )
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "E{}", self.code)
    }
}

impl std::error::Error for Error {}

#[cfg_attr(doc, doc = "ErrorKind\n\nPublic error category.")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorKind {
    Query(QueryErrorKind),

    /// Runtime failure.
    Runtime(RuntimeErrorKind),
}

impl ErrorKind {
    /// Return the compact diagnostic code for this public error category.
    #[must_use]
    pub const fn diagnostic_code(self) -> icydb_diagnostic_code::DiagnosticCode {
        match self {
            Self::Query(kind) => kind.diagnostic_code(),
            Self::Runtime(kind) => kind.diagnostic_code(),
        }
    }

    const fn diagnostic_detail(self) -> icydb_diagnostic_code::DiagnosticDetail {
        match self {
            Self::Query(kind) => icydb_diagnostic_code::DiagnosticDetail::QueryKind {
                kind: kind.diagnostic_kind(),
            },
            Self::Runtime(kind) => icydb_diagnostic_code::DiagnosticDetail::RuntimeKind {
                kind: kind.diagnostic_kind(),
            },
        }
    }
}

#[cfg_attr(doc, doc = "RuntimeErrorKind\n\nPublic runtime error class.")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RuntimeErrorKind {
    Corruption,
    IncompatiblePersistedFormat,
    InvariantViolation,
    Conflict,
    NotFound,
    Unsupported,
    Internal,
}

impl RuntimeErrorKind {
    /// Return the compact diagnostic code for this runtime category.
    #[must_use]
    pub const fn diagnostic_code(self) -> icydb_diagnostic_code::DiagnosticCode {
        match self {
            Self::Corruption => icydb_diagnostic_code::DiagnosticCode::RuntimeCorruption,
            Self::IncompatiblePersistedFormat => {
                icydb_diagnostic_code::DiagnosticCode::RuntimeIncompatiblePersistedFormat
            }
            Self::InvariantViolation => {
                icydb_diagnostic_code::DiagnosticCode::RuntimeInvariantViolation
            }
            Self::Conflict => icydb_diagnostic_code::DiagnosticCode::RuntimeConflict,
            Self::NotFound => icydb_diagnostic_code::DiagnosticCode::RuntimeNotFound,
            Self::Unsupported => icydb_diagnostic_code::DiagnosticCode::RuntimeUnsupported,
            Self::Internal => icydb_diagnostic_code::DiagnosticCode::RuntimeInternal,
        }
    }

    const fn diagnostic_kind(self) -> icydb_diagnostic_code::RuntimeErrorKind {
        match self {
            Self::Corruption => icydb_diagnostic_code::RuntimeErrorKind::Corruption,
            Self::IncompatiblePersistedFormat => {
                icydb_diagnostic_code::RuntimeErrorKind::IncompatiblePersistedFormat
            }
            Self::InvariantViolation => icydb_diagnostic_code::RuntimeErrorKind::InvariantViolation,
            Self::Conflict => icydb_diagnostic_code::RuntimeErrorKind::Conflict,
            Self::NotFound => icydb_diagnostic_code::RuntimeErrorKind::NotFound,
            Self::Unsupported => icydb_diagnostic_code::RuntimeErrorKind::Unsupported,
            Self::Internal => icydb_diagnostic_code::RuntimeErrorKind::Internal,
        }
    }
}

#[cfg_attr(doc, doc = "QueryErrorKind\n\nPublic query error class.")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueryErrorKind {
    /// Validation failed.
    Validate,

    /// Intent validation failed.
    Intent,

    /// Planning failed.
    Plan,

    /// Pagination lacked ordering.
    UnorderedPagination,

    /// Continuation cursor was invalid.
    InvalidContinuationCursor,

    /// No rows matched.
    NotFound,

    /// More than one row matched.
    NotUnique,
}

impl QueryErrorKind {
    /// Return the compact diagnostic code for this query category.
    #[must_use]
    pub const fn diagnostic_code(self) -> icydb_diagnostic_code::DiagnosticCode {
        match self {
            Self::Validate => icydb_diagnostic_code::DiagnosticCode::QueryValidate,
            Self::Intent => icydb_diagnostic_code::DiagnosticCode::QueryIntent,
            Self::Plan => icydb_diagnostic_code::DiagnosticCode::QueryPlan,
            Self::UnorderedPagination => {
                icydb_diagnostic_code::DiagnosticCode::QueryUnorderedPagination
            }
            Self::InvalidContinuationCursor => {
                icydb_diagnostic_code::DiagnosticCode::QueryInvalidContinuationCursor
            }
            Self::NotFound => icydb_diagnostic_code::DiagnosticCode::QueryNotFound,
            Self::NotUnique => icydb_diagnostic_code::DiagnosticCode::QueryNotUnique,
        }
    }

    const fn diagnostic_kind(self) -> icydb_diagnostic_code::QueryErrorKind {
        match self {
            Self::Validate => icydb_diagnostic_code::QueryErrorKind::Validate,
            Self::Intent => icydb_diagnostic_code::QueryErrorKind::Intent,
            Self::Plan => icydb_diagnostic_code::QueryErrorKind::Plan,
            Self::UnorderedPagination => icydb_diagnostic_code::QueryErrorKind::UnorderedPagination,
            Self::InvalidContinuationCursor => {
                icydb_diagnostic_code::QueryErrorKind::InvalidContinuationCursor
            }
            Self::NotFound => icydb_diagnostic_code::QueryErrorKind::NotFound,
            Self::NotUnique => icydb_diagnostic_code::QueryErrorKind::NotUnique,
        }
    }
}

#[cfg_attr(doc, doc = "ErrorOrigin\n\nPublic error origin.")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorOrigin {
    Cursor,
    Executor,
    Identity,
    Index,
    Interface,
    Planner,
    Query,
    Recovery,
    Response,
    Runtime,
    Serialize,
    Store,
}

impl ErrorOrigin {
    const fn wire_code(self) -> u8 {
        match self {
            Self::Cursor => icydb_diagnostic_code::ErrorOrigin::Cursor.wire_code(),
            Self::Executor => icydb_diagnostic_code::ErrorOrigin::Executor.wire_code(),
            Self::Identity => icydb_diagnostic_code::ErrorOrigin::Identity.wire_code(),
            Self::Index => icydb_diagnostic_code::ErrorOrigin::Index.wire_code(),
            Self::Interface => icydb_diagnostic_code::ErrorOrigin::Interface.wire_code(),
            Self::Planner => icydb_diagnostic_code::ErrorOrigin::Planner.wire_code(),
            Self::Query => icydb_diagnostic_code::ErrorOrigin::Query.wire_code(),
            Self::Recovery => icydb_diagnostic_code::ErrorOrigin::Recovery.wire_code(),
            Self::Response => icydb_diagnostic_code::ErrorOrigin::Response.wire_code(),
            Self::Runtime => icydb_diagnostic_code::ErrorOrigin::Runtime.wire_code(),
            Self::Serialize => icydb_diagnostic_code::ErrorOrigin::Serialize.wire_code(),
            Self::Store => icydb_diagnostic_code::ErrorOrigin::Store.wire_code(),
        }
    }

    const fn from_wire_code(code: u8) -> Self {
        match icydb_diagnostic_code::ErrorOrigin::from_wire_code(code) {
            icydb_diagnostic_code::ErrorOrigin::Cursor => Self::Cursor,
            icydb_diagnostic_code::ErrorOrigin::Executor => Self::Executor,
            icydb_diagnostic_code::ErrorOrigin::Identity => Self::Identity,
            icydb_diagnostic_code::ErrorOrigin::Index => Self::Index,
            icydb_diagnostic_code::ErrorOrigin::Interface => Self::Interface,
            icydb_diagnostic_code::ErrorOrigin::Planner => Self::Planner,
            icydb_diagnostic_code::ErrorOrigin::Query => Self::Query,
            icydb_diagnostic_code::ErrorOrigin::Recovery => Self::Recovery,
            icydb_diagnostic_code::ErrorOrigin::Response => Self::Response,
            icydb_diagnostic_code::ErrorOrigin::Runtime => Self::Runtime,
            icydb_diagnostic_code::ErrorOrigin::Serialize => Self::Serialize,
            icydb_diagnostic_code::ErrorOrigin::Store => Self::Store,
        }
    }
}

impl From<CoreErrorOrigin> for ErrorOrigin {
    fn from(origin: CoreErrorOrigin) -> Self {
        match origin {
            CoreErrorOrigin::Cursor => Self::Cursor,
            CoreErrorOrigin::Executor => Self::Executor,
            CoreErrorOrigin::Identity => Self::Identity,
            CoreErrorOrigin::Index => Self::Index,
            CoreErrorOrigin::Interface => Self::Interface,
            CoreErrorOrigin::Planner => Self::Planner,
            CoreErrorOrigin::Query => Self::Query,
            CoreErrorOrigin::Recovery => Self::Recovery,
            CoreErrorOrigin::Response => Self::Response,
            CoreErrorOrigin::Serialize => Self::Serialize,
            CoreErrorOrigin::Store => Self::Store,
        }
    }
}

impl From<ErrorOrigin> for icydb_diagnostic_code::ErrorOrigin {
    fn from(origin: ErrorOrigin) -> Self {
        match origin {
            ErrorOrigin::Cursor => Self::Cursor,
            ErrorOrigin::Executor => Self::Executor,
            ErrorOrigin::Identity => Self::Identity,
            ErrorOrigin::Index => Self::Index,
            ErrorOrigin::Interface => Self::Interface,
            ErrorOrigin::Planner => Self::Planner,
            ErrorOrigin::Query => Self::Query,
            ErrorOrigin::Recovery => Self::Recovery,
            ErrorOrigin::Response => Self::Response,
            ErrorOrigin::Runtime => Self::Runtime,
            ErrorOrigin::Serialize => Self::Serialize,
            ErrorOrigin::Store => Self::Store,
        }
    }
}

impl From<icydb_diagnostic_code::ErrorOrigin> for ErrorOrigin {
    fn from(origin: icydb_diagnostic_code::ErrorOrigin) -> Self {
        match origin {
            icydb_diagnostic_code::ErrorOrigin::Cursor => Self::Cursor,
            icydb_diagnostic_code::ErrorOrigin::Executor => Self::Executor,
            icydb_diagnostic_code::ErrorOrigin::Identity => Self::Identity,
            icydb_diagnostic_code::ErrorOrigin::Index => Self::Index,
            icydb_diagnostic_code::ErrorOrigin::Interface => Self::Interface,
            icydb_diagnostic_code::ErrorOrigin::Planner => Self::Planner,
            icydb_diagnostic_code::ErrorOrigin::Query => Self::Query,
            icydb_diagnostic_code::ErrorOrigin::Recovery => Self::Recovery,
            icydb_diagnostic_code::ErrorOrigin::Response => Self::Response,
            icydb_diagnostic_code::ErrorOrigin::Runtime => Self::Runtime,
            icydb_diagnostic_code::ErrorOrigin::Serialize => Self::Serialize,
            icydb_diagnostic_code::ErrorOrigin::Store => Self::Store,
        }
    }
}