icydb-model 0.215.4

IcyDB application-model authoring, validation, and code generation
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
//! Module: build::actor
//! Responsibility: host-side generated actor code construction for IcyDB canisters.
//! Does not own: schema validation, runtime session semantics, or build config parsing.
//! Boundary: turns validated schema nodes and build options into generated Rust tokens.

mod crate_path;
mod db;

use std::sync::Arc;

use crate::{
    build::get_schema,
    node::{Canister, Entity, Schema, Store},
};
use icydb_schema::encode_schema_fragment;
use proc_macro2::TokenStream;
use quote::quote;
use sha2::{Digest, Sha256};

/// Generate canister actor code for the given schema path and build options.
///
/// # Panics
///
/// Panics if the process-global schema has not validated successfully,
/// `canister_path` does not resolve to a canister node, or the consuming
/// package's `icydb` dependency path cannot be resolved.
#[must_use]
pub fn generate_with_options(canister_path: &str, options: BuildOptions) -> String {
    // Load the validated schema and resolve the requested canister node.
    let schema = get_schema().expect("schema must be valid before codegen");
    let canister = schema
        .cast_node::<Canister>(canister_path)
        .expect("canister path must resolve to a canister node");
    let fragment = schema
        .schema_fragment_for_canister(canister_path)
        .expect("sealed canister database closure must lower into a schema fragment");

    // Render the canister actor glue from the schema-owned metadata.
    let code = ActorBuilder::new(
        Arc::new(schema.clone()),
        canister.clone(),
        options,
        fragment,
    );
    drop(schema);
    let tokens = crate_path::rewrite_icydb_path(code.generate(), options.icydb_crate_path());

    tokens.to_string()
}

///
/// BuildOptions
///
/// Host-provided actor generation options. Config parsing remains outside this
/// crate; callers pass already-validated booleans into codegen.
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct BuildOptions {
    sql: BuildSqlOptions,
    metrics: BuildMetricsOptions,
    snapshot_enabled: bool,
    schema_enabled: bool,
    icydb_crate_path: Option<&'static str>,
}

impl BuildOptions {
    /// Build options with generated read-only SQL endpoint emission configured.
    #[must_use]
    pub const fn with_sql_readonly_enabled(mut self, enabled: bool) -> Self {
        self.sql.surfaces = self.sql.surfaces.with_readonly_enabled(enabled);

        self
    }

    /// Build options with generated SQL DDL endpoint emission configured.
    #[must_use]
    pub const fn with_sql_ddl_enabled(mut self, enabled: bool) -> Self {
        self.sql.surfaces = self.sql.surfaces.with_ddl_enabled(enabled);

        self
    }

    /// Build options with generated SQL fixture lifecycle endpoint emission configured.
    #[must_use]
    pub const fn with_sql_fixtures_enabled(mut self, enabled: bool) -> Self {
        self.sql.surfaces = self.sql.surfaces.with_fixtures_enabled(enabled);

        self
    }

    /// Build options with generated administrative integrity endpoint emission configured.
    #[must_use]
    pub const fn with_sql_integrity_enabled(mut self, enabled: bool) -> Self {
        self.sql.surfaces = self.sql.surfaces.with_integrity_enabled(enabled);

        self
    }

    /// Build options with generated read-only SQL introspection configured.
    #[must_use]
    pub const fn with_sql_introspection_enabled(mut self, enabled: bool) -> Self {
        self.sql.surfaces = self.sql.surfaces.with_introspection_enabled(enabled);

        self
    }

    /// Build options with generated SQL update endpoint policy configured.
    #[must_use]
    pub const fn with_sql_update_policy(mut self, policy: Option<BuildSqlUpdatePolicy>) -> Self {
        self.sql.update_policy = policy;

        self
    }

    /// Build options with generated metrics report endpoint emission configured.
    #[must_use]
    pub const fn with_metrics_enabled(mut self, enabled: bool) -> Self {
        self.metrics.enabled = enabled;

        self
    }

    /// Build options with generated extended metrics report endpoint emission configured.
    #[must_use]
    pub const fn with_metrics_extended_enabled(mut self, enabled: bool) -> Self {
        self.metrics.extended_enabled = enabled;

        self
    }

    /// Build options with generated storage snapshot endpoint emission configured.
    #[must_use]
    pub const fn with_snapshot_enabled(mut self, enabled: bool) -> Self {
        self.snapshot_enabled = enabled;

        self
    }

    /// Build options with generated schema report endpoint emission configured.
    #[must_use]
    pub const fn with_schema_enabled(mut self, enabled: bool) -> Self {
        self.schema_enabled = enabled;

        self
    }

    /// Build options with an explicit path to the consumer's `icydb`
    /// dependency.
    ///
    /// This is useful when package discovery is unavailable or the caller
    /// deliberately wants generated output to use a specific re-export.
    #[must_use]
    pub const fn with_icydb_crate_path(mut self, path: &'static str) -> Self {
        self.icydb_crate_path = Some(path);

        self
    }

    /// Return whether generated actor glue should export the read-only SQL endpoint.
    #[must_use]
    pub const fn sql_readonly_enabled(self) -> bool {
        self.sql.surfaces.readonly_enabled()
    }

    /// Return whether generated actor glue should export the SQL DDL endpoint.
    #[must_use]
    pub const fn sql_ddl_enabled(self) -> bool {
        self.sql.surfaces.ddl_enabled()
    }

    /// Return whether generated actor glue should export SQL fixture lifecycle endpoints.
    #[must_use]
    pub const fn sql_fixtures_enabled(self) -> bool {
        self.sql.surfaces.fixtures_enabled()
    }

    /// Return whether generated actor glue should export the integrity endpoint.
    #[must_use]
    pub const fn sql_integrity_enabled(self) -> bool {
        self.sql.surfaces.integrity_enabled()
    }

    /// Return whether generated read-only SQL endpoints should admit introspection.
    #[must_use]
    pub const fn sql_introspection_enabled(self) -> bool {
        self.sql.surfaces.introspection_enabled()
    }

    #[must_use]
    pub(crate) const fn sql_surface_flags(self) -> BuildSqlSurfaceFlags {
        self.sql.surfaces
    }

    #[must_use]
    const fn icydb_crate_path(self) -> Option<&'static str> {
        self.icydb_crate_path
    }

    /// Return the generated SQL update endpoint policy, if explicitly enabled.
    #[must_use]
    pub const fn sql_update_policy(self) -> Option<BuildSqlUpdatePolicy> {
        self.sql.update_policy
    }

    /// Return whether generated actor glue should export the SQL update endpoint.
    #[must_use]
    pub const fn sql_update_enabled(self) -> bool {
        self.sql_update_policy().is_some()
    }

    /// Return whether generated actor glue should export metrics report endpoints.
    #[must_use]
    pub const fn metrics_enabled(self) -> bool {
        self.metrics.enabled
    }

    /// Return whether generated actor glue should export extended metrics report endpoints.
    #[must_use]
    pub const fn metrics_extended_enabled(self) -> bool {
        self.metrics.enabled && self.metrics.extended_enabled
    }

    /// Return whether generated actor glue should export storage snapshot endpoints.
    #[must_use]
    pub const fn snapshot_enabled(self) -> bool {
        self.snapshot_enabled
    }

    /// Return whether generated actor glue should export schema report endpoints.
    #[must_use]
    pub const fn schema_enabled(self) -> bool {
        self.schema_enabled
    }

    /// Return whether any generated SQL endpoint surface is enabled.
    #[must_use]
    pub const fn sql_enabled(self) -> bool {
        self.sql_readonly_enabled()
            || self.sql_ddl_enabled()
            || self.sql_fixtures_enabled()
            || self.sql_integrity_enabled()
            || self.sql_update_enabled()
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct BuildSqlOptions {
    surfaces: BuildSqlSurfaceFlags,
    update_policy: Option<BuildSqlUpdatePolicy>,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct BuildSqlSurfaceFlags(u8);

impl BuildSqlSurfaceFlags {
    const DDL: u8 = 1 << 1;
    const FIXTURES: u8 = 1 << 2;
    const INTROSPECTION: u8 = 1 << 3;
    const INTEGRITY: u8 = 1 << 4;
    const READONLY: u8 = 1;

    #[must_use]
    pub(crate) const fn with_readonly_enabled(self, enabled: bool) -> Self {
        self.with_flag(Self::READONLY, enabled)
    }

    #[must_use]
    pub(crate) const fn with_ddl_enabled(self, enabled: bool) -> Self {
        self.with_flag(Self::DDL, enabled)
    }

    #[must_use]
    pub(crate) const fn with_fixtures_enabled(self, enabled: bool) -> Self {
        self.with_flag(Self::FIXTURES, enabled)
    }

    #[must_use]
    pub(crate) const fn with_integrity_enabled(self, enabled: bool) -> Self {
        self.with_flag(Self::INTEGRITY, enabled)
    }

    #[must_use]
    pub(crate) const fn with_introspection_enabled(self, enabled: bool) -> Self {
        self.with_flag(Self::INTROSPECTION, enabled)
    }

    #[must_use]
    pub(crate) const fn readonly_enabled(self) -> bool {
        self.contains(Self::READONLY)
    }

    #[must_use]
    pub(crate) const fn ddl_enabled(self) -> bool {
        self.contains(Self::DDL)
    }

    #[must_use]
    pub(crate) const fn fixtures_enabled(self) -> bool {
        self.contains(Self::FIXTURES)
    }

    #[must_use]
    pub(crate) const fn integrity_enabled(self) -> bool {
        self.contains(Self::INTEGRITY)
    }

    #[must_use]
    pub(crate) const fn introspection_enabled(self) -> bool {
        self.contains(Self::INTROSPECTION)
    }

    #[must_use]
    const fn contains(self, flag: u8) -> bool {
        self.0 & flag == flag
    }

    #[must_use]
    const fn with_flag(self, flag: u8, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | flag)
        } else {
            Self(self.0 & !flag)
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct BuildMetricsOptions {
    enabled: bool,
    extended_enabled: bool,
}

impl Default for BuildMetricsOptions {
    fn default() -> Self {
        Self {
            enabled: true,
            extended_enabled: false,
        }
    }
}

/// Generated SQL update endpoint policy selected by actor codegen.

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BuildSqlUpdatePolicy {
    /// Expose only public-safe primary-key `UPDATE` through `icydb_update`.
    PublicPrimaryKeyOnly,
    /// Expose only public-safe bounded deterministic `UPDATE` through `icydb_update`.
    PublicBoundedDeterministic,
}

/// Build-script helper that emits generated actor code with host-provided
/// generation options.
///
/// # Panics
///
/// Panics if Cargo does not provide `OUT_DIR`, the registered graph cannot be
/// generated, or the consuming package's `icydb` dependency path cannot be
/// resolved.
#[macro_export]
macro_rules! build_with_options {
    ($actor:expr, $options:expr) => {
        use std::{env::var, fs::File, io::Write, path::PathBuf};

        // Register the build inputs and generated-code cfg knobs expected by
        // the emitted actor glue.
        println!("cargo:rerun-if-changed=build.rs");
        println!("cargo:rustc-check-cfg=cfg(icydb)");
        println!("cargo:rustc-check-cfg=cfg(feature, values(\"sql\"))");
        println!("cargo:rustc-cfg=icydb");

        // Render the actor module into Cargo's output directory.
        let out_dir = var("OUT_DIR").expect("OUT_DIR not set");
        let output = $crate::build::generate_with_options($actor, $options);
        let actor_file = PathBuf::from(out_dir.clone()).join("actor.rs");
        let mut file = File::create(actor_file)?;
        file.write_all(output.as_bytes())?;
    };
}

///
/// ActorBuilder
///
/// Internal codegen helper that renders one canister's generated runtime
/// module from the validated schema graph.
///

pub(crate) struct ActorBuilder {
    pub(crate) schema: Arc<Schema>,
    pub(crate) canister: Canister,
    pub(crate) options: BuildOptions,
    pub(crate) schema_fragment_bytes: Vec<u8>,
    pub(crate) schema_submission_key: String,
}

impl ActorBuilder {
    /// Create an actor builder for a specific canister.
    #[must_use]
    pub fn new(
        schema: Arc<Schema>,
        canister: Canister,
        options: BuildOptions,
        fragment: icydb_schema::SchemaFragment,
    ) -> Self {
        let schema_fragment_bytes =
            encode_schema_fragment(&fragment).expect("sealed schema fragment must encode");
        let digest = Sha256::digest(schema_fragment_bytes.as_slice());
        let schema_submission_key = format!("generated/{}", hex_bytes(digest.as_slice()));

        Self {
            schema,
            canister,
            options,
            schema_fragment_bytes,
            schema_submission_key,
        }
    }

    /// Generate the full actor module (db/metrics/query glue).
    #[must_use]
    pub fn generate(self) -> TokenStream {
        let mut tokens = quote!();

        // Emit the shared runtime wiring and configured generated endpoints.
        tokens.extend(db::generate(&self));
        tokens.extend(generate_snapshot(&self));
        tokens.extend(generate_metrics(&self));

        quote! {
            #tokens
        }
    }

    /// All stores belonging to the current canister, keyed by path.
    #[must_use]
    pub fn get_stores(&self) -> Vec<(String, Store)> {
        let canister_path = self.canister_path();

        self.schema
            .filter_nodes::<Store>(|node| node.canister() == canister_path)
            .map(|(path, store)| (path.to_string(), store.clone()))
            .collect()
    }

    /// All entities belonging to the current canister, keyed by path.
    #[must_use]
    pub fn get_entities(&self) -> Vec<(String, Entity)> {
        let canister_path = self.canister_path();

        self.schema
            .get_nodes::<Entity>()
            .filter_map(|(path, entity)| {
                let store = self.schema.cast_node::<Store>(entity.store()).ok()?;
                if store.canister() == canister_path {
                    Some((path.to_string(), entity.clone()))
                } else {
                    None
                }
            })
            .collect()
    }

    fn canister_path(&self) -> String {
        self.canister.def().path()
    }
}

fn hex_bytes(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

/// Render the storage snapshot endpoint for a canister actor.
#[must_use]
fn generate_snapshot(builder: &ActorBuilder) -> TokenStream {
    if builder.options.snapshot_enabled() {
        quote! {
        #[::icydb::__reexports::ic_cdk::query(name = "icydb_snapshot")]
        pub fn __icydb_snapshot() -> Result<::icydb::db::StorageReport, ::icydb::Error> {
            ::icydb::__macro::execute_generated_storage_report(&db()?)
        }
        }
    } else {
        TokenStream::new()
    }
}

/// Render the configured metrics endpoints for a canister actor.
#[must_use]
fn generate_metrics(builder: &ActorBuilder) -> TokenStream {
    let metrics_endpoint = builder.options.metrics_enabled().then(|| {
        quote! {
        #[::icydb::__reexports::ic_cdk::query(name = "icydb_metrics")]
        pub fn __icydb_metrics(window_start_ms: Option<u64>) -> Result<::icydb::metrics::CompactMetricsReport, ::icydb::Error> {
            Ok(::icydb::metrics::compact_metrics_report(window_start_ms))
        }
        }
    });

    let metrics_extended_endpoint = builder.options.metrics_extended_enabled().then(|| {
        quote! {
        #[::icydb::__reexports::ic_cdk::query(name = "icydb_metrics_extended")]
        pub fn __icydb_metrics_extended(window_start_ms: Option<u64>) -> Result<::icydb::metrics::EventReport, ::icydb::Error> {
            Ok(::icydb::metrics::metrics_report(window_start_ms))
        }
        }
    });

    let metrics_reset_endpoint = builder.options.metrics_enabled().then(|| {
        quote! {
        #[::icydb::__reexports::ic_cdk::update(name = "icydb_metrics_reset")]
        pub fn __icydb_metrics_reset() -> Result<(), ::icydb::Error> {
            ::icydb::metrics::metrics_reset_all();

            Ok(())
        }
        }
    });

    quote! {
        #metrics_endpoint
        #metrics_extended_endpoint
        #metrics_reset_endpoint
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::node::{Canister, Def, Schema};
    use proc_macro2::TokenStream;

    use super::{ActorBuilder, BuildOptions};

    fn compact_tokens(tokens: TokenStream) -> String {
        tokens
            .to_string()
            .chars()
            .filter(|character| !character.is_whitespace())
            .collect()
    }

    fn actor_builder_with_options(options: BuildOptions) -> ActorBuilder {
        ActorBuilder::new(
            Arc::new(Schema::new()),
            Canister::new(Def::new("test", "Canister"), "test", 0, 1, 2, 3),
            options,
            icydb_schema::SchemaFragment::try_new(Vec::new(), Vec::new())
                .expect("empty test fragment should admit"),
        )
    }

    #[test]
    fn default_build_options_enable_minimal_metrics_only() {
        let options = BuildOptions::default();

        assert!(!options.sql_readonly_enabled());
        assert!(!options.sql_ddl_enabled());
        assert!(!options.sql_fixtures_enabled());
        assert!(!options.sql_integrity_enabled());
        assert!(!options.sql_introspection_enabled());
        assert!(!options.sql_update_enabled());
        assert_eq!(options.sql_update_policy(), None);
        assert!(options.metrics_enabled());
        assert!(!options.metrics_extended_enabled());
        assert!(!options.snapshot_enabled());
        assert!(!options.schema_enabled());
    }

    #[test]
    fn extended_metrics_requires_metrics_surface() {
        let options = BuildOptions::default()
            .with_metrics_enabled(false)
            .with_metrics_extended_enabled(true);

        assert!(!options.metrics_enabled());
        assert!(!options.metrics_extended_enabled());

        let options = options.with_metrics_enabled(true);

        assert!(options.metrics_enabled());
        assert!(options.metrics_extended_enabled());
    }

    #[test]
    fn generated_metrics_surface_uses_public_icydb_endpoint_names() {
        let builder =
            actor_builder_with_options(BuildOptions::default().with_metrics_extended_enabled(true));
        let surface = compact_tokens(super::generate_metrics(&builder));

        assert!(surface.contains("name=\"icydb_metrics\""));
        assert!(surface.contains("name=\"icydb_metrics_extended\""));
        assert!(surface.contains("name=\"icydb_metrics_reset\""));
        assert!(surface.contains("pubfn__icydb_metrics("));
        assert!(surface.contains("pubfn__icydb_metrics_extended("));
        assert!(surface.contains("pubfn__icydb_metrics_reset("));
    }

    #[test]
    fn generated_snapshot_surface_uses_public_icydb_endpoint_name() {
        let builder =
            actor_builder_with_options(BuildOptions::default().with_snapshot_enabled(true));
        let surface = compact_tokens(super::generate_snapshot(&builder));

        assert!(surface.contains("name=\"icydb_snapshot\""));
        assert!(surface.contains("pubfn__icydb_snapshot("));
    }
}