icydb-core 0.94.0

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
//! Module: visitor
//!
//! Responsibility: generic sanitize/validate visitor diagnostics and context.
//! Does not own: schema-specific validation rules or session error mapping.
//! Boundary: shared visitor error/context surface for derived sanitizers and validators.

pub(crate) mod context;
pub(crate) mod sanitize;
pub(crate) mod validate;

use crate::{
    error::{ErrorClass, ErrorOrigin, InternalError},
    sanitize::SanitizeWriteContext,
    traits::Visitable,
};
use candid::CandidType;
use derive_more::{Deref, DerefMut};
use serde::Deserialize;
use std::{collections::BTreeMap, fmt};
use thiserror::Error as ThisError;

// re-exports
pub use context::{Issue, PathSegment, ScopedContext, VisitorContext};

//
// VisitorError
// Structured error type for visitor-based sanitization and validation.
//

#[derive(Debug, ThisError)]
#[error("{issues}")]
pub struct VisitorError {
    issues: VisitorIssues,
}

impl VisitorError {
    #[must_use]
    pub const fn issues(&self) -> &VisitorIssues {
        &self.issues
    }
}

impl From<VisitorIssues> for VisitorError {
    fn from(issues: VisitorIssues) -> Self {
        Self { issues }
    }
}

impl From<VisitorError> for VisitorIssues {
    fn from(err: VisitorError) -> Self {
        err.issues
    }
}

impl From<VisitorError> for InternalError {
    fn from(err: VisitorError) -> Self {
        Self::classified(
            ErrorClass::Unsupported,
            ErrorOrigin::Executor,
            err.to_string(),
        )
    }
}

//
// VisitorIssues
// Aggregated visitor diagnostics.
//
// NOTE: This is not an error type. It does not represent failure.
// It is converted into a `VisitorError` at the runtime boundary and
// may be lifted into an `InternalError` as needed.
//

#[derive(CandidType, Clone, Debug, Default, Deref, DerefMut, Deserialize, Eq, PartialEq)]
pub struct VisitorIssues(BTreeMap<String, Vec<String>>);

impl VisitorIssues {
    #[must_use]
    pub const fn new() -> Self {
        Self(BTreeMap::new())
    }
}

impl From<BTreeMap<String, Vec<String>>> for VisitorIssues {
    fn from(map: BTreeMap<String, Vec<String>>) -> Self {
        Self(map)
    }
}

impl fmt::Display for VisitorIssues {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut wrote = false;

        for (path, messages) in &self.0 {
            for message in messages {
                if wrote {
                    writeln!(f)?;
                }

                if path.is_empty() {
                    write!(f, "{message}")?;
                } else {
                    write!(f, "{path}: {message}")?;
                }

                wrote = true;
            }
        }

        if !wrote {
            write!(f, "no visitor issues")?;
        }

        Ok(())
    }
}

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

//
// Visitor
// (immutable)
//

pub(crate) trait Visitor {
    fn enter(&mut self, node: &dyn Visitable, ctx: &mut dyn VisitorContext);
    fn exit(&mut self, node: &dyn Visitable, ctx: &mut dyn VisitorContext);
}

// ============================================================================
// VisitorCore (object-safe traversal)
// ============================================================================

// Object-safe visitor contract for immutable traversal dispatch.
pub trait VisitorCore {
    fn enter(&mut self, node: &dyn Visitable);
    fn exit(&mut self, node: &dyn Visitable);

    fn push(&mut self, _: PathSegment) {}
    fn pop(&mut self) {}
}

//
// VisitableFieldDescriptor
//
// Runtime traversal descriptor for one generated struct field.
// Generated code uses this to replace repeated per-field `drive` bodies with
// one shared descriptor loop while preserving typed field access at the
// boundary.
//

pub struct VisitableFieldDescriptor<T> {
    name: &'static str,
    drive: fn(&T, &mut dyn VisitorCore),
    drive_mut: fn(&mut T, &mut dyn VisitorMutCore),
}

impl<T> VisitableFieldDescriptor<T> {
    /// Construct one traversal descriptor for one generated field.
    #[must_use]
    pub const fn new(
        name: &'static str,
        drive: fn(&T, &mut dyn VisitorCore),
        drive_mut: fn(&mut T, &mut dyn VisitorMutCore),
    ) -> Self {
        Self {
            name,
            drive,
            drive_mut,
        }
    }

    /// Return the field name carried by this descriptor.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }
}

// Drive one generated field table through immutable visitor traversal.
pub fn drive_visitable_fields<T>(
    visitor: &mut dyn VisitorCore,
    node: &T,
    fields: &[VisitableFieldDescriptor<T>],
) {
    for field in fields {
        (field.drive)(node, visitor);
    }
}

// Drive one generated field table through mutable visitor traversal.
pub fn drive_visitable_fields_mut<T>(
    visitor: &mut dyn VisitorMutCore,
    node: &mut T,
    fields: &[VisitableFieldDescriptor<T>],
) {
    for field in fields {
        (field.drive_mut)(node, visitor);
    }
}

//
// SanitizeFieldDescriptor
//
// Runtime sanitization descriptor for one generated struct field.
// Generated code uses this to replace repeated per-field `sanitize_self`
// bodies with one shared descriptor loop while preserving typed field access
// at the boundary.
//

pub struct SanitizeFieldDescriptor<T> {
    sanitize: fn(&mut T, &mut dyn VisitorContext),
}

impl<T> SanitizeFieldDescriptor<T> {
    /// Construct one sanitization descriptor for one generated field.
    #[must_use]
    pub const fn new(sanitize: fn(&mut T, &mut dyn VisitorContext)) -> Self {
        Self { sanitize }
    }
}

// Drive one generated field table through sanitization dispatch.
pub fn drive_sanitize_fields<T>(
    node: &mut T,
    ctx: &mut dyn VisitorContext,
    fields: &[SanitizeFieldDescriptor<T>],
) {
    for field in fields {
        (field.sanitize)(node, ctx);
    }
}

//
// ValidateFieldDescriptor
//
// Runtime validation descriptor for one generated struct field.
// Generated code uses this to replace repeated per-field `validate_self`
// bodies with one shared descriptor loop while preserving typed field access
// at the boundary.
//

pub struct ValidateFieldDescriptor<T> {
    validate: fn(&T, &mut dyn VisitorContext),
}

impl<T> ValidateFieldDescriptor<T> {
    /// Construct one validation descriptor for one generated field.
    #[must_use]
    pub const fn new(validate: fn(&T, &mut dyn VisitorContext)) -> Self {
        Self { validate }
    }
}

// Drive one generated field table through validation dispatch.
pub fn drive_validate_fields<T>(
    node: &T,
    ctx: &mut dyn VisitorContext,
    fields: &[ValidateFieldDescriptor<T>],
) {
    for field in fields {
        (field.validate)(node, ctx);
    }
}

// ============================================================================
// Internal adapter context (fixes borrow checker)
// ============================================================================

struct AdapterContext<'a> {
    path: &'a [PathSegment],
    issues: &'a mut VisitorIssues,
    sanitize_write_context: Option<SanitizeWriteContext>,
}

impl VisitorContext for AdapterContext<'_> {
    fn add_issue(&mut self, issue: Issue) {
        let key = render_path(self.path, None);
        self.issues
            .entry(key)
            .or_default()
            .push(issue.into_message());
    }

    fn add_issue_at(&mut self, seg: PathSegment, issue: Issue) {
        let key = render_path(self.path, Some(seg));
        self.issues
            .entry(key)
            .or_default()
            .push(issue.into_message());
    }

    fn sanitize_write_context(&self) -> Option<SanitizeWriteContext> {
        self.sanitize_write_context
    }
}

fn render_path(path: &[PathSegment], extra: Option<PathSegment>) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let mut first = true;

    let iter = path.iter().cloned().chain(extra);

    for seg in iter {
        match seg {
            PathSegment::Field(s) => {
                if !first {
                    out.push('.');
                }
                out.push_str(s);
                first = false;
            }
            PathSegment::Index(i) => {
                let _ = write!(out, "[{i}]");
                first = false;
            }
            PathSegment::Empty => {}
        }
    }

    out
}

// ============================================================================
// VisitorAdapter (immutable)
// ============================================================================

pub(crate) struct VisitorAdapter<V> {
    visitor: V,
    path: Vec<PathSegment>,
    issues: VisitorIssues,
}

impl<V> VisitorAdapter<V>
where
    V: Visitor,
{
    pub(crate) const fn new(visitor: V) -> Self {
        Self {
            visitor,
            path: Vec::new(),
            issues: VisitorIssues::new(),
        }
    }

    pub(crate) fn result(self) -> Result<(), VisitorIssues> {
        if self.issues.is_empty() {
            Ok(())
        } else {
            Err(self.issues)
        }
    }
}

impl<V> VisitorCore for VisitorAdapter<V>
where
    V: Visitor,
{
    fn push(&mut self, seg: PathSegment) {
        if !matches!(seg, PathSegment::Empty) {
            self.path.push(seg);
        }
    }

    fn pop(&mut self) {
        self.path.pop();
    }

    fn enter(&mut self, node: &dyn Visitable) {
        let mut ctx = AdapterContext {
            path: &self.path,
            issues: &mut self.issues,
            sanitize_write_context: None,
        };
        self.visitor.enter(node, &mut ctx);
    }

    fn exit(&mut self, node: &dyn Visitable) {
        let mut ctx = AdapterContext {
            path: &self.path,
            issues: &mut self.issues,
            sanitize_write_context: None,
        };
        self.visitor.exit(node, &mut ctx);
    }
}

// ============================================================================
// Traversal (immutable)
// ============================================================================

pub fn perform_visit<S: Into<PathSegment>>(
    visitor: &mut dyn VisitorCore,
    node: &dyn Visitable,
    seg: S,
) {
    let seg = seg.into();
    let should_push = !matches!(seg, PathSegment::Empty);

    if should_push {
        visitor.push(seg);
    }

    visitor.enter(node);
    node.drive(visitor);
    visitor.exit(node);

    if should_push {
        visitor.pop();
    }
}

// ============================================================================
// VisitorMut (mutable)
// ============================================================================

// Mutable visitor callbacks paired with a scoped visitor context.
pub(crate) trait VisitorMut {
    fn enter_mut(&mut self, node: &mut dyn Visitable, ctx: &mut dyn VisitorContext);
    fn exit_mut(&mut self, node: &mut dyn Visitable, ctx: &mut dyn VisitorContext);
}

// ============================================================================
// VisitorMutCore
// ============================================================================

// Object-safe mutable visitor contract used by traversal drivers.
pub trait VisitorMutCore {
    fn enter_mut(&mut self, node: &mut dyn Visitable);
    fn exit_mut(&mut self, node: &mut dyn Visitable);

    fn push(&mut self, _: PathSegment) {}
    fn pop(&mut self) {}
}

// ============================================================================
// VisitorMutAdapter
// ============================================================================

// Adapter that binds `VisitorMut` to object-safe traversal and path tracking.
pub(crate) struct VisitorMutAdapter<V> {
    visitor: V,
    path: Vec<PathSegment>,
    issues: VisitorIssues,
    sanitize_write_context: Option<SanitizeWriteContext>,
}

impl<V> VisitorMutAdapter<V>
where
    V: VisitorMut,
{
    pub(crate) const fn with_sanitize_write_context(
        visitor: V,
        sanitize_write_context: Option<SanitizeWriteContext>,
    ) -> Self {
        Self {
            visitor,
            path: Vec::new(),
            issues: VisitorIssues::new(),
            sanitize_write_context,
        }
    }

    pub(crate) fn result(self) -> Result<(), VisitorIssues> {
        if self.issues.is_empty() {
            Ok(())
        } else {
            Err(self.issues)
        }
    }
}

impl<V> VisitorMutCore for VisitorMutAdapter<V>
where
    V: VisitorMut,
{
    fn push(&mut self, seg: PathSegment) {
        if !matches!(seg, PathSegment::Empty) {
            self.path.push(seg);
        }
    }

    fn pop(&mut self) {
        self.path.pop();
    }

    fn enter_mut(&mut self, node: &mut dyn Visitable) {
        let mut ctx = AdapterContext {
            path: &self.path,
            issues: &mut self.issues,
            sanitize_write_context: self.sanitize_write_context,
        };
        self.visitor.enter_mut(node, &mut ctx);
    }

    fn exit_mut(&mut self, node: &mut dyn Visitable) {
        let mut ctx = AdapterContext {
            path: &self.path,
            issues: &mut self.issues,
            sanitize_write_context: self.sanitize_write_context,
        };
        self.visitor.exit_mut(node, &mut ctx);
    }
}

// ============================================================================
// Traversal (mutable)
// ============================================================================

// Perform a mutable visitor traversal starting at a trait-object node.
//
// This is the *core* traversal entrypoint. It operates on `&mut dyn Visitable`
// because visitor callbacks (`enter_mut` / `exit_mut`) require a trait object.
//
// Path segments are pushed/popped around the traversal unless the segment is
// `PathSegment::Empty`.
pub fn perform_visit_mut<S: Into<PathSegment>>(
    visitor: &mut dyn VisitorMutCore,
    node: &mut dyn Visitable,
    seg: S,
) {
    let seg = seg.into();
    let should_push = !matches!(seg, PathSegment::Empty);

    if should_push {
        visitor.push(seg);
    }

    visitor.enter_mut(node);
    node.drive_mut(visitor);
    visitor.exit_mut(node);

    if should_push {
        visitor.pop();
    }
}