icydb-model 0.284.1

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
//! 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 into generated private Rust capabilities.

mod crate_path;
mod db;

use std::sync::Arc;

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

/// Generate private canister actor code for the given authored schema path.
///
/// # 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, or its generated
/// migration plan does not match the complete target fragment.
#[must_use]
pub fn generate(canister_path: &str) -> String {
    generate_with_crate_path(canister_path, None)
}

fn generate_with_crate_path(canister_path: &str, icydb_crate_path: Option<&str>) -> 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");
    let migration_plan = canister
        .migration_plan()
        .expect("source migration plan must satisfy the public schema contract");

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

    tokens.to_string()
}

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

pub(crate) struct ActorBuilder {
    pub(crate) icydb: TokenStream,
    pub(crate) schema: Arc<Schema>,
    pub(crate) canister: Canister,
    pub(crate) schema_fragment_bytes: Vec<u8>,
    pub(crate) schema_migration_plan_bytes: Option<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,
        fragment: icydb_schema::SchemaFragment,
        migration_plan: Option<SchemaMigrationPlan>,
        icydb: TokenStream,
    ) -> Self {
        if let Some(plan) = &migration_plan {
            plan.validate_target_fragment(&fragment)
                .expect("generated migration target must satisfy the schema proposal contract");
        }
        let schema_fragment_bytes =
            encode_schema_fragment(&fragment).expect("sealed schema fragment must encode");
        let schema_migration_plan_bytes = migration_plan.as_ref().map(|plan| {
            encode_schema_migration_plan(plan).expect("sealed migration plan must encode")
        });
        let mut hasher = Sha256::new();
        hasher.update(b"icydb.generated-schema-submission.v1");
        hasher.update((schema_fragment_bytes.len() as u64).to_be_bytes());
        hasher.update(schema_fragment_bytes.as_slice());
        if let Some(bytes) = &schema_migration_plan_bytes {
            hasher.update((bytes.len() as u64).to_be_bytes());
            hasher.update(bytes);
        } else {
            hasher.update(0_u64.to_be_bytes());
        }
        let digest = hasher.finalize();
        let schema_submission_key = format!("generated/{}", hex_bytes(digest.as_slice()));

        Self {
            icydb,
            schema,
            canister,
            schema_fragment_bytes,
            schema_migration_plan_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 private runtime wiring and endpoint capabilities only.
        tokens.extend(db::generate(&self));
        tokens.extend(generate_endpoint_runtime(&self.icydb));

        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 private operational capabilities and authorization policies used by
/// source-declared endpoint wrappers.
fn generate_endpoint_runtime(icydb: &TokenStream) -> TokenStream {
    quote! {
        #[allow(
            unused_imports,
            reason = "downstream endpoint declarations select a feature-dependent handler subset"
        )]
        pub(crate) mod endpoint_handlers {
            pub(crate) use super::__icydb_endpoint_handler_schema as schema;

            #icydb::__icydb_with_sql_items! {
                pub(crate) use super::__icydb_endpoint_handler_fixtures_load as fixtures_load;
                pub(crate) use super::__icydb_endpoint_handler_fixtures_reset as fixtures_reset;
                pub(crate) use super::__icydb_endpoint_handler_sql_ddl as sql_ddl;
                pub(crate) use super::__icydb_endpoint_handler_sql_integrity as sql_integrity;
                pub(crate) use super::__icydb_endpoint_handler_sql_query as sql_query;
                pub(crate) use super::__icydb_endpoint_handler_sql_update_bounded as sql_update_bounded;
                pub(crate) use super::__icydb_endpoint_handler_sql_update_primary_key as sql_update_primary_key;
            }

            #icydb::__icydb_with_migration_items! {
                pub(crate) fn schema_migrate(
                    command: #icydb::db::SchemaMigrationCommand,
                ) -> Result<#icydb::db::SchemaMigrationStatusPage, #icydb::Error> {
                    let session = #icydb::db::DbSession::new(super::core_db()?);
                    session.migrate_generated_schema(
                        super::ICYDB_SCHEMA_FRAGMENT,
                        super::ICYDB_SCHEMA_MIGRATION_PLAN,
                        super::ICYDB_SCHEMA_SUBMISSION_KEY,
                        super::ICYDB_SCHEMA_ENTITY_STORES,
                        command,
                    )
                }

                pub(crate) fn schema_migration(
                    request: &#icydb::db::SchemaMigrationStatusRequest,
                ) -> Result<#icydb::db::SchemaMigrationStatusPage, #icydb::Error> {
                    let session = #icydb::db::DbSession::new(super::core_db()?);
                    session.generated_schema_migration_status(
                        super::ICYDB_SCHEMA_FRAGMENT,
                        super::ICYDB_SCHEMA_MIGRATION_PLAN,
                        super::ICYDB_SCHEMA_SUBMISSION_KEY,
                        super::ICYDB_SCHEMA_ENTITY_STORES,
                        request,
                    )
                }
            }

            #icydb::__icydb_with_metrics_items! {
                pub(crate) fn metrics(
                ) -> Result<#icydb::metrics::MetricsReport, #icydb::Error> {
                    // The read-only startup boundary qualifies and selects the
                    // current database without requiring ordinary-work readiness.
                    super::startup_state().map_err(|failure| failure.error().clone())?;
                    #icydb::metrics::metrics_report()
                }

                #[allow(
                    clippy::unnecessary_wraps,
                    reason = "generated endpoint handlers retain one uniform fallible dispatch contract"
                )]
                pub(crate) fn metrics_reset() -> Result<(), #icydb::Error> {
                    #icydb::metrics::metrics_reset_all();
                    Ok(())
                }
            }

            pub(crate) fn snapshot(
            ) -> Result<#icydb::db::StorageReport, #icydb::Error> {
                #icydb::__macro::execute_generated_storage_report(&super::db()?)
            }
        }
    }
}

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

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

    use super::ActorBuilder;

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

    fn actor_builder() -> ActorBuilder {
        ActorBuilder::new(
            Arc::new(Schema::new()),
            Canister::new(Def::new("test", "Canister"), "test", None),
            icydb_schema::SchemaFragment::try_new(Vec::new(), Vec::new())
                .expect("empty test fragment should admit"),
            None,
            quote::quote!(::icydb),
        )
    }

    fn migration_target_fragment(version: u32) -> icydb_schema::SchemaFragment {
        use icydb_schema::{
            DeclaredEntityVersion, EntityFragment, FieldFragment, FieldInsertPolicy,
            FieldSourceKey, FieldType, ScalarType, SchemaFragment, SchemaName,
        };
        let field = FieldFragment::new(
            SchemaName::try_new("primary_email").unwrap(),
            FieldType::Scalar(ScalarType::Text { max_len: None }),
            false,
            FieldInsertPolicy::Required,
            None,
        );
        let entity = EntityFragment::try_new(
            SchemaName::try_new("Account").unwrap(),
            DeclaredEntityVersion::try_new(version).unwrap(),
            vec![
                field,
                FieldFragment::new(
                    SchemaName::try_new("id").unwrap(),
                    FieldType::Scalar(ScalarType::Nat64),
                    false,
                    FieldInsertPolicy::Required,
                    None,
                ),
            ],
            vec![FieldSourceKey::try_new("id").unwrap()],
            vec![],
            vec![],
            vec![],
        )
        .unwrap();
        SchemaFragment::try_new(vec![entity], vec![]).unwrap()
    }

    fn actor_builder_with_migration() -> ActorBuilder {
        use icydb_schema::{
            DeclaredEntityVersion, EntityMigration, EntitySourceKey, FieldSourceKey,
            SchemaMigrationPlan, SchemaMigrationRename,
        };

        let migration = SchemaMigrationPlan::try_new(vec![
            EntityMigration::try_new(
                EntitySourceKey::try_new("Account").expect("entity source should admit"),
                DeclaredEntityVersion::try_new(1).expect("version should admit"),
                Some(EntitySourceKey::try_new("User").expect("entity source should admit")),
                vec![SchemaMigrationRename::Field {
                    from: FieldSourceKey::try_new("email").expect("field source should admit"),
                    to: FieldSourceKey::try_new("primary_email")
                        .expect("field source should admit"),
                }],
                Vec::new(),
            )
            .expect("transition should admit"),
        ])
        .expect("plan should admit");
        ActorBuilder::new(
            Arc::new(Schema::new()),
            Canister::new(Def::new("test", "Canister"), "test", None),
            migration_target_fragment(2),
            Some(migration),
            quote::quote!(::icydb),
        )
    }

    #[test]
    fn generated_endpoint_runtime_is_private_and_contains_no_export_attributes() {
        let surface = compact_tokens(super::generate_endpoint_runtime(&quote::quote!(::icydb)));

        for handler in [
            "metrics",
            "metrics_reset",
            "snapshot",
            "schema",
            "schema_migrate",
            "schema_migration",
            "sql_query",
        ] {
            assert!(surface.contains(handler));
        }
        for forbidden in [
            "ic_cdk::query",
            "ic_cdk::update",
            "export_name",
            "no_mangle",
        ] {
            assert!(!surface.contains(forbidden));
        }
    }

    #[test]
    fn complete_generated_actor_cannot_create_a_public_endpoint() {
        let surface = compact_tokens(actor_builder().generate());

        assert!(surface.contains("pub(crate)modendpoint_handlers"));
        for forbidden in [
            "ic_cdk::query",
            "ic_cdk::update",
            "export_name",
            "no_mangle",
        ] {
            assert!(!surface.contains(forbidden));
        }
    }

    #[test]
    fn actor_generation_checks_migration_target_before_emitting_bootstrap() {
        let builder = actor_builder_with_migration();
        let plan = icydb_schema::decode_schema_migration_plan(
            builder.schema_migration_plan_bytes.as_ref().unwrap(),
        )
        .unwrap();
        assert_eq!(
            plan.validate_target_fragment(&migration_target_fragment(2)),
            Ok(())
        );
        assert_eq!(
            plan.validate_target_fragment(&migration_target_fragment(3)),
            Err(icydb_schema::SchemaContractError::MigrationVersionGap)
        );
        let empty = icydb_schema::SchemaFragment::try_new(vec![], vec![]).unwrap();
        assert_eq!(
            plan.validate_target_fragment(&empty),
            Err(icydb_schema::SchemaContractError::InvalidMigrationReference)
        );
        assert!(
            std::panic::catch_unwind(|| ActorBuilder::new(
                Arc::new(Schema::new()),
                Canister::new(Def::new("test", "Canister"), "test", None),
                migration_target_fragment(3),
                Some(plan),
                quote::quote!(::icydb),
            ))
            .is_err()
        );
    }

    #[test]
    fn source_migration_plan_is_bound_into_private_actor_bootstrap_and_submission_identity() {
        let without = actor_builder();
        let without_key = without.schema_submission_key.clone();
        let without_surface = compact_tokens(without.generate());
        let with = actor_builder_with_migration();
        let with_key = with.schema_submission_key.clone();
        let with_surface = compact_tokens(with.generate());

        assert_ne!(with_key, without_key);
        assert!(!without_surface.contains("__icydb_require_migration_capability"));
        assert!(with_surface.contains("__icydb_require_migration_capability"));
        assert!(with_surface.contains("ICYDB_SCHEMA_MIGRATION_PLAN"));
        assert!(without_surface.contains("apply_generated_schema_fragment"));
        assert!(!without_surface.contains("ensure_generated_schema_fragment"));
        assert!(with_surface.contains("ensure_generated_schema_fragment"));
    }
    #[test]
    fn renamed_runtime_path_is_used_by_every_actor_surface() {
        let mut builder = actor_builder_with_migration();
        builder.icydb = super::crate_path::resolve_path(Some("::runtime_api"));
        let tokens = builder.generate();
        syn::parse2::<syn::File>(tokens.clone()).expect("renamed actor remains valid Rust");
        let tokens = compact_tokens(tokens);
        for surface in [
            "::runtime_api::Error",
            "::runtime_api::db::DbSession",
            "::runtime_api::__icydb_with_sql_items",
            "::runtime_api::__icydb_with_migration_items",
        ] {
            assert!(
                tokens.contains(surface),
                "missing runtime-owned surface {surface}"
            );
        }
        assert!(
            tokens.contains("icydb.test"),
            "memory identity is authored data"
        );
    }
}