icydb-config-build 0.158.4

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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//! Host-only build helper for `icydb.toml` project configuration.
//!
//! This crate owns TOML parsing for build scripts. Runtime crates and generated
//! actor code should consume only the generated Rust constants emitted here.

use serde::Deserialize;
use std::{
    collections::{BTreeMap, btree_map::Entry},
    env, fs, io,
    path::{Path, PathBuf},
};
use thiserror::Error as ThisError;

const CONFIG_FILE_NAME: &str = "icydb.toml";
const CONFIG_PATH_ENV: &str = "ICYDB_CONFIG_PATH";
const GENERATED_CONFIG_FILE_NAME: &str = "icydb_config.rs";

/// Resolved IcyDB config and the path it came from, if a manifest exists.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ResolvedIcydbConfig {
    config_path: Option<PathBuf>,
    config: GeneratedIcydbConfig,
}

impl ResolvedIcydbConfig {
    /// Return the resolved config path, or `None` when no config file exists.
    #[must_use]
    pub fn config_path(&self) -> Option<&Path> {
        self.config_path.as_deref()
    }

    /// Borrow the validated generated config model.
    #[must_use]
    pub const fn config(&self) -> &GeneratedIcydbConfig {
        &self.config
    }

    const fn new(config_path: Option<PathBuf>, config: GeneratedIcydbConfig) -> Self {
        Self {
            config_path,
            config,
        }
    }
}

/// Validated IcyDB project config ready for generated-Rust emission.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct GeneratedIcydbConfig {
    canisters: BTreeMap<String, GeneratedCanisterConfig>,
}

impl GeneratedIcydbConfig {
    /// Borrow validated per-canister config entries.
    #[must_use]
    pub const fn canisters(&self) -> &BTreeMap<String, GeneratedCanisterConfig> {
        &self.canisters
    }

    /// Return whether read-only SQL should be generated for one canister.
    #[must_use]
    pub fn canister_sql_readonly_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::sql_readonly)
    }

    /// Return whether SQL DDL/write endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_sql_ddl_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::sql_ddl)
    }

    /// Return whether SQL fixture lifecycle endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_sql_fixtures_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::sql_fixtures)
    }

    /// Return whether metrics report endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_metrics_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::metrics)
    }

    /// Return whether metrics reset endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_metrics_reset_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::metrics_reset)
    }

    /// Return whether storage snapshot endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_snapshot_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::snapshot)
    }

    /// Return whether schema report endpoints should be generated for one canister.
    #[must_use]
    pub fn canister_schema_enabled(&self, canister_name: &str) -> bool {
        self.canisters
            .get(canister_name)
            .is_some_and(GeneratedCanisterConfig::schema)
    }
}

/// Validated generated settings for one canister.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct GeneratedCanisterConfig {
    sql: GeneratedCanisterSqlConfig,
    metrics: GeneratedCanisterMetricsConfig,
    snapshot: bool,
    schema: bool,
}

impl GeneratedCanisterConfig {
    /// Return whether generated actor glue should export read-only SQL endpoints.
    #[must_use]
    pub const fn sql_readonly(&self) -> bool {
        self.sql.readonly
    }

    /// Return whether generated actor glue should export SQL DDL/write endpoints.
    #[must_use]
    pub const fn sql_ddl(&self) -> bool {
        self.sql.ddl
    }

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

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

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

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

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

/// Validated generated SQL endpoint switches for one canister.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct GeneratedCanisterSqlConfig {
    readonly: bool,
    ddl: bool,
    fixtures: bool,
}

/// Validated generated metrics endpoint switches for one canister.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct GeneratedCanisterMetricsConfig {
    enabled: bool,
    reset: bool,
}

/// Build-script config loading error with path-aware diagnostics.
#[derive(Debug, ThisError)]
pub enum ConfigBuildError {
    #[error("failed to read IcyDB config at '{}': {source}", path.display())]
    Read { path: PathBuf, source: io::Error },

    #[error("failed to parse IcyDB config at '{}': {source}", path.display())]
    Parse {
        path: PathBuf,
        source: toml::de::Error,
    },

    #[error("IcyDB config at '{}' contains an empty canister name", path.display())]
    EmptyCanisterName { path: PathBuf },

    #[error(
        "IcyDB config at '{}' has ambiguous canister names '{first}' and '{second}' after normalization"
    , path.display())]
    AmbiguousCanisterName {
        path: PathBuf,
        first: String,
        second: String,
    },

    #[error(
        "IcyDB config at '{}' contains canister '{canister}' but the generated schema has no matching canister"
    , path.display())]
    UnknownCanister { path: PathBuf, canister: String },

    #[error(
        "generated schema canister names '{first}' and '{second}' are ambiguous after normalization"
    )]
    AmbiguousKnownCanister { first: String, second: String },

    #[error("OUT_DIR is not set for IcyDB config generation")]
    MissingOutDir,

    #[error("failed to write generated IcyDB config to '{}': {source}", path.display())]
    WriteGenerated { path: PathBuf, source: io::Error },
}

/// Parse and validate one TOML config string.
pub fn parse_icydb_toml(
    source: &str,
    known_canisters: &[&str],
) -> Result<GeneratedIcydbConfig, ConfigBuildError> {
    parse_icydb_toml_at(source, None, known_canisters)
}

/// Parse and validate one TOML config file.
pub fn load_icydb_toml(
    path: impl AsRef<Path>,
    known_canisters: &[&str],
) -> Result<GeneratedIcydbConfig, ConfigBuildError> {
    let path = path.as_ref();
    let source = fs::read_to_string(path).map_err(|source| ConfigBuildError::Read {
        path: path.to_path_buf(),
        source,
    })?;

    parse_icydb_toml_at(source.as_str(), Some(path), known_canisters)
}

/// Resolve and validate config from a starting directory without writing
/// generated files. This is intended for host tools such as `icydb config`.
pub fn load_resolved_icydb_toml(
    start_dir: impl AsRef<Path>,
    known_canisters: &[&str],
) -> Result<ResolvedIcydbConfig, ConfigBuildError> {
    let resolved = resolve_config_path(start_dir.as_ref());
    let Some(path) = resolved.config_path else {
        return Ok(ResolvedIcydbConfig::default());
    };
    let config = load_icydb_toml(path.as_path(), known_canisters)?;

    Ok(ResolvedIcydbConfig::new(Some(path), config))
}

/// Render generated Rust constants for one canister target.
#[must_use]
pub fn render_rust_config_for_canister(
    config: &GeneratedIcydbConfig,
    canister_name: &str,
) -> String {
    let sql_readonly_enabled = config.canister_sql_readonly_enabled(canister_name);
    let sql_ddl_enabled = config.canister_sql_ddl_enabled(canister_name);
    let sql_fixtures_enabled = config.canister_sql_fixtures_enabled(canister_name);
    let metrics_enabled = config.canister_metrics_enabled(canister_name);
    let metrics_reset_enabled = config.canister_metrics_reset_enabled(canister_name);
    let snapshot_enabled = config.canister_snapshot_enabled(canister_name);
    let schema_enabled = config.canister_schema_enabled(canister_name);

    format!(
        "\
// @generated by icydb-config-build. Do not edit by hand.
pub const ICYDB_SQL_READONLY_ENABLED: bool = {sql_readonly_enabled};
pub const ICYDB_SQL_DDL_ENABLED: bool = {sql_ddl_enabled};
pub const ICYDB_SQL_FIXTURES_ENABLED: bool = {sql_fixtures_enabled};
pub const ICYDB_METRICS_ENABLED: bool = {metrics_enabled};
pub const ICYDB_METRICS_RESET_ENABLED: bool = {metrics_reset_enabled};
pub const ICYDB_SNAPSHOT_ENABLED: bool = {snapshot_enabled};
pub const ICYDB_SCHEMA_ENABLED: bool = {schema_enabled};
"
    )
}

/// Write generated Rust constants into `OUT_DIR/icydb_config.rs`.
pub fn write_rust_config_for_canister(
    out_dir: impl AsRef<Path>,
    config: &GeneratedIcydbConfig,
    canister_name: &str,
) -> Result<PathBuf, ConfigBuildError> {
    let output_path = out_dir.as_ref().join(GENERATED_CONFIG_FILE_NAME);
    let source = render_rust_config_for_canister(config, canister_name);
    fs::write(output_path.as_path(), source).map_err(|source| {
        ConfigBuildError::WriteGenerated {
            path: output_path.clone(),
            source,
        }
    })?;

    Ok(output_path)
}

/// Resolve, validate, and write config for a canister build script.
///
/// Resolution order:
/// 1. `ICYDB_CONFIG_PATH`
/// 2. nearest `icydb.toml` found by walking up from the canister crate
/// 3. absent config, treated as defaults
pub fn emit_config_for_canister(
    canister_name: &str,
    _known_canisters: &[&str],
) -> Result<GeneratedIcydbConfig, ConfigBuildError> {
    println!("cargo:rerun-if-env-changed={CONFIG_PATH_ENV}");
    let manifest_dir = env::var_os("CARGO_MANIFEST_DIR").map_or_else(
        || env::current_dir().expect("current directory should resolve"),
        PathBuf::from,
    );
    let resolved = resolve_config_path(manifest_dir.as_path());
    let config = if let Some(path) = resolved.config_path.as_ref() {
        println!("cargo:rerun-if-changed={}", path.display());
        load_icydb_toml(path.as_path(), &[])?
    } else {
        for candidate in &resolved.candidate_paths {
            println!("cargo:rerun-if-changed={}", candidate.display());
        }
        GeneratedIcydbConfig::default()
    };
    let out_dir = env::var_os("OUT_DIR")
        .map(PathBuf::from)
        .ok_or(ConfigBuildError::MissingOutDir)?;
    write_rust_config_for_canister(out_dir, &config, canister_name)?;

    Ok(config)
}

fn parse_icydb_toml_at(
    source: &str,
    path: Option<&Path>,
    known_canisters: &[&str],
) -> Result<GeneratedIcydbConfig, ConfigBuildError> {
    let path = path.unwrap_or_else(|| Path::new("<inline>"));
    let raw: RawIcydbProjectConfig =
        toml::from_str(source).map_err(|source| ConfigBuildError::Parse {
            path: path.to_path_buf(),
            source,
        })?;

    validate_raw_config(raw, path, known_canisters)
}

fn validate_raw_config(
    raw: RawIcydbProjectConfig,
    path: &Path,
    known_canisters: &[&str],
) -> Result<GeneratedIcydbConfig, ConfigBuildError> {
    let known_by_normalized = normalized_known_canisters(known_canisters)?;
    let canisters = validate_canisters(
        raw.canisters.unwrap_or_default(),
        path,
        &known_by_normalized,
    )?;

    Ok(GeneratedIcydbConfig { canisters })
}

fn validate_canisters(
    raw_canisters: BTreeMap<String, RawCanisterConfig>,
    path: &Path,
    known_by_normalized: &BTreeMap<String, String>,
) -> Result<BTreeMap<String, GeneratedCanisterConfig>, ConfigBuildError> {
    let mut normalized_seen = BTreeMap::new();
    let mut generated = BTreeMap::new();

    for (raw_name, raw_config) in raw_canisters {
        if raw_name.trim().is_empty() {
            return Err(ConfigBuildError::EmptyCanisterName {
                path: path.to_path_buf(),
            });
        }
        let normalized = normalize_canister_name(raw_name.as_str());
        match normalized_seen.entry(normalized.clone()) {
            Entry::Vacant(slot) => {
                slot.insert(raw_name.clone());
            }
            Entry::Occupied(existing) => {
                return Err(ConfigBuildError::AmbiguousCanisterName {
                    path: path.to_path_buf(),
                    first: existing.get().clone(),
                    second: raw_name,
                });
            }
        }

        let resolved_name = if known_by_normalized.is_empty() {
            raw_name
        } else {
            known_by_normalized
                .get(normalized.as_str())
                .cloned()
                .ok_or_else(|| ConfigBuildError::UnknownCanister {
                    path: path.to_path_buf(),
                    canister: raw_name.clone(),
                })?
        };
        generated.insert(
            resolved_name,
            GeneratedCanisterConfig {
                sql: GeneratedCanisterSqlConfig {
                    readonly: raw_config
                        .sql
                        .as_ref()
                        .and_then(|sql| sql.readonly)
                        .unwrap_or(false),
                    ddl: raw_config
                        .sql
                        .as_ref()
                        .and_then(|sql| sql.ddl)
                        .unwrap_or(false),
                    fixtures: raw_config
                        .sql
                        .as_ref()
                        .and_then(|sql| sql.fixtures)
                        .unwrap_or(false),
                },
                metrics: GeneratedCanisterMetricsConfig {
                    enabled: raw_config
                        .metrics
                        .as_ref()
                        .and_then(|metrics| metrics.enabled)
                        .unwrap_or(false),
                    reset: raw_config
                        .metrics
                        .as_ref()
                        .and_then(|metrics| metrics.reset)
                        .unwrap_or(false),
                },
                snapshot: raw_config
                    .snapshot
                    .as_ref()
                    .and_then(|snapshot| snapshot.enabled)
                    .unwrap_or(false),
                schema: raw_config
                    .schema
                    .as_ref()
                    .and_then(|schema| schema.enabled)
                    .unwrap_or(false),
            },
        );
    }

    Ok(generated)
}

fn normalized_known_canisters(
    known_canisters: &[&str],
) -> Result<BTreeMap<String, String>, ConfigBuildError> {
    let mut known_by_normalized = BTreeMap::new();
    for known in known_canisters {
        let normalized = normalize_canister_name(known);
        match known_by_normalized.entry(normalized) {
            Entry::Vacant(slot) => {
                slot.insert((*known).to_string());
            }
            Entry::Occupied(existing) => {
                return Err(ConfigBuildError::AmbiguousKnownCanister {
                    first: existing.get().clone(),
                    second: (*known).to_string(),
                });
            }
        }
    }

    Ok(known_by_normalized)
}

fn normalize_canister_name(name: &str) -> String {
    name.chars()
        .map(|ch| match ch {
            '-' => '_',
            other => other.to_ascii_lowercase(),
        })
        .collect()
}

struct ResolvedConfigPath {
    config_path: Option<PathBuf>,
    candidate_paths: Vec<PathBuf>,
}

fn resolve_config_path(manifest_dir: &Path) -> ResolvedConfigPath {
    let candidate_paths = config_search_candidates(manifest_dir);
    if let Some(explicit) = env::var_os(CONFIG_PATH_ENV) {
        return ResolvedConfigPath {
            config_path: Some(PathBuf::from(explicit)),
            candidate_paths,
        };
    }

    let config_path = candidate_paths
        .iter()
        .find(|candidate| candidate.exists())
        .cloned();

    ResolvedConfigPath {
        config_path,
        candidate_paths,
    }
}

fn config_search_candidates(manifest_dir: &Path) -> Vec<PathBuf> {
    let mut candidates = Vec::new();
    for ancestor in manifest_dir.ancestors() {
        candidates.push(ancestor.join(CONFIG_FILE_NAME));
        if is_workspace_root(ancestor) {
            break;
        }
    }

    candidates
}

fn is_workspace_root(path: &Path) -> bool {
    let manifest = path.join("Cargo.toml");
    let Ok(source) = fs::read_to_string(manifest) else {
        return false;
    };

    source.contains("[workspace]")
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawIcydbProjectConfig {
    canisters: Option<BTreeMap<String, RawCanisterConfig>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCanisterConfig {
    sql: Option<RawCanisterSqlConfig>,
    metrics: Option<RawCanisterMetricsConfig>,
    snapshot: Option<RawCanisterSnapshotConfig>,
    schema: Option<RawCanisterSchemaConfig>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCanisterSqlConfig {
    readonly: Option<bool>,
    ddl: Option<bool>,
    fixtures: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCanisterMetricsConfig {
    enabled: Option<bool>,
    reset: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCanisterSnapshotConfig {
    enabled: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCanisterSchemaConfig {
    enabled: Option<bool>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn absent_config_defaults_all_optional_surfaces_off() {
        let config = parse_icydb_toml("", &[]).expect("empty config should parse");

        assert!(!config.canister_sql_readonly_enabled("demo_rpg"));
        assert!(!config.canister_sql_ddl_enabled("demo_rpg"));
        assert!(!config.canister_sql_fixtures_enabled("demo_rpg"));
        assert!(!config.canister_metrics_enabled("demo_rpg"));
        assert!(!config.canister_metrics_reset_enabled("demo_rpg"));
        assert!(!config.canister_snapshot_enabled("demo_rpg"));
        assert!(!config.canister_schema_enabled("demo_rpg"));
    }

    #[test]
    fn readonly_ddl_fixtures_metrics_snapshot_and_schema_config_validate() {
        let config = parse_icydb_toml(
            r"
                [canisters.demo_rpg.sql]
                readonly = true
                ddl = true
                fixtures = true

                [canisters.demo_rpg.metrics]
                enabled = true
                reset = true

                [canisters.demo_rpg.snapshot]
                enabled = true

                [canisters.demo_rpg.schema]
                enabled = true
            ",
            &["demo_rpg"],
        )
        .expect("valid config should parse");

        assert!(config.canister_sql_readonly_enabled("demo_rpg"));
        assert!(config.canister_sql_ddl_enabled("demo_rpg"));
        assert!(config.canister_sql_fixtures_enabled("demo_rpg"));
        assert!(config.canister_metrics_enabled("demo_rpg"));
        assert!(config.canister_metrics_reset_enabled("demo_rpg"));
        assert!(config.canister_snapshot_enabled("demo_rpg"));
        assert!(config.canister_schema_enabled("demo_rpg"));
    }

    #[test]
    fn unknown_top_level_section_fails_parse() {
        let err = parse_icydb_toml(
            r"
                [unexpected]
                enabled = true
            ",
            &[],
        )
        .expect_err("unknown top-level sections should fail");

        assert!(matches!(err, ConfigBuildError::Parse { .. }));
    }

    #[test]
    fn unknown_canister_field_fails_parse() {
        let err = parse_icydb_toml(
            r"
                [canisters.demo_rpg]
                unexpected = true
            ",
            &[],
        )
        .expect_err("unknown canister fields should fail");

        assert!(matches!(err, ConfigBuildError::Parse { .. }));
    }

    #[test]
    fn unknown_generated_canister_fails_validation() {
        let err = parse_icydb_toml(
            r"
                [canisters.unknown.sql]
                readonly = true
            ",
            &["demo_rpg"],
        )
        .expect_err("config canister must match generated schema canister");

        assert!(matches!(
            err,
            ConfigBuildError::UnknownCanister { canister, .. } if canister == "unknown"
        ));
    }

    #[test]
    fn ambiguous_canister_names_fail_validation() {
        let err = parse_icydb_toml(
            r"
                [canisters.demo-rpg.sql]
                readonly = true

                [canisters.demo_rpg.sql]
                ddl = true
            ",
            &[],
        )
        .expect_err("normalized duplicate canister names should fail");

        assert!(matches!(
            err,
            ConfigBuildError::AmbiguousCanisterName { .. }
        ));
    }

    #[test]
    fn generated_rust_constants_use_typed_values() {
        let config = parse_icydb_toml(
            r"
                [canisters.demo_rpg.sql]
                readonly = true
                ddl = true
                fixtures = true

                [canisters.demo_rpg.metrics]
                enabled = true
                reset = true

                [canisters.demo_rpg.snapshot]
                enabled = true

                [canisters.demo_rpg.schema]
                enabled = true
            ",
            &["demo_rpg"],
        )
        .expect("valid config should parse");

        let generated = render_rust_config_for_canister(&config, "demo_rpg");

        assert!(generated.contains("pub const ICYDB_SQL_READONLY_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_SQL_DDL_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_SQL_FIXTURES_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_METRICS_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_METRICS_RESET_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_SNAPSHOT_ENABLED: bool = true;"));
        assert!(generated.contains("pub const ICYDB_SCHEMA_ENABLED: bool = true;"));
        assert!(!generated.contains("[demo.sql]"));
    }

    #[test]
    fn config_resolution_uses_nearest_ancestor_before_workspace_root() {
        let root = env::temp_dir().join(format!("icydb-config-build-test-{}", std::process::id()));
        let workspace = root.join("workspace");
        let canister = workspace.join("canisters").join("demo").join("rpg");
        fs::create_dir_all(canister.as_path()).expect("test directory should be created");
        fs::write(workspace.join("Cargo.toml"), "[workspace]\n")
            .expect("workspace manifest should be written");
        fs::write(
            workspace.join("icydb.toml"),
            "[canisters.workspace.sql]\nreadonly = true\n",
        )
        .expect("workspace config should be written");
        let demo_config = workspace.join("canisters").join("demo").join("icydb.toml");
        fs::write(
            demo_config.as_path(),
            "[canisters.demo_rpg.sql]\nreadonly = true\n",
        )
        .expect("demo config should be written");

        let resolved = resolve_config_path(canister.as_path());

        assert_eq!(resolved.config_path.as_deref(), Some(demo_config.as_path()));
        fs::remove_dir_all(root).expect("test directory should be removed");
    }

    #[test]
    fn load_resolved_config_reports_path_and_validated_config() {
        let root = env::temp_dir().join(format!(
            "icydb-config-build-load-test-{}",
            std::process::id()
        ));
        let canister = root.join("canisters").join("demo").join("rpg");
        fs::create_dir_all(canister.as_path()).expect("test directory should be created");
        let config_path = root.join("canisters").join("demo").join(CONFIG_FILE_NAME);
        fs::write(
            config_path.as_path(),
            r"
                [canisters.demo_rpg.sql]
                readonly = true
                ddl = true
                fixtures = true
            ",
        )
        .expect("config should be written");

        let resolved = load_resolved_icydb_toml(canister.as_path(), &["demo_rpg"])
            .expect("resolved config should load");

        assert_eq!(resolved.config_path(), Some(config_path.as_path()));
        assert!(resolved.config().canister_sql_readonly_enabled("demo_rpg"));
        assert!(resolved.config().canister_sql_ddl_enabled("demo_rpg"));
        assert!(resolved.config().canister_sql_fixtures_enabled("demo_rpg"));
        fs::remove_dir_all(root).expect("test directory should be removed");
    }
}