From 7ba92508622a68402653bd5e9678bf96a3b02633 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:01:05 -0500 Subject: [PATCH 1/6] feat(rust): read YAML, resolve sources and config, add naming (R3, preview) The Rust loader reads authoring YAML (ADR-0006 desugar, the coercion guard, line and column on every YAML error), and the crate resolves a project: the .metaobjects/config.json reader, source kinds, directory discovery, the embedded iam and ai library sources, and the naming strategies, pluralizers and collection-name collision check. Passes yaml-conformance 15 of 19, and source-resolution-conformance and naming-conformance in full. --- CHANGELOG.md | 8 + docs/CONFORMANCE.md | 15 +- server/rust/Cargo.lock | 136 ++ server/rust/metaobjects/Cargo.toml | 1 + server/rust/metaobjects/build.rs | 71 + .../rust/metaobjects/examples/load_bench.rs | 178 ++- server/rust/metaobjects/src/collection.rs | 309 +++++ server/rust/metaobjects/src/config.rs | 1161 +++++++++++++++++ server/rust/metaobjects/src/errors.rs | 15 + server/rust/metaobjects/src/lib.rs | 10 +- server/rust/metaobjects/src/library.rs | 257 ++++ server/rust/metaobjects/src/loader.rs | 47 +- server/rust/metaobjects/src/naming.rs | 1145 ++++++++++++++++ server/rust/metaobjects/src/parser.rs | 34 +- server/rust/metaobjects/src/source.rs | 46 +- server/rust/metaobjects/src/sources.rs | 242 ++++ server/rust/metaobjects/src/yaml.rs | 407 ++++++ .../rust/metaobjects/tests/config_reader.rs | 621 +++++++++ .../tests/conformance-expected-failures.json | 4 +- .../naming-conformance-expected-failures.json | 1 + .../metaobjects/tests/naming_conformance.rs | 455 +++++++ server/rust/metaobjects/tests/project_load.rs | 147 +++ .../source-resolution-expected-failures.json | 5 + .../tests/source_resolution_conformance.rs | 168 +++ .../yaml-conformance-expected-failures.json | 12 + .../metaobjects/tests/yaml_conformance.rs | 173 +++ 26 files changed, 5617 insertions(+), 51 deletions(-) create mode 100644 server/rust/metaobjects/build.rs create mode 100644 server/rust/metaobjects/src/collection.rs create mode 100644 server/rust/metaobjects/src/config.rs create mode 100644 server/rust/metaobjects/src/library.rs create mode 100644 server/rust/metaobjects/src/naming.rs create mode 100644 server/rust/metaobjects/src/sources.rs create mode 100644 server/rust/metaobjects/src/yaml.rs create mode 100644 server/rust/metaobjects/tests/config_reader.rs create mode 100644 server/rust/metaobjects/tests/naming-conformance-expected-failures.json create mode 100644 server/rust/metaobjects/tests/naming_conformance.rs create mode 100644 server/rust/metaobjects/tests/project_load.rs create mode 100644 server/rust/metaobjects/tests/source-resolution-expected-failures.json create mode 100644 server/rust/metaobjects/tests/source_resolution_conformance.rs create mode 100644 server/rust/metaobjects/tests/yaml-conformance-expected-failures.json create mode 100644 server/rust/metaobjects/tests/yaml_conformance.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index bc3b11affc..c6a41a3e94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,14 @@ here.** or `cargo meta` command yet. A `rust` lane runs `cargo fmt --check`, clippy and the tests in `scripts/ci-local.sh --only rust`, `pr-ci` and `local-ci`, selected by changes under `server/rust/`. +- **Rust port reads a real project, in preview.** The loader now reads YAML authoring files + (ADR-0006: bare type keys, scalar-body names, the `[]` suffix, sigil-free attributes, anchors and + aliases, the `ERR_YAML_COERCION` guard, and a line and column on every error from a YAML file), + and the crate resolves a project the way the other ports do: the `.metaobjects/config.json` + reader, the four source kinds, directory discovery (symlinks followed, `_pending` skipped), the + `iam` and `ai` library sources embedded in the crate, and the naming strategies, pluralizers and + collection-name collision check. It passes `yaml-conformance` 15 of 19, and the + `source-resolution-conformance` and `naming-conformance` corpora in full. Nothing is published. ### Changed diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 16e6366afd..311bb107fe 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -69,14 +69,17 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | -**Rust (preview, ADR-0065) is not a column yet.** The sixth port runs two corpora -today: `registry-conformance` (byte-identical manifest) and the metamodel corpus, 256 -of 510 green with the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` +**Rust (preview, ADR-0065) is not a column yet.** The sixth port runs five corpora +today: `registry-conformance` (byte-identical manifest); the metamodel corpus, 261 +of 526 green with the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` (validation passes, merge warnings, the reporting short-name rule and the `script.json` -fixtures, none of them built yet). That ledger may only shrink. While the port is in +fixtures, none of them built yet); `yaml-conformance`, 15 of 19 (the four on +`yaml-conformance-expected-failures.json` wait for the attribute-schema pass and the +ADR-0059 reference rules); `source-resolution-conformance` (all 27 cases); and +`naming-conformance` (all of it). Those ledgers may only shrink. While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when the port leaves preview. A regression still -fails: the ledger's `minPassing` (256) is the number of fixtures known to pass, and the run +fails: the ledger's `minPassing` (261) is the number of fixtures known to pass, and the run fails when fewer do. The column joins this table when the port leaves preview. @@ -394,7 +397,7 @@ Per-port runners + commands: | Kotlin | `cd server/java && mvn -pl codegen-kotlin test` (snapshot suite) | `mvn -f server/java/integration-tests-kotlin/pom.xml test` (needs Docker) | `mvn -f server/java/integration-tests-kotlin/pom.xml test -Dtest=ApiContractConformanceTest` (needs Docker) | | C# | `dotnet test` (per project) | `scripts/integration-test.sh csharp` (needs Docker) | `dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj --filter "FullyQualifiedName~ApiContractConformanceTest"` (needs Docker) | | Python | `pytest` (per package) | `scripts/integration-test.sh python` (needs Docker) | `cd server/python && uv run --extra integration pytest tests/integration/test_api_contract.py` (needs Docker) | -| Rust (preview) | `cd server/rust && cargo test` (registry + metamodel corpora) | — | — | +| Rust (preview) | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution and naming corpora) | — | — | The `persistence-conformance` corpus is intentionally **on-demand** — none of the unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index e7a15d74ad..1815dc38d9 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -2,6 +2,44 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -19,6 +57,18 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] [[package]] name = "indexmap" @@ -47,9 +97,34 @@ name = "metaobjects" version = "0.1.0" dependencies = [ "indexmap", + "saphyr", "serde_json", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -68,6 +143,41 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "saphyr" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "239ada9508355b353044d043e5806c6d84030234503b62ccb8785f549cd9359b" +dependencies = [ + "encoding_rs", + "hashlink", + "ordered-float", + "saphyr-parser", + "thiserror", +] + +[[package]] +name = "saphyr-parser" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c98d2738e44a25e6ba2e6d83d91805648df204768abc96f4f1278cb3d5c90bbe" +dependencies = [ + "arraydeque", + "thiserror", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -112,6 +222,12 @@ dependencies = [ "zmij", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "syn" version = "3.0.10" @@ -123,6 +239,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/server/rust/metaobjects/Cargo.toml b/server/rust/metaobjects/Cargo.toml index a2f453b242..924c916d9f 100644 --- a/server/rust/metaobjects/Cargo.toml +++ b/server/rust/metaobjects/Cargo.toml @@ -12,6 +12,7 @@ publish = false [dependencies] serde_json.workspace = true indexmap.workspace = true +saphyr = "0.3.4" [lints] workspace = true diff --git a/server/rust/metaobjects/build.rs b/server/rust/metaobjects/build.rs new file mode 100644 index 0000000000..68b9e98c8b --- /dev/null +++ b/server/rust/metaobjects/build.rs @@ -0,0 +1,71 @@ +//! Embeds the repo-root `library/` tree (YAML files and `library.json` manifests) +//! into the crate, as the other ports do, so a shipped library resolves with no +//! file on disk. When the directory is absent (the crate built outside the +//! repository) the embed is empty. + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; + +fn collect( + dir: &Path, + rel: &str, + yaml: &mut Vec<(String, PathBuf)>, + manifests: &mut Vec<(String, PathBuf)>, +) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + let child_rel = if rel.is_empty() { + name.clone() + } else { + format!("{rel}/{name}") + }; + if path.is_dir() { + collect(&path, &child_rel, yaml, manifests); + } else if let Some(r) = child_rel.strip_suffix(".yaml") { + yaml.push((r.to_string(), path)); + } else if name == "library.json" && !rel.is_empty() && !rel.contains('/') { + manifests.push((rel.to_string(), path)); + } + } +} + +fn main() { + let manifest_dir = + PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); + let lib_dir = manifest_dir.join("../../../library"); + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={}", lib_dir.display()); + let (mut yaml, mut manifests) = (Vec::new(), Vec::new()); + collect(&lib_dir, "", &mut yaml, &mut manifests); + yaml.sort(); + manifests.sort(); + for (_, p) in yaml.iter().chain(manifests.iter()) { + println!("cargo:rerun-if-changed={}", p.display()); + } + let mut out = String::new(); + for (name, list) in [ + ("EMBEDDED_LIBRARY", &yaml), + ("EMBEDDED_LIBRARY_MANIFESTS", &manifests), + ] { + let _ = writeln!(out, "pub static {name}: &[(&str, &str)] = &["); + for (key, path) in list { + let abs = std::fs::canonicalize(path).expect("canonicalize library file"); + let _ = writeln!( + out, + " ({key:?}, include_str!({:?})),", + abs.display().to_string() + ); + } + out.push_str("];\n"); + } + let dest = + PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR")).join("embedded_library.rs"); + let unchanged = std::fs::read_to_string(&dest).is_ok_and(|old| old == out); + if !unchanged { + std::fs::write(dest, out).expect("write embedded_library.rs"); + } +} diff --git a/server/rust/metaobjects/examples/load_bench.rs b/server/rust/metaobjects/examples/load_bench.rs index cf8f17fb59..52037d4bcf 100644 --- a/server/rust/metaobjects/examples/load_bench.rs +++ b/server/rust/metaobjects/examples/load_bench.rs @@ -8,15 +8,22 @@ //! Run it in release mode: //! //! ```text -//! cargo run --release --example load_bench [-- ] +//! cargo run --release --example load_bench [-- [json|yaml|project|all]] //! ``` +//! +//! `json`, `yaml` and `project` run one part only, so a peak-memory reading (for example +//! `/usr/bin/time -f %M`) belongs to that format alone. `all` is the default. use std::time::{Duration, Instant}; +use metaobjects::collection::resolve_collection; use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; use metaobjects::node::{NodeId, Tree}; use metaobjects::providers::default_registry; use metaobjects::serializer::canonical_serialize; +use metaobjects::yaml::parse_yaml; +use serde_json::Value; const FITNESS: &str = include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); @@ -39,6 +46,80 @@ fn read_pass(tree: &Tree) -> usize { n } +/// A canonical node as sigil-free authoring YAML (ADR-0006): attributes lose +/// their `@`, and the fused `type.subType` key stays. `prefix` is the text before +/// the key on its first line (`"- "` for a list item), which also sets the +/// column the body lines up under. +fn emit_node(out: &mut String, prefix: &str, node: &Value) { + let (key, body) = node + .as_object() + .and_then(|m| m.iter().next()) + .expect("a node is a one-key wrapper"); + out.push_str(&format!("{prefix}{key}:\n")); + let pad = " ".repeat(prefix.len() + 2); + for (k, v) in body.as_object().expect("a node body is a mapping") { + if k == "children" { + out.push_str(&format!("{pad}children:\n")); + for child in v.as_array().expect("children is a list") { + emit_node(out, &format!("{pad} - "), child); + } + } else { + let k = k.strip_prefix('@').unwrap_or(k); + // A JSON value is a YAML flow value. + out.push_str(&format!("{pad}{k}: {v}\n")); + } + } +} + +fn to_yaml(json: &str) -> String { + let doc: Value = serde_json::from_str(json).expect("the model is JSON"); + let mut out = String::new(); + emit_node(&mut out, "", &doc); + out +} + +/// The project-reading steps, each timed on its own: read the config, walk the +/// metadata directory, and read every file's text. The model is written to a +/// scratch directory (`$DEV_SCRATCH`, a RAM disk) and removed afterwards. +fn project_rows(sources: &[(String, String)], iterations: usize) { + let base = std::env::var_os("DEV_SCRATCH") + .map(std::path::PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("mo-load-bench-{}", std::process::id())); + std::fs::create_dir_all(dir.join(".metaobjects")).expect("scratch dir"); + std::fs::create_dir_all(dir.join("metaobjects")).expect("scratch dir"); + std::fs::write( + dir.join(".metaobjects/config.json"), + r#"{ "schema_version": 1, "naming": { "columns": "snake_case" }, "libraries": ["iam", "ai"] }"#, + ) + .expect("config"); + for (id, text) in sources { + std::fs::write(dir.join("metaobjects").join(id), text).expect("model file"); + } + let naming = NamingRegistry::builtin(); + let (mut resolves, mut reads) = (Vec::new(), Vec::new()); + for _ in 0..iterations { + let t = Instant::now(); + let collection = resolve_collection(&dir, None, &naming).expect("the project resolves"); + resolves.push(t.elapsed()); + let t = Instant::now(); + let (pairs, errors) = collection.read_sources(); + reads.push(t.elapsed()); + assert!(errors.is_empty(), "{errors:?}"); + std::hint::black_box(pairs); + } + let _ = std::fs::remove_dir_all(&dir); + println!( + "project: config read + directory walk ({} files), median of {iterations}: {:?}", + sources.len(), + median(resolves) + ); + println!( + "project: read every file's text plus the library sources, median of {iterations}: {:?}", + median(reads) + ); +} + fn main() { let mut args = std::env::args().skip(1); let copies: usize = args @@ -47,6 +128,14 @@ fn main() { let iterations: usize = args .next() .map_or(15, |a| a.parse().expect("iterations is a number")); + let mode = args.next().unwrap_or_else(|| "all".to_string()); + let (do_json, do_yaml, do_project) = match mode.as_str() { + "json" => (true, false, false), + "yaml" => (false, true, false), + "project" => (false, false, true), + "all" => (true, true, true), + other => panic!("mode is json, yaml or all, not {other}"), + }; assert!( FITNESS.contains(ROOT_PACKAGE), "the fitness model declares its root package" @@ -62,6 +151,22 @@ fn main() { }) .collect(); let bytes: usize = sources.iter().map(|(_, t)| t.len()).sum(); + let yaml_sources: Vec<(String, String)> = if do_yaml { + sources + .iter() + .map(|(id, text)| (id.replace(".json", ".yaml"), to_yaml(text))) + .collect() + } else { + Vec::new() + }; + let yaml_bytes: usize = yaml_sources.iter().map(|(_, t)| t.len()).sum(); + + if do_project { + project_rows(&sources, iterations); + if !do_json && !do_yaml { + return; + } + } let t = Instant::now(); let registry = default_registry().expect("the built-in providers compose"); @@ -69,20 +174,52 @@ fn main() { let loader = Loader::new(®istry); let mut loads = Vec::with_capacity(iterations); + let mut yaml_loads = Vec::with_capacity(iterations); + let mut yaml_desugars = Vec::with_capacity(iterations); let mut serializes = Vec::with_capacity(iterations); let mut cold_reads = Vec::with_capacity(iterations); let mut warm_reads = Vec::with_capacity(iterations); let mut nodes = 0; for _ in 0..iterations { - let t = Instant::now(); - let result = loader.load_sources(&sources); - loads.push(t.elapsed()); - assert!( - result.errors.is_empty(), - "the scaled model loads clean: {:?}", - result.errors.first() - ); - nodes = result.tree.len(); + let mut loaded = None; + if do_json { + let t = Instant::now(); + let result = loader.load_sources(&sources); + loads.push(t.elapsed()); + assert!( + result.errors.is_empty(), + "the scaled model loads clean: {:?}", + result.errors.first() + ); + nodes = result.tree.len(); + loaded = Some(result); + } + if do_yaml { + let t = Instant::now(); + for (id, text) in &yaml_sources { + std::hint::black_box(parse_yaml(text, ®istry, id).expect("the YAML parses")); + } + yaml_desugars.push(t.elapsed()); + let t = Instant::now(); + let yaml_result = loader.load_sources(&yaml_sources); + yaml_loads.push(t.elapsed()); + assert!( + yaml_result.errors.is_empty(), + "the YAML model loads clean: {:?}", + yaml_result.errors.first() + ); + if do_json { + assert_eq!( + yaml_result.tree.len(), + nodes, + "YAML and JSON load the same nodes" + ); + } else { + nodes = yaml_result.tree.len(); + } + loaded.get_or_insert(yaml_result); + } + let result = loaded.expect("one format ran"); let t = Instant::now(); std::hint::black_box(read_pass(&result.tree)); cold_reads.push(t.elapsed()); @@ -99,10 +236,23 @@ fn main() { bytes / 1024 ); println!("registry compose: {compose:?}"); - println!( - "load (parse, merge, extends, references), median of {iterations}: {:?}", - median(loads) - ); + if do_json { + println!( + "load (parse, merge, extends, references), median of {iterations}: {:?}", + median(loads) + ); + } + if do_yaml { + println!( + "YAML ({} KiB): parse and desugar only, median of {iterations}: {:?}", + yaml_bytes / 1024, + median(yaml_desugars) + ); + println!( + "YAML load (parse, desugar, merge, extends, references), median of {iterations}: {:?}", + median(yaml_loads) + ); + } println!( "resolved reads of every node (children, attrs, is_array), first pass fills the cache, median of {iterations}: {:?}", median(cold_reads) diff --git a/server/rust/metaobjects/src/collection.rs b/server/rust/metaobjects/src/collection.rs new file mode 100644 index 0000000000..1d6336b1e8 --- /dev/null +++ b/server/rust/metaobjects/src/collection.rs @@ -0,0 +1,309 @@ +//! `resolve_collection`: the single authority on where a project's metadata +//! lives, ported from the TypeScript SDK's `collection.ts` and `discovery.ts`. +//! +//! `metaobjects/` is the DEFAULT value of `sources`, never a requirement. +//! Dependency snapshots are not resolved here: a config that declares +//! `dependencies` gets them back unresolved in [`Collection::dependencies`]. + +use std::path::{Path, PathBuf}; + +use crate::config::{ + ApiPagination, Config, DependencySpec, EnumDefaults, HandEditsPolicy, Scope, UnknownFieldsMode, + WireFormat, load_config, +}; +use crate::errors::{ERR_COLLECTION_NOT_FOUND, ERR_UNKNOWN, ERR_UNKNOWN_LIBRARY, MetaError}; +use crate::library::{known_library_tokens, library_sources, unknown_library_tokens}; +use crate::naming::{NamingRegistry, PhysicalNaming}; +use crate::source::ErrorSource; +use crate::sources::{ + CONFIG_FILE, DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, ResolvedSource, SourceSpec, + absolutize, default_sources, is_metadata_file, ordered_path_specs, resolve_sources, + resolve_spec_path, +}; + +const GIT_DIR: &str = ".git"; +/// Bound on the metadata-document sniff used to improve one error message. +const MAX_SNIFFED_FILES: usize = 20; + +/// A resolved project: where its config lives, which files it reads and every +/// setting the config declares. +#[derive(Debug, Clone)] +pub struct Collection { + /// Directory whose config declared this collection (or the resolved start + /// directory, when nothing was discovered and the default applies). + pub config_dir: PathBuf, + /// Canonically ordered absolute metadata file paths. With dependencies + /// unresolved this equals [`Collection::own_files`]. + pub files: Vec, + /// Same set, carrying the contributing spec. + pub sources: Vec, + /// The distinct roots the declared specs resolve to, in canonical order. + pub source_roots: Vec, + /// The project's own metadata files. + pub own_files: Vec, + /// Declared dependencies, validated but NOT resolved against any snapshot. + pub dependencies: Vec, + /// The shipped-library selection as authored. + pub libraries: Vec, + pub physical_naming: PhysicalNaming, + pub wire_format: WireFormat, + pub enum_defaults: EnumDefaults, + pub api_pagination: Option, + pub api_unknown_fields: Option, + /// `migrate.conventions`. + pub schema_conventions: Option, + /// `migrate.checks.skipRedundant`; false when absent. + pub skip_redundant_checks: bool, + /// `migrate.foreignKeyIndexes`; false when absent. + pub foreign_key_indexes: bool, + /// `verify.handEdits`. + pub hand_edits: Option, + /// The declared `scope`, parsed (matching is not part of this module). + pub scope: Option, + /// `migrate.scope` patterns. + pub migrate_scope: Option>, + /// `requirements.inherit` patterns. + pub requirements_inherit: Option>, + /// The whole parsed config; the default config when none was found. + pub config: Config, + /// Warnings reading the config produced (unknown top-level keys). + pub warnings: Vec, +} + +impl Collection { + /// The ordered `(id, text)` pairs the loader should receive: the selected + /// shipped libraries first (ids like `library:iam/model.yaml`), then the + /// project's own files (ids are their absolute paths). A file that cannot be + /// read is returned as an error and the rest are still returned. + pub fn read_sources(&self) -> (Vec<(String, String)>, Vec) { + let mut out = library_sources(&self.libraries); + let mut errors = Vec::new(); + for file in &self.files { + let id = file.to_string_lossy().into_owned(); + match std::fs::read_to_string(file) { + Ok(text) => out.push((id, text)), + Err(e) => errors.push(MetaError::at( + ERR_UNKNOWN, + format!("{id}: cannot read metadata file: {e}"), + ErrorSource::json(&id, "$"), + )), + } + } + (out, errors) + } +} + +fn exists(p: &Path) -> bool { + std::fs::metadata(p).is_ok() +} + +fn is_dir(p: &Path) -> bool { + std::fs::metadata(p).is_ok_and(|m| m.is_dir()) +} + +/// Where the discovery walk stopped, and what it found there. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiscoveredRoot { + pub dir: PathBuf, + /// Whether `dir` carries `.metaobjects/config.json`. False only on the + /// no-marker fallback, where the default sources apply. + pub has_config: bool, +} + +/// Walk up from `start_dir` for the nearest directory holding +/// `.metaobjects/config.json`, the only project marker. The walk stops after a +/// directory containing `.git`, checked AFTER the marker so a repo-root project +/// stays findable. With no marker it reports the resolved start directory. +pub fn discover_collection_root(start_dir: &Path) -> DiscoveredRoot { + let start = absolutize(start_dir); + let mut dir = start.clone(); + loop { + if exists(&dir.join(DEFAULT_METAOBJECTS_DIR).join(CONFIG_FILE)) { + return DiscoveredRoot { + dir, + has_config: true, + }; + } + if exists(&dir.join(GIT_DIR)) { + break; + } + match dir.parent() { + Some(p) => dir = p.to_path_buf(), + None => break, + } + } + DiscoveredRoot { + dir: start, + has_config: false, + } +} + +/// The directory whose configuration governs a run started in `start_dir`. +pub fn resolve_config_dir(start_dir: &Path) -> PathBuf { + discover_collection_root(start_dir).dir +} + +/// A cheap "is this file a metadata DOCUMENT?" sniff, for a diagnostic only. +fn sniffs_as_metadata_document(file: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(file) else { + return false; + }; + let is_json = file + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("json")); + if !is_json { + return text.lines().any(|l| { + l.strip_prefix("metadata") + .is_some_and(|r| r.trim_start().starts_with(':')) + }); + } + serde_json::from_str::(&text) + .ok() + .is_some_and(|v| { + v.as_object() + .is_some_and(|o| o.contains_key("metadata.root")) + }) +} + +/// Does `dir` hold metadata but carry no project marker: is it the METADATA +/// directory, handed to a command whose argument is the PROJECT ROOT? +fn holds_metadata_but_is_no_root(dir: &Path, has_config: bool) -> bool { + if has_config { + return false; + } + let Ok(read) = std::fs::read_dir(dir) else { + return false; + }; + let mut names: Vec = read + .filter_map(Result::ok) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| is_metadata_file(n)) + .collect(); + names.sort(); + names + .iter() + .take(MAX_SNIFFED_FILES) + .any(|n| sniffs_as_metadata_document(&dir.join(n))) +} + +/// THE single authority on where metadata lives. +/// +/// An `explicit_dir` wins outright; otherwise discovery walks up from +/// `start_dir`. A config that EXISTS but is invalid is the author's error and +/// propagates. Only an absent config falls through to the default `metaobjects` +/// directory, and `ERR_COLLECTION_NOT_FOUND` is raised only when no sources were +/// declared AND that default does not exist. A declared source that does not +/// resolve is `ERR_SOURCE_UNRESOLVED`. +pub fn resolve_collection( + start_dir: &Path, + explicit_dir: Option<&Path>, + naming: &NamingRegistry, +) -> Result { + let (config_dir, has_config) = match explicit_dir { + Some(dir) => { + let dir = absolutize(dir); + let has = exists(&dir.join(DEFAULT_METAOBJECTS_DIR).join(CONFIG_FILE)); + (dir, has) + } + None => { + let found = discover_collection_root(start_dir); + (found.dir, found.has_config) + } + }; + + let mut config = Config::default(); + let mut warnings = Vec::new(); + if has_config { + let loaded = load_config(&config_dir.join(DEFAULT_METAOBJECTS_DIR), naming)?; + config = loaded.config; + warnings = loaded.warnings; + // A token a human typed into a config is a mistake worth failing on. + let unknown = unknown_library_tokens(&config.libraries); + if !unknown.is_empty() { + let quoted = |v: &[String]| { + let items: Vec = v.iter().map(|s| format!("\"{s}\"")).collect(); + format!("[{}]", items.join(",")) + }; + return Err(MetaError::code( + ERR_UNKNOWN_LIBRARY, + format!( + ".metaobjects/config.json in {}: 'libraries' names unknown librar{} {}; available: {}.", + config_dir.display(), + if unknown.len() == 1 { "y" } else { "ies" }, + quoted(&unknown), + quoted(&known_library_tokens()), + ), + )); + } + } + + let using_default = config.sources.is_empty(); + let specs: Vec = if using_default { + default_sources() + } else { + config.sources.clone() + }; + + if using_default && !is_dir(&config_dir.join(DEFAULT_METADATA_DIR)) { + if holds_metadata_but_is_no_root(&config_dir, has_config) { + let parent = config_dir.parent().unwrap_or(&config_dir).to_path_buf(); + let near = discover_collection_root(&parent); + let suggested = if near.has_config { near.dir } else { parent }; + return Err(MetaError::code( + ERR_COLLECTION_NOT_FOUND, + format!( + "{} looks like a metadata directory, not a project root — it holds metadata files but carries no {DEFAULT_METAOBJECTS_DIR}/{CONFIG_FILE}. A directory argument here is the PROJECT ROOT that CONTAINS your metadata; where the metadata lives is then the root's \"sources\" (default: the \"{DEFAULT_METADATA_DIR}\" directory beneath it). Try {} instead.", + config_dir.display(), + suggested.display() + ), + )); + } + return Err(MetaError::code( + ERR_COLLECTION_NOT_FOUND, + format!( + "no metadata sources declared in {} and no default \"{DEFAULT_METADATA_DIR}\" directory found. Declare \"sources\" in {DEFAULT_METAOBJECTS_DIR}/{CONFIG_FILE} — each entry is an OBJECT, e.g. \"sources\": [{{ \"path\": \"model\" }}] — or run 'meta init' to scaffold.", + config_dir.display() + ), + )); + } + + let own_sources = resolve_sources(&config_dir, &specs)?; + let own_files: Vec = own_sources.iter().map(|s| s.file.clone()).collect(); + + let mut source_roots: Vec = Vec::new(); + for (path, _) in ordered_path_specs(&specs)? { + let root = resolve_spec_path(&config_dir, &path); + if !source_roots.contains(&root) { + source_roots.push(root); + } + } + + let migrate = config.migrate.clone(); + Ok(Collection { + config_dir, + files: own_files.clone(), + own_files, + sources: own_sources, + source_roots, + dependencies: config.dependencies.clone(), + libraries: config.libraries.clone(), + physical_naming: config.physical_naming(), + wire_format: config.wire_format(), + enum_defaults: config.enum_defaults(), + api_pagination: config.api_pagination(), + api_unknown_fields: config.api_unknown_fields(), + schema_conventions: migrate.as_ref().and_then(|m| m.conventions.clone()), + skip_redundant_checks: migrate + .as_ref() + .is_some_and(|m| m.checks_skip_redundant == Some(true)), + foreign_key_indexes: migrate + .as_ref() + .is_some_and(|m| m.foreign_key_indexes == Some(true)), + hand_edits: config.hand_edits, + scope: config.scope.clone(), + migrate_scope: migrate.and_then(|m| m.scope), + requirements_inherit: config.requirements_inherit.clone(), + config, + warnings, + }) +} diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs new file mode 100644 index 0000000000..ac3e9cadcb --- /dev/null +++ b/server/rust/metaobjects/src/config.rs @@ -0,0 +1,1161 @@ +//! The reader for `.metaobjects/config.json`, ported from the TypeScript SDK's +//! `config.ts` (a zod schema there, hand-written validation over +//! `serde_json::Value` here). +//! +//! Strictness follows the TypeScript reader. A key this version does not know at +//! the TOP level is a warning returned as data (a newer MetaObjects may have +//! written it); a wrong type on a known key, and an unknown key inside a block +//! the reader owns, is an error that names the file and each problem. The two +//! blocks TypeScript leaves non-strict (`confidence_thresholds`, `extract`) +//! ignore unknown keys here too. + +use std::path::Path; + +use serde_json::{Map, Value}; + +use crate::errors::{ERR_BAD_ATTR_VALUE, ERR_MALFORMED_JSON, ERR_UNKNOWN, MetaError}; +use crate::naming::{NamingKind, NamingRegistry, PhysicalNaming}; +use crate::sources::{CONFIG_FILE, SourceSpec}; + +/// The only `schema_version` this reader accepts. +pub const SCHEMA_VERSION: u64 = 1; +/// The largest page size every port's integer type holds. +pub const PAGE_SIZE_MAX: u64 = 2_147_483_647; +/// The largest integer a JSON number can carry exactly. +const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + +/// The top-level keys this version reads. +pub const CONFIG_TOP_LEVEL_KEYS: &[&str] = &[ + "schema_version", + "pending_in_git", + "confidence_thresholds", + "sources", + "dependencies", + "libraries", + "scope", + "extract", + "migrate", + "verify", + "requirements", + "naming", + "wire", + "api", + "enums", + "csharp", +]; + +/// The `migrate.allow` tokens (kept in step with the CLI's `ALLOW_TOKENS`). +pub const ALLOW_TOKENS: &[&str] = &[ + "drop-column", + "drop-table", + "type-change", + "drop-index", + "drop-fk", + "drop-check", + "drop-view", + "drop-view-cascade", + "drop-column-read-by-view", + "adopt-view", + "nullable-to-not-null", + "drop-identity-default", + "drop-unmanaged", + "drop-comment", +]; +const MIGRATE_DIALECTS: &[&str] = &["sqlite", "postgres", "d1"]; +const MIGRATE_FORMATS: &[&str] = &["default", "flyway"]; +const MIGRATE_ON_AMBIGUOUS: &[&str] = &["abort", "rename", "drop-add"]; + +macro_rules! string_enum { + ($(#[$m:meta])* $name:ident { $($var:ident => $s:literal),+ $(,)? }) => { + $(#[$m])* + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum $name { $($var),+ } + impl $name { + /// Every accepted spelling, in declaration order. + pub const ALL: &'static [&'static str] = &[$($s),+]; + pub fn parse(s: &str) -> Option { + match s { $($s => Some(Self::$var),)+ _ => None } + } + pub fn as_str(self) -> &'static str { + match self { $(Self::$var => $s),+ } + } + } + }; +} + +string_enum!( + /// `wire.decimals`. + WireDecimals { Native => "native", String => "string" } +); +string_enum!( + /// `wire.nullMembers`. + WireNullMembers { Native => "native", Emit => "emit", Omit => "omit" } +); +string_enum!( + /// `wire.durations`. + WireDurations { Native => "native", Iso => "iso" } +); +string_enum!( + /// `api.unknownFields`. + UnknownFieldsMode { Reject => "reject", Drop => "drop" } +); +string_enum!( + /// `verify.handEdits`. + HandEditsPolicy { Fail => "fail", Notice => "notice" } +); + +/// The output form of a generated REST surface, each absent key at its default. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WireFormat { + pub decimals: WireDecimals, + pub null_members: WireNullMembers, + pub durations: WireDurations, +} + +impl Default for WireFormat { + fn default() -> Self { + Self { + decimals: WireDecimals::Native, + null_members: WireNullMembers::Native, + durations: WireDurations::Native, + } + } +} + +/// The `wire` block as written; absent keys are `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct WireConfig { + pub decimals: Option, + pub null_members: Option, + pub durations: Option, +} + +/// The page size of generated list routes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ApiPagination { + pub default_limit: u32, + pub max_limit: u32, +} + +/// The `api` block. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ApiConfig { + pub pagination: Option, + pub unknown_fields: Option, +} + +/// The string-stored enum defaults (`enums`); none when absent. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct EnumDefaults { + pub max_length: Option, +} + +/// The `naming` block as written. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct NamingConfig { + pub columns: Option, + pub tables: Option, + pub collections: Option, +} + +/// An output filter: include and exclude package patterns. Parsed and validated +/// only; matching is not part of this module. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Scope { + pub include: Option>, + pub exclude: Option>, +} + +/// `confidence_thresholds`, defaults applied. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ConfidenceThresholds { + pub pending_promote: f64, + pub drift_warn: f64, +} + +impl Default for ConfidenceThresholds { + fn default() -> Self { + Self { + pending_promote: 0.8, + drift_warn: 0.7, + } + } +} + +/// `migrate.d1`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct D1Block { + pub binding: Option, + pub remote: Option, + pub auto_apply: Option, + pub wrangler_config_path: Option, +} + +/// The `migrate` block: every key optional, every unknown key an error. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct MigrateConfig { + pub out_dir: Option, + pub database_url: Option, + pub shadow_database_url: Option, + pub dialect: Option, + pub format: Option, + pub on_ambiguous: Option, + pub allow: Option>, + pub d1: Option, + pub scope: Option>, + pub conventions: Option, + /// `migrate.checks.skipRedundant`. + pub checks_skip_redundant: Option, + /// `migrate.checks` was present (possibly empty). + pub checks_present: bool, + pub foreign_key_indexes: Option, +} + +/// One declared metadata dependency (FR-023). Parsed and validated only. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DependencySpec { + pub name: String, + pub transport: DependencyTransport, +} + +/// The one transport a dependency names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DependencyTransport { + Path(String), + Npm { + npm: String, + dir: Option, + }, + Python { + python: String, + dir: Option, + }, + Maven { + maven: String, + version: String, + dir: Option, + }, + Nuget { + nuget: String, + version: String, + dir: Option, + }, +} + +/// A C# metadata provider: a built assembly and the provider's full type name. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CsharpProvider { + pub assembly: String, + pub type_name: String, +} + +/// The `csharp` block. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CsharpConfig { + pub out_dir: Option, + pub namespace: Option, + pub providers: Option>, +} + +/// A parsed `.metaobjects/config.json`, defaults applied. +#[derive(Debug, Clone, PartialEq)] +pub struct Config { + pub schema_version: u64, + pub pending_in_git: bool, + pub confidence_thresholds: ConfidenceThresholds, + pub sources: Vec, + pub dependencies: Vec, + pub libraries: Vec, + pub scope: Option, + /// `extract.metaignore`. + pub extract_metaignore: Option, + pub migrate: Option, + /// `verify.handEdits`; `None` when the block or the key is absent. + pub hand_edits: Option, + /// `requirements.inherit`. + pub requirements_inherit: Option>, + pub naming: Option, + pub wire: Option, + pub api: Option, + pub enums: Option, + pub csharp: Option, +} + +impl Default for Config { + /// What `{ "schema_version": 1 }` parses to. + fn default() -> Self { + Self { + schema_version: SCHEMA_VERSION, + pending_in_git: true, + confidence_thresholds: ConfidenceThresholds::default(), + sources: Vec::new(), + dependencies: Vec::new(), + libraries: Vec::new(), + scope: None, + extract_metaignore: None, + migrate: None, + hand_edits: None, + requirements_inherit: None, + naming: None, + wire: None, + api: None, + enums: None, + csharp: None, + } + } +} + +impl Config { + /// The physical-naming rules, each absent rule at its default. + pub fn physical_naming(&self) -> PhysicalNaming { + let d = PhysicalNaming::default(); + let n = self.naming.clone().unwrap_or_default(); + PhysicalNaming { + columns: n.columns.unwrap_or(d.columns), + tables: n.tables.unwrap_or(d.tables), + collections: n.collections, + } + } + + /// The wire format, each absent key at its default. + pub fn wire_format(&self) -> WireFormat { + let d = WireFormat::default(); + let w = self.wire.unwrap_or_default(); + WireFormat { + decimals: w.decimals.unwrap_or(d.decimals), + null_members: w.null_members.unwrap_or(d.null_members), + durations: w.durations.unwrap_or(d.durations), + } + } + + /// The enum storage defaults; none when absent. + pub fn enum_defaults(&self) -> EnumDefaults { + self.enums.unwrap_or_default() + } + + /// `api.pagination`; `None` when absent. + pub fn api_pagination(&self) -> Option { + self.api.and_then(|a| a.pagination) + } + + /// `api.unknownFields`; `None` when absent (the default, `reject`). + pub fn api_unknown_fields(&self) -> Option { + self.api.and_then(|a| a.unknown_fields) + } +} + +/// A parsed config and the warnings reading it produced. +#[derive(Debug, Clone, PartialEq)] +pub struct LoadedConfig { + pub config: Config, + /// One message per unknown top-level key; nothing is printed. + pub warnings: Vec, +} + +// --------------------------------------------------------------------------- +// Validation helpers + +#[derive(Default)] +struct Issues(Vec<(String, String)>); + +impl Issues { + fn add(&mut self, at: &str, message: impl Into) { + self.0.push((at.to_string(), message.into())); + } +} + +fn type_name(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +fn expected(want: &str, v: &Value) -> String { + format!("Invalid input: expected {want}, received {}", type_name(v)) +} + +/// A strict object: `Some` when `v` is an object, with each unknown key reported. +fn strict_object<'a>( + v: &'a Value, + at: &str, + allowed: &[&str], + issues: &mut Issues, +) -> Option<&'a Map> { + let Some(o) = v.as_object() else { + issues.add(at, expected("object", v)); + return None; + }; + let unknown: Vec = o + .keys() + .filter(|k| !allowed.contains(&k.as_str())) + .map(|k| format!("\"{k}\"")) + .collect(); + match unknown.len() { + 0 => {} + 1 => issues.add(at, format!("Unrecognized key: {}", unknown[0])), + _ => issues.add(at, format!("Unrecognized keys: {}", unknown.join(", "))), + } + Some(o) +} + +fn string_of(v: &Value, at: &str, issues: &mut Issues) -> Option { + match v.as_str() { + Some(s) => Some(s.to_string()), + None => { + issues.add(at, expected("string", v)); + None + } + } +} + +fn nonempty_string_of(v: &Value, at: &str, issues: &mut Issues) -> Option { + let s = string_of(v, at, issues)?; + if s.is_empty() { + issues.add(at, "Too small: expected string to have >=1 characters"); + return None; + } + Some(s) +} + +fn bool_of(v: &Value, at: &str, issues: &mut Issues) -> Option { + match v.as_bool() { + Some(b) => Some(b), + None => { + issues.add(at, expected("boolean", v)); + None + } + } +} + +fn array_of<'a>(v: &'a Value, at: &str, issues: &mut Issues) -> Option<&'a Vec> { + match v.as_array() { + Some(a) => Some(a), + None => { + issues.add(at, expected("array", v)); + None + } + } +} + +fn string_array(v: &Value, at: &str, nonempty: bool, issues: &mut Issues) -> Option> { + let arr = array_of(v, at, issues)?; + let mut out = Vec::with_capacity(arr.len()); + let mut ok = true; + for (i, item) in arr.iter().enumerate() { + let item_at = format!("{at}[{i}]"); + let s = if nonempty { + nonempty_string_of(item, &item_at, issues) + } else { + string_of(item, &item_at, issues) + }; + match s { + Some(s) => out.push(s), + None => ok = false, + } + } + ok.then_some(out) +} + +fn enum_of( + v: &Value, + at: &str, + options: &[&str], + message: Option, + issues: &mut Issues, +) -> Option { + let default_message = || { + let list: Vec = options.iter().map(|o| format!("\"{o}\"")).collect(); + if v.is_string() { + format!("Invalid option: expected one of {}", list.join("|")) + } else { + expected("string", v) + } + }; + match v.as_str() { + Some(s) if options.contains(&s) => Some(s.to_string()), + _ => { + issues.add(at, message.unwrap_or_else(default_message)); + None + } + } +} + +/// A JSON number that is a whole number, however it is spelled (`50`, `50.0`, `5e1`). +fn whole_number(v: &Value) -> Option { + let f = v.as_f64()?; + (f.fract() == 0.0 && f.abs() <= MAX_SAFE_INTEGER).then_some(f) +} + +fn page_size(v: Option<&Value>, key: &str, issues: &mut Issues) -> Option { + let at = format!("api.pagination.{key}"); + let message = format!("\"api.pagination.{key}\" must be a positive integer"); + let Some(v) = v else { + issues.add(&at, message); + return None; + }; + match whole_number(v) { + Some(f) if f >= 1.0 && f <= PAGE_SIZE_MAX as f64 => Some(f as u32), + _ => { + issues.add(&at, message); + None + } + } +} + +// --------------------------------------------------------------------------- +// Blocks + +fn parse_sources(v: &Value, issues: &mut Issues) -> Vec { + let Some(arr) = array_of(v, "sources", issues) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (i, entry) in arr.iter().enumerate() { + let at = format!("sources[{i}]"); + let Some(o) = entry.as_object() else { + issues.add(&at, expected("object", entry)); + continue; + }; + let spec = (o.len() == 1) + .then(|| o.iter().next()) + .flatten() + .and_then(|(k, v)| { + let s = v.as_str().filter(|s| !s.is_empty())?.to_string(); + match k.as_str() { + "path" => Some(SourceSpec::Path(s)), + "resource" => Some(SourceSpec::Resource(s)), + "package" => Some(SourceSpec::Package(s)), + _ => None, + } + }); + match spec { + Some(s) => out.push(s), + None => issues.add( + &at, + "expected exactly one of \"path\", \"resource\" or \"package\", set to a non-empty string", + ), + } + } + out +} + +fn dependency_name_ok(name: &str) -> bool { + let mut chars = name.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "._-".contains(c)) +} + +fn parse_dependencies(v: &Value, issues: &mut Issues) -> Vec { + const TRANSPORTS: &[&str] = &["path", "npm", "python", "maven", "nuget"]; + let Some(arr) = array_of(v, "dependencies", issues) else { + return Vec::new(); + }; + let mut out: Vec = Vec::new(); + for (i, entry) in arr.iter().enumerate() { + let at = format!("dependencies[{i}]"); + let Some(o) = entry.as_object() else { + issues.add(&at, expected("object", entry)); + continue; + }; + let present: Vec<&str> = TRANSPORTS + .iter() + .copied() + .filter(|t| o.contains_key(*t)) + .collect(); + if present.len() != 1 { + issues.add( + &at, + "expected exactly one transport: \"path\", \"npm\", \"python\", \"maven\" or \"nuget\"", + ); + continue; + } + let transport = present[0]; + let mut allowed = vec!["name", transport]; + if transport != "path" { + allowed.push("dir"); + } + if matches!(transport, "maven" | "nuget") { + allowed.push("version"); + } + let before = issues.0.len(); + let unknown: Vec = o + .keys() + .filter(|k| !allowed.contains(&k.as_str())) + .map(|k| format!("\"{k}\"")) + .collect(); + if !unknown.is_empty() { + issues.add(&at, format!("Unrecognized key: {}", unknown.join(", "))); + } + let name = match o.get("name") { + Some(n) => string_of(n, &format!("{at}.name"), issues).filter(|n| { + let ok = dependency_name_ok(n); + if !ok { + issues.add( + &format!("{at}.name"), + "Invalid string: must match pattern /^[a-z0-9][a-z0-9._-]*$/", + ); + } + ok + }), + None => { + issues.add(&format!("{at}.name"), expected("string", &Value::Null)); + None + } + }; + let main = o + .get(transport) + .and_then(|v| nonempty_string_of(v, &format!("{at}.{transport}"), issues)); + let dir = o + .get("dir") + .and_then(|v| nonempty_string_of(v, &format!("{at}.dir"), issues)); + let version = match o.get("version") { + Some(v) => nonempty_string_of(v, &format!("{at}.version"), issues), + None if matches!(transport, "maven" | "nuget") => { + issues.add(&format!("{at}.version"), expected("string", &Value::Null)); + None + } + None => None, + }; + if issues.0.len() > before { + continue; + } + let (Some(name), Some(main)) = (name, main) else { + continue; + }; + let transport = match transport { + "path" => DependencyTransport::Path(main), + "npm" => DependencyTransport::Npm { npm: main, dir }, + "python" => DependencyTransport::Python { python: main, dir }, + "maven" => DependencyTransport::Maven { + maven: main, + version: version.unwrap_or_default(), + dir, + }, + _ => DependencyTransport::Nuget { + nuget: main, + version: version.unwrap_or_default(), + dir, + }, + }; + out.push(DependencySpec { name, transport }); + } + let mut names: Vec<&str> = out.iter().map(|d| d.name.as_str()).collect(); + names.sort_unstable(); + names.dedup(); + if names.len() != out.len() { + issues.add("dependencies", "dependencies: names must be unique"); + } + out +} + +fn parse_scope(v: &Value, issues: &mut Issues) -> Option { + let o = strict_object(v, "scope", &["include", "exclude"], issues)?; + Some(Scope { + include: o + .get("include") + .and_then(|v| string_array(v, "scope.include", true, issues)), + exclude: o + .get("exclude") + .and_then(|v| string_array(v, "scope.exclude", true, issues)), + }) +} + +fn parse_migrate(v: &Value, issues: &mut Issues) -> Option { + const KEYS: &[&str] = &[ + "outDir", + "databaseUrl", + "shadowDatabaseUrl", + "dialect", + "format", + "onAmbiguous", + "allow", + "d1", + "scope", + "conventions", + "checks", + "foreignKeyIndexes", + ]; + let o = strict_object(v, "migrate", KEYS, issues)?; + let s = |key: &str, issues: &mut Issues| { + o.get(key) + .and_then(|v| string_of(v, &format!("migrate.{key}"), issues)) + }; + let mut m = MigrateConfig { + out_dir: s("outDir", issues), + database_url: s("databaseUrl", issues), + shadow_database_url: s("shadowDatabaseUrl", issues), + ..MigrateConfig::default() + }; + m.dialect = o + .get("dialect") + .and_then(|v| enum_of(v, "migrate.dialect", MIGRATE_DIALECTS, None, issues)); + m.format = o + .get("format") + .and_then(|v| enum_of(v, "migrate.format", MIGRATE_FORMATS, None, issues)); + m.on_ambiguous = o + .get("onAmbiguous") + .and_then(|v| enum_of(v, "migrate.onAmbiguous", MIGRATE_ON_AMBIGUOUS, None, issues)); + if let Some(v) = o.get("allow") + && let Some(arr) = array_of(v, "migrate.allow", issues) + { + let mut tokens = Vec::new(); + for (i, t) in arr.iter().enumerate() { + if let Some(t) = enum_of( + t, + &format!("migrate.allow[{i}]"), + ALLOW_TOKENS, + None, + issues, + ) { + tokens.push(t); + } + } + m.allow = Some(tokens); + } + if let Some(v) = o.get("d1") + && let Some(d) = strict_object( + v, + "migrate.d1", + &["binding", "remote", "autoApply", "wranglerConfigPath"], + issues, + ) + { + m.d1 = Some(D1Block { + binding: d + .get("binding") + .and_then(|v| string_of(v, "migrate.d1.binding", issues)), + remote: d + .get("remote") + .and_then(|v| bool_of(v, "migrate.d1.remote", issues)), + auto_apply: d + .get("autoApply") + .and_then(|v| bool_of(v, "migrate.d1.autoApply", issues)), + wrangler_config_path: d + .get("wranglerConfigPath") + .and_then(|v| string_of(v, "migrate.d1.wranglerConfigPath", issues)), + }); + } + m.scope = o + .get("scope") + .and_then(|v| string_array(v, "migrate.scope", true, issues)); + m.conventions = o + .get("conventions") + .and_then(|v| nonempty_string_of(v, "migrate.conventions", issues)); + if let Some(v) = o.get("checks") + && let Some(c) = strict_object(v, "migrate.checks", &["skipRedundant"], issues) + { + m.checks_present = true; + m.checks_skip_redundant = c + .get("skipRedundant") + .and_then(|v| bool_of(v, "migrate.checks.skipRedundant", issues)); + } + m.foreign_key_indexes = o + .get("foreignKeyIndexes") + .and_then(|v| bool_of(v, "migrate.foreignKeyIndexes", issues)); + Some(m) +} + +fn parse_naming(v: &Value, naming: &NamingRegistry, issues: &mut Issues) -> Option { + let o = strict_object(v, "naming", &["columns", "tables", "collections"], issues)?; + let mut pick = |key: &str, + kind: NamingKind, + known: &dyn Fn(&NamingRegistry, &str) -> bool| + -> Option { + let at = format!("naming.{key}"); + let s = string_of(o.get(key)?, &at, issues)?; + if known(naming, &s) { + Some(s) + } else { + issues.add(&at, naming.unknown_strategy_message(kind, &s)); + None + } + }; + Some(NamingConfig { + columns: pick("columns", NamingKind::Columns, &|r, n| { + r.has_column_strategy(n) + }), + tables: pick("tables", NamingKind::Tables, &|r, n| r.has_table_rule(n)), + collections: pick("collections", NamingKind::Collections, &|r, n| { + r.has_pluralizer(n) + }), + }) +} + +fn parse_wire(v: &Value, issues: &mut Issues) -> Option { + let Some(o) = v.as_object() else { + issues.add("wire", "\"wire\" must be an object"); + return None; + }; + if let Some(k) = o + .keys() + .find(|k| !["decimals", "nullMembers", "durations"].contains(&k.as_str())) + { + issues.add( + "wire", + format!( + "\"wire\" has an unknown key \"{k}\" (expected \"decimals\", \"nullMembers\" and/or \"durations\")" + ), + ); + } + let mut pick = |key: &str, all: &[&str]| -> Option { + let list: Vec = all.iter().map(|v| format!("\"{v}\"")).collect(); + let message = format!("\"wire.{key}\" must be one of {}", list.join(", ")); + enum_of( + o.get(key)?, + &format!("wire.{key}"), + all, + Some(message), + issues, + ) + }; + Some(WireConfig { + decimals: pick("decimals", WireDecimals::ALL).and_then(|s| WireDecimals::parse(&s)), + null_members: pick("nullMembers", WireNullMembers::ALL) + .and_then(|s| WireNullMembers::parse(&s)), + durations: pick("durations", WireDurations::ALL).and_then(|s| WireDurations::parse(&s)), + }) +} + +fn parse_api(v: &Value, issues: &mut Issues) -> Option { + let Some(o) = v.as_object() else { + issues.add("api", "\"api\" must be an object"); + return None; + }; + if let Some(k) = o + .keys() + .find(|k| !["pagination", "unknownFields"].contains(&k.as_str())) + { + issues.add( + "api", + format!( + "\"api\" has an unknown key \"{k}\" (expected \"pagination\" or \"unknownFields\")" + ), + ); + } + let mut cfg = ApiConfig::default(); + if let Some(p) = o.get("pagination") { + match p.as_object() { + None => issues.add("api.pagination", "\"api.pagination\" must be an object"), + Some(po) => { + if let Some(k) = po + .keys() + .find(|k| !["defaultLimit", "maxLimit"].contains(&k.as_str())) + { + issues.add( + "api.pagination", + format!( + "\"api.pagination\" has an unknown key \"{k}\" (expected \"defaultLimit\" and \"maxLimit\")" + ), + ); + } + let d = page_size(po.get("defaultLimit"), "defaultLimit", issues); + let m = page_size(po.get("maxLimit"), "maxLimit", issues); + if let (Some(default_limit), Some(max_limit)) = (d, m) { + if default_limit > max_limit { + issues.add( + "api.pagination", + "\"api.pagination.defaultLimit\" must not exceed \"api.pagination.maxLimit\"", + ); + } else { + cfg.pagination = Some(ApiPagination { + default_limit, + max_limit, + }); + } + } + } + } + } + if let Some(u) = o.get("unknownFields") { + let message = "\"api.unknownFields\" must be \"reject\" or \"drop\"".to_string(); + cfg.unknown_fields = enum_of( + u, + "api.unknownFields", + UnknownFieldsMode::ALL, + Some(message), + issues, + ) + .and_then(|s| UnknownFieldsMode::parse(&s)); + } + Some(cfg) +} + +fn parse_enums(v: &Value, issues: &mut Issues) -> Option { + let o = strict_object(v, "enums", &["maxLength"], issues)?; + let mut out = EnumDefaults::default(); + if let Some(m) = o.get("maxLength") { + let at = "enums.maxLength"; + if !m.is_number() { + issues.add(at, expected("number", m)); + } else { + match whole_number(m) { + None => issues.add(at, "Invalid input: expected int, received number"), + Some(f) if f <= 0.0 => { + issues.add(at, "Too small: expected number to be >0"); + } + Some(f) => out.max_length = Some(f as u64), + } + } + } + Some(out) +} + +fn parse_csharp(v: &Value, issues: &mut Issues) -> Option { + let o = strict_object(v, "csharp", &["outDir", "namespace", "providers"], issues)?; + let mut out = CsharpConfig { + out_dir: o + .get("outDir") + .and_then(|v| nonempty_string_of(v, "csharp.outDir", issues)), + namespace: o + .get("namespace") + .and_then(|v| nonempty_string_of(v, "csharp.namespace", issues)), + providers: None, + }; + if let Some(p) = o.get("providers") + && let Some(arr) = array_of(p, "csharp.providers", issues) + { + let mut providers = Vec::new(); + for (i, item) in arr.iter().enumerate() { + let at = format!("csharp.providers[{i}]"); + let Some(po) = strict_object(item, &at, &["assembly", "type"], issues) else { + continue; + }; + let field = |key: &str, issues: &mut Issues| match po.get(key) { + Some(v) => nonempty_string_of(v, &format!("{at}.{key}"), issues), + None => { + issues.add(&format!("{at}.{key}"), expected("string", &Value::Null)); + None + } + }; + if let (Some(assembly), Some(type_name)) = + (field("assembly", issues), field("type", issues)) + { + providers.push(CsharpProvider { + assembly, + type_name, + }); + } + } + out.providers = Some(providers); + } + Some(out) +} + +fn unit_number(v: &Value, at: &str, default: f64, issues: &mut Issues) -> f64 { + match v { + Value::Number(n) => { + let f = n.as_f64().unwrap_or(f64::NAN); + if f < 0.0 { + issues.add(at, "Too small: expected number to be >=0"); + } else if f > 1.0 { + issues.add(at, "Too big: expected number to be <=1"); + } + f + } + other => { + issues.add(at, expected("number", other)); + default + } + } +} + +fn parse_thresholds(v: &Value, issues: &mut Issues) -> ConfidenceThresholds { + let mut t = ConfidenceThresholds::default(); + let Some(o) = v.as_object() else { + issues.add("confidence_thresholds", expected("object", v)); + return t; + }; + if let Some(p) = o.get("pending_promote") { + t.pending_promote = unit_number(p, "confidence_thresholds.pending_promote", 0.8, issues); + } + if let Some(d) = o.get("drift_warn") { + t.drift_warn = unit_number(d, "confidence_thresholds.drift_warn", 0.7, issues); + } + t +} + +// --------------------------------------------------------------------------- +// Public entry points + +fn describe_config_error(path: &str, issues: &Issues) -> String { + let mut lines: Vec = Vec::new(); + for (at, message) in &issues.0 { + let at = if at.is_empty() { "(top level)" } else { at }; + let line = format!(" {at}: {message}"); + if !lines.contains(&line) { + lines.push(line); + } + } + let touches_sources = issues + .0 + .iter() + .any(|(at, _)| at == "sources" || at.starts_with("sources[")); + let mut out = format!( + "{path} is not a valid MetaObjects config:\n{}", + lines.join("\n") + ); + if touches_sources { + out.push_str( + "\nEach `sources` entry is an object, for example { \"path\": \"model\" }, never a bare string.", + ); + } + out +} + +/// Validate a parsed config document. `display_path` names the file in messages. +/// +/// Forward-tolerant at the top level: an unknown key becomes one warning and is +/// ignored. Everything this version knows is validated strictly. +pub fn parse_config( + doc: &Value, + display_path: &str, + naming: &NamingRegistry, +) -> Result { + let mut issues = Issues::default(); + let mut warnings = Vec::new(); + let mut cfg = Config::default(); + match doc.as_object() { + None => issues.add("", expected("object", doc)), + Some(o) => { + for key in o.keys() { + if !CONFIG_TOP_LEVEL_KEYS.contains(&key.as_str()) { + warnings.push(format!( + "warning: {display_path}: unknown top-level key \"{key}\" ignored. A newer MetaObjects may have written it; upgrade this tool, or remove the key if it is a misspelling. Known keys: {}.", + CONFIG_TOP_LEVEL_KEYS.join(", ") + )); + } + } + match o.get("schema_version") { + Some(v) if whole_number(v) == Some(SCHEMA_VERSION as f64) => {} + _ => issues.add("schema_version", "Invalid input: expected 1"), + } + if let Some(v) = o.get("pending_in_git") + && let Some(b) = bool_of(v, "pending_in_git", &mut issues) + { + cfg.pending_in_git = b; + } + if let Some(v) = o.get("confidence_thresholds") { + cfg.confidence_thresholds = parse_thresholds(v, &mut issues); + } + if let Some(v) = o.get("sources") { + cfg.sources = parse_sources(v, &mut issues); + } + if let Some(v) = o.get("dependencies") { + cfg.dependencies = parse_dependencies(v, &mut issues); + } + if let Some(v) = o.get("libraries") + && let Some(l) = string_array(v, "libraries", false, &mut issues) + { + cfg.libraries = l; + } + if let Some(v) = o.get("scope") { + cfg.scope = parse_scope(v, &mut issues); + } + if let Some(v) = o.get("extract") { + match v.as_object() { + None => issues.add("extract", expected("object", v)), + Some(eo) => { + cfg.extract_metaignore = eo + .get("metaignore") + .and_then(|v| string_of(v, "extract.metaignore", &mut issues)); + } + } + } + if let Some(v) = o.get("migrate") { + cfg.migrate = parse_migrate(v, &mut issues); + } + if let Some(v) = o.get("verify") { + match v.as_object() { + None => issues.add("verify", "\"verify\" must be an object"), + Some(vo) => { + if let Some(k) = vo.keys().find(|k| k.as_str() != "handEdits") { + issues.add( + "verify", + format!( + "\"verify\" has an unknown key \"{k}\" (expected \"handEdits\")" + ), + ); + } + if let Some(h) = vo.get("handEdits") { + let list: Vec = HandEditsPolicy::ALL + .iter() + .map(|v| format!("\"{v}\"")) + .collect(); + let message = + format!("\"verify.handEdits\" must be one of {}", list.join(", ")); + cfg.hand_edits = enum_of( + h, + "verify.handEdits", + HandEditsPolicy::ALL, + Some(message), + &mut issues, + ) + .and_then(|s| HandEditsPolicy::parse(&s)); + } + } + } + } + if let Some(v) = o.get("requirements") + && let Some(ro) = strict_object(v, "requirements", &["inherit"], &mut issues) + { + cfg.requirements_inherit = ro + .get("inherit") + .and_then(|v| string_array(v, "requirements.inherit", true, &mut issues)); + } + if let Some(v) = o.get("naming") { + cfg.naming = parse_naming(v, naming, &mut issues); + } + if let Some(v) = o.get("wire") { + cfg.wire = parse_wire(v, &mut issues); + } + if let Some(v) = o.get("api") { + cfg.api = parse_api(v, &mut issues); + } + if let Some(v) = o.get("enums") { + cfg.enums = parse_enums(v, &mut issues); + } + if let Some(v) = o.get("csharp") { + cfg.csharp = parse_csharp(v, &mut issues); + } + } + } + if issues.0.is_empty() { + Ok(LoadedConfig { + config: cfg, + warnings, + }) + } else { + Err(MetaError::code( + ERR_BAD_ATTR_VALUE, + describe_config_error(display_path, &issues), + )) + } +} + +/// Parse config text (JSON). Malformed JSON is `ERR_MALFORMED_JSON`; an invalid +/// config is `ERR_BAD_ATTR_VALUE`. +pub fn parse_config_text( + text: &str, + display_path: &str, + naming: &NamingRegistry, +) -> Result { + let doc: Value = serde_json::from_str(text) + .map_err(|e| MetaError::code(ERR_MALFORMED_JSON, format!("{display_path}: {e}")))?; + parse_config(&doc, display_path, naming) +} + +/// Read `/config.json`, where `meta_root` is the `.metaobjects` directory. +pub fn load_config(meta_root: &Path, naming: &NamingRegistry) -> Result { + let path = meta_root.join(CONFIG_FILE); + let shown = path.display().to_string(); + let text = std::fs::read_to_string(&path) + .map_err(|e| MetaError::code(ERR_UNKNOWN, format!("{shown}: cannot read config: {e}")))?; + parse_config_text(&text, &shown, naming) +} diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index d99bc54e97..ed4a15e713 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -30,6 +30,14 @@ pub const ERR_PROVIDER_MISSING_DEPENDENCY: &str = "ERR_PROVIDER_MISSING_DEPENDEN pub const ERR_PROVIDER_DEPENDENCY_CYCLE: &str = "ERR_PROVIDER_DEPENDENCY_CYCLE"; pub const ERR_OVERLAY_NO_TARGET: &str = "ERR_OVERLAY_NO_TARGET"; +pub const ERR_MALFORMED_YAML: &str = "ERR_MALFORMED_YAML"; +pub const ERR_YAML_COERCION: &str = "ERR_YAML_COERCION"; +pub const ERR_SOURCE_UNRESOLVED: &str = "ERR_SOURCE_UNRESOLVED"; +pub const ERR_SOURCE_KIND_UNSUPPORTED: &str = "ERR_SOURCE_KIND_UNSUPPORTED"; +pub const ERR_COLLECTION_NOT_FOUND: &str = "ERR_COLLECTION_NOT_FOUND"; +pub const ERR_COLLECTION_NAME_COLLISION: &str = "ERR_COLLECTION_NAME_COLLISION"; +pub const ERR_UNKNOWN_LIBRARY: &str = "ERR_UNKNOWN_LIBRARY"; + /// The code reported for a failure that carries none (a programming error in a /// provider definition, say). pub const ERR_UNKNOWN: &str = "ERR_UNKNOWN"; @@ -58,6 +66,13 @@ pub const ALL_CODES: &[&str] = &[ ERR_PROVIDER_MISSING_DEPENDENCY, ERR_PROVIDER_DEPENDENCY_CYCLE, ERR_OVERLAY_NO_TARGET, + ERR_MALFORMED_YAML, + ERR_YAML_COERCION, + ERR_SOURCE_UNRESOLVED, + ERR_SOURCE_KIND_UNSUPPORTED, + ERR_COLLECTION_NOT_FOUND, + ERR_COLLECTION_NAME_COLLISION, + ERR_UNKNOWN_LIBRARY, ERR_UNKNOWN, ]; diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index f73418baf8..adf7712fc4 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -1,19 +1,27 @@ //! MetaObjects for Rust (preview). //! -//! The metamodel registry, the JSON loader and the canonical serializer. The +//! The metamodel registry, the JSON and YAML loader, project and source +//! resolution (the `.metaobjects/config.json` reader, the library sources), +//! naming, and the canonical serializer. The //! behaviour is defined by the shared conformance corpora that every port runs; //! ADR-0065 records how this port differs from the other five. +pub mod collection; +pub mod config; pub mod errors; pub mod json; +pub mod library; pub mod loader; pub mod manifest; +pub mod naming; pub mod node; pub mod parser; pub mod providers; pub mod registry; pub mod serializer; pub mod source; +pub mod sources; +pub mod yaml; pub use errors::MetaError; pub use loader::{LoadResult, Loader}; diff --git a/server/rust/metaobjects/src/library.rs b/server/rust/metaobjects/src/library.rs new file mode 100644 index 0000000000..2461d4425f --- /dev/null +++ b/server/rust/metaobjects/src/library.rs @@ -0,0 +1,257 @@ +//! The shipped libraries (FR-043): manifests, selection tokens and the YAML a +//! selection contributes, embedded into the crate at compile time by `build.rs`. +//! +//! This module only resolves *which texts* a selection names, in what order and +//! under which source ids; loading them is the loader's job. + +use std::collections::{BTreeMap, HashSet}; +use std::sync::OnceLock; + +use serde_json::Value; + +mod embedded { + include!(concat!(env!("OUT_DIR"), "/embedded_library.rs")); +} + +/// The prefix every library source id carries. +pub const LIBRARY_FILE_ID_PREFIX: &str = "library:"; + +/// One layer of a library, as its manifest declares it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LibraryLayer { + /// Refs (path under `library/` minus `.yaml`) this layer contributes, in order. + pub refs: Vec, + pub description: Option, +} + +/// A library's `library.json`, parsed. +#[derive(Debug, Clone, PartialEq)] +pub struct LibraryManifest { + pub name: String, + pub kind: Option, + pub stability: Option, + pub since: Option, + pub description: Option, + pub use_when: Option, + pub packages: Vec, + /// Layer token to layer, in manifest order. The CORE layer's token is `""`. + pub layers: Vec<(String, LibraryLayer)>, + /// `(name, anchor)` of each declared generator. + pub generators: Vec<(String, Option)>, + /// The `runtime` map as authored, untyped. + pub runtime: Value, +} + +impl LibraryManifest { + fn layer(&self, token: &str) -> Option<&LibraryLayer> { + self.layers.iter().find(|(t, _)| t == token).map(|(_, l)| l) + } +} + +fn opt_string(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_str).map(str::to_owned) +} + +fn parse_manifest(text: &str) -> LibraryManifest { + let v: Value = serde_json::from_str(text).expect("embedded library.json is valid JSON"); + let strings = |v: Option<&Value>| -> Vec { + v.and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() + }; + let layers = v + .get("layers") + .and_then(Value::as_object) + .map(|o| { + o.iter() + .map(|(token, l)| { + ( + token.clone(), + LibraryLayer { + refs: strings(l.get("refs")), + description: opt_string(l, "description"), + }, + ) + }) + .collect() + }) + .unwrap_or_default(); + let generators = v + .get("generators") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|g| Some((opt_string(g, "name")?, opt_string(g, "anchor")))) + .collect() + }) + .unwrap_or_default(); + LibraryManifest { + name: opt_string(&v, "name").unwrap_or_default(), + kind: opt_string(&v, "kind"), + stability: opt_string(&v, "stability"), + since: opt_string(&v, "since"), + description: opt_string(&v, "description"), + use_when: opt_string(&v, "useWhen"), + packages: strings(v.get("packages")), + layers, + generators, + runtime: v.get("runtime").cloned().unwrap_or(Value::Null), + } +} + +/// Every shipped library's parsed manifest, keyed by the library's directory name. +pub fn library_manifests() -> &'static BTreeMap { + static MANIFESTS: OnceLock> = OnceLock::new(); + MANIFESTS.get_or_init(|| { + embedded::EMBEDDED_LIBRARY_MANIFESTS + .iter() + .map(|(name, text)| ((*name).to_string(), parse_manifest(text))) + .collect() + }) +} + +/// Split a selection token into `(library, layer)`: `"iam"` is `("iam", "")`, +/// `"iam/db"` is `("iam", "db")`. Only the first separator is meaningful. +pub fn split_layer_token(token: &str) -> (&str, &str) { + token.split_once('/').unwrap_or((token, "")) +} + +/// The library names this build ships, sorted. +pub fn known_library_packages() -> Vec { + library_manifests().keys().cloned().collect() +} + +/// Every package name a shipped library owns, across every library and layer. +pub fn library_packages() -> HashSet { + library_manifests() + .values() + .flat_map(|m| m.packages.iter().cloned()) + .collect() +} + +/// Every selection token this build accepts, sorted: `["ai", "ai/db", "iam", "iam/db"]`. +pub fn known_library_tokens() -> Vec { + let mut out = Vec::new(); + for (name, m) in library_manifests() { + if m.layers.is_empty() { + out.push(name.clone()); + } + for (token, _) in &m.layers { + out.push(if token.is_empty() { + name.clone() + } else { + format!("{name}/{token}") + }); + } + } + out.sort(); + out +} + +/// The source id a library file loads under: `library:iam/model.yaml`. +pub fn library_file_id(r: &str) -> String { + format!("{LIBRARY_FILE_ID_PREFIX}{r}.yaml") +} + +/// True when a source id names a file a shipped library contributed. +pub fn is_library_file_id(id: &str) -> bool { + id.starts_with(LIBRARY_FILE_ID_PREFIX) +} + +/// The text of one library ref (`iam/model`), when this build embeds it. +pub fn library_ref_text(r: &str) -> Option<&'static str> { + embedded::EMBEDDED_LIBRARY + .iter() + .find(|(k, _)| *k == r) + .map(|(_, t)| *t) +} + +/// Every ref one library contributes, core layer first, de-duplicated. +pub fn library_refs(name: &str) -> Vec { + let Some(m) = library_manifests().get(name) else { + return Vec::new(); + }; + let mut seen = HashSet::new(); + let mut out = Vec::new(); + let core = m.layer("").into_iter().map(|l| ("", l)); + let rest = m + .layers + .iter() + .filter(|(t, _)| !t.is_empty()) + .map(|(t, l)| (t.as_str(), l)); + for (_, layer) in core.chain(rest) { + for r in &layer.refs { + if seen.insert(r.clone()) { + out.push(r.clone()); + } + } + } + out +} + +/// The tokens of `selection` this build does not ship (an unknown library or an +/// unknown layer of a known one), in selection order. +pub fn unknown_library_tokens(selection: &[String]) -> Vec { + let known = known_library_tokens(); + selection + .iter() + .filter(|t| !known.contains(t)) + .cloned() + .collect() +} + +/// The refs a selection names, in load order. A layer token implies its core; a +/// token whose library or layer is unknown contributes nothing, not even a core. +pub fn library_selection_refs(selection: &[String]) -> Vec { + let manifests = library_manifests(); + let wanted: Vec<(&LibraryManifest, &str)> = selection + .iter() + .map(|t| split_layer_token(t)) + .filter_map(|(lib, layer)| { + let m = manifests.get(lib)?; + m.layer(layer)?; + Some((m, layer)) + }) + .collect(); + let mut seen = HashSet::new(); + let mut refs = Vec::new(); + let mut add = |r: &String| { + if seen.insert(r.clone()) { + refs.push(r.clone()); + } + }; + // Core layers first, across every requested library, so a db layer named + // before its core still loads after it. + for (m, _) in &wanted { + if let Some(core) = m.layer("") { + core.refs.iter().for_each(&mut add); + } + } + for (m, layer) in &wanted { + if !layer.is_empty() + && let Some(l) = m.layer(layer) + { + l.refs.iter().for_each(&mut add); + } + } + refs +} + +/// `(source id, YAML text)` for the requested library selection, ordered as the +/// TypeScript port orders them: every core layer, then each requested layer. +/// An unrecognised token is skipped silently; the config reader refuses a token +/// a human typed (see [`unknown_library_tokens`]). +pub fn library_sources(selection: &[String]) -> Vec<(String, String)> { + library_selection_refs(selection) + .into_iter() + .filter_map(|r| { + let text = library_ref_text(&r)?; + Some((library_file_id(&r), text.to_owned())) + }) + .collect() +} diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index 596b718a8a..d6543fefad 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -18,12 +18,12 @@ use crate::errors::{ ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError, }; use crate::node::{Node, NodeId, PACKAGE_SEP, Tree}; -use crate::parser::{SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT, parse_document}; +use crate::parser::{SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT, parse_document_with}; use crate::registry::TypeRegistry; use crate::source::ErrorSource; +use crate::yaml::parse_yaml; -/// The extensions a directory load picks up. YAML is a later step of this port; -/// a `.yaml` file is reported rather than silently skipped. +/// The extensions a directory load picks up. const JSON_SUFFIX: &str = "json"; const YAML_SUFFIXES: &[&str] = &["yaml", "yml"]; /// A directory of drafts that a directory load never descends into. @@ -143,26 +143,31 @@ impl<'r> Loader<'r> { } else { ErrorSource::json(id, "$") }; - let lower = id.to_ascii_lowercase(); - if YAML_SUFFIXES - .iter() - .any(|s| lower.ends_with(&format!(".{s}"))) - { - errors.push(MetaError::at( - ERR_UNKNOWN, - format!("{id}: YAML metadata is not supported by the Rust port yet"), - envelope, - )); - continue; - } - let doc: Value = match serde_json::from_str(text) { - Ok(v) => v, - Err(e) => { - errors.push(MetaError::at(ERR_MALFORMED_JSON, e.to_string(), envelope)); - continue; + let is_yaml = id + .rsplit_once('.') + .is_some_and(|(_, ext)| YAML_SUFFIXES.iter().any(|s| ext.eq_ignore_ascii_case(s))); + let (doc, positions) = if is_yaml { + match parse_yaml(text, self.registry, id) { + Ok(d) => { + errors.extend(d.errors); + (d.canonical, Some(d.positions)) + } + Err(e) => { + errors.push(e); + continue; + } + } + } else { + match serde_json::from_str::(text) { + Ok(v) => (v, None), + Err(e) => { + errors.push(MetaError::at(ERR_MALFORMED_JSON, e.to_string(), envelope)); + continue; + } } }; - let parsed = parse_document(&doc, self.registry, &mut tree, id); + let parsed = + parse_document_with(&doc, self.registry, &mut tree, id, positions.as_ref()); // An unknown type or subtype drops only that node, so the rest of the // document is kept; any other parse error drops the document, as the // TypeScript and Python loaders do. diff --git a/server/rust/metaobjects/src/naming.rs b/server/rust/metaobjects/src/naming.rs new file mode 100644 index 0000000000..c962fc9341 --- /dev/null +++ b/server/rust/metaobjects/src/naming.rs @@ -0,0 +1,1145 @@ +//! Naming: how a metadata name becomes a physical name or a collection name. +//! +//! The Rust port of the TypeScript reference (`metadata/src/naming.ts`), checked by the +//! shared `fixtures/naming-conformance/` corpus. It holds +//! +//! * the string helpers ([`to_snake_case`], [`to_kebab_case`], [`to_pascal_column`], +//! [`strip_package`], [`package_of_resolution_key`]); +//! * the strategy registry ([`NamingRegistry`]): the built-in column rules, table rules +//! and pluralizers, and the ones an application registers (ADR-0058 Amendment 1); +//! * the project setting ([`PhysicalNaming`], `naming` in `.metaobjects/config.json`); +//! * both pluralizers: [`pluralize`] for every API and code surface, and the frozen +//! [`pluralize_table_name_legacy`] for default physical names; +//! * the collection names and REST segments ([`collection_name_of`], +//! [`collection_segment_of`]); +//! * the node-level resolvers over a loaded [`Tree`] ([`resolve_table_name`], +//! [`resolve_column_name`], the flattened-column names, [`resolve_index_name`], +//! [`resolve_table_schema`], [`build_name_map`]); +//! * the collection-name collision refusal ([`assert_no_collection_name_collisions`]). +//! +//! Unlike the TypeScript reference, the registry and the project setting are passed in +//! (a [`NamingCtx`]) rather than read from a process-wide registry and the loaded root: +//! the Rust tree carries no config, and a registry per context cannot leak between +//! tests. +//! +//! Reads follow ADR-0039: resolving accessors by default. The only own-only reads are +//! `@collectionName` (an inherited name would give every subtype one collection), the +//! TPH level walk, and `@dbColumnType`-style physical attrs, none of which this module +//! needs beyond the first two. + +use std::collections::HashMap; +use std::fmt; +use std::sync::Arc; + +use indexmap::IndexMap; + +use crate::errors::{ERR_COLLECTION_NAME_COLLISION, ERR_UNKNOWN, MetaError}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; + +// ---- string helpers ---------------------------------------------------------- + +/// Strip the package prefix from a qualified name (`pkg::Name` becomes `Name`). +pub fn strip_package(name: &str) -> &str { + match name.rfind(PACKAGE_SEP) { + Some(i) => &name[i + PACKAGE_SEP.len()..], + None => name, + } +} + +/// The package half of a resolution key (`a::b::C` becomes `a::b`; a bare `C` becomes `""`). +pub fn package_of_resolution_key(fqn: &str) -> &str { + match fqn.rfind(PACKAGE_SEP) { + Some(i) => &fqn[..i], + None => "", + } +} + +/// snake_case with an acronym-aware split (`URLHost` becomes `url_host`, `taxID` becomes +/// `tax_id`). The two regex passes of the reference, written as local rules: an upper +/// case letter after an upper case letter and before a lower case one starts a word, and +/// so does an upper case letter after a lower case letter or digit. ASCII classes only. +pub fn to_snake_case(s: &str) -> String { + let chars: Vec = s.chars().collect(); + // Pass 1: ([A-Z]+)([A-Z][a-z]) -> $1_$2 + let mut pass1 = String::with_capacity(s.len() + 4); + for (k, &c) in chars.iter().enumerate() { + if k > 0 + && c.is_ascii_uppercase() + && chars[k - 1].is_ascii_uppercase() + && chars.get(k + 1).is_some_and(|n| n.is_ascii_lowercase()) + { + pass1.push('_'); + } + pass1.push(c); + } + // Pass 2: ([a-z0-9])([A-Z]) -> $1_$2 + let chars: Vec = pass1.chars().collect(); + let mut pass2 = String::with_capacity(pass1.len() + 4); + for (k, &c) in chars.iter().enumerate() { + if k > 0 + && c.is_ascii_uppercase() + && (chars[k - 1].is_ascii_lowercase() || chars[k - 1].is_ascii_digit()) + { + pass2.push('_'); + } + pass2.push(c); + } + pass2.to_lowercase() +} + +/// kebab-case: [`to_snake_case`] with `-` for `_`. +pub fn to_kebab_case(s: &str) -> String { + to_snake_case(s).replace('_', "-") +} + +/// The `pascal` column rule: the first letter upper-cased, nothing else changed +/// (`createdAt` becomes `CreatedAt`, `requestURL` becomes `RequestURL`). +/// +/// One UTF-16 unit in and one out, as the other ports do: a letter whose upper case is +/// several characters (`ß`) or that is outside the basic plane stays as written. +pub fn to_pascal_column(s: &str) -> String { + let mut chars = s.chars(); + let Some(first) = chars.next() else { + return String::new(); + }; + let mut upper = first.to_uppercase(); + let replaced = match (upper.next(), upper.next()) { + (Some(u), None) if first.len_utf16() == 1 && u.len_utf16() == 1 => u, + _ => first, + }; + let mut out = String::with_capacity(s.len()); + out.push(replaced); + out.push_str(chars.as_str()); + out +} + +// ---- pluralizers ------------------------------------------------------------- + +/// True when `s` already reads as a plural noun (`Stats`, `Settings`, `Series`): it ends +/// in `s` and the letter before that `s` is not one of s/u/i/a (`Status`, `Address`, +/// `Bonus`, `Alias`, `Gas` stay on the ordinary suffix path). A heuristic, not a +/// dictionary: `Lens` reads as already plural too. +fn is_already_plural(s: &str) -> bool { + let mut rev = s.chars().rev(); + let (Some(last), Some(prev)) = (rev.next(), rev.next()) else { + return false; + }; + last.eq_ignore_ascii_case(&'s') && !matches!(prev.to_ascii_lowercase(), 's' | 'u' | 'i' | 'a') +} + +/// The FROZEN suffix-only pluralizer: the default PHYSICAL name derivation, with no +/// already-plural detection. Changing it would make `meta migrate` propose a rename for +/// every already-plural entity name of an existing database. Never use it for an API or +/// code-surface name; those go through [`pluralize`]. +pub fn pluralize_table_name_legacy(s: &str) -> String { + let lower = s.to_ascii_lowercase(); + if lower.ends_with(['s', 'x', 'z']) || lower.ends_with("ch") || lower.ends_with("sh") { + return format!("{s}es"); + } + let mut rev = s.chars().rev(); + if let (Some(y), Some(before)) = (rev.next(), rev.next()) + && y.eq_ignore_ascii_case(&'y') + && !matches!(before.to_ascii_lowercase(), 'a' | 'e' | 'i' | 'o' | 'u') + { + let mut out = s.to_string(); + out.pop(); + out.push_str("ies"); + return out; + } + format!("{s}s") +} + +/// API and code-surface pluralization: REST segments, generated hook, query, finder and +/// list names, collection variable names. Already-plural detection first, then the +/// suffix rule. +pub fn pluralize(s: &str) -> String { + if is_already_plural(s) { + s.to_string() + } else { + pluralize_table_name_legacy(s) + } +} + +// ---- strategies and the registry --------------------------------------------- + +/// A naming strategy: a bare metadata name in, a physical (or collection) name out. +pub type NamingFunction = Arc String + Send + Sync>; + +/// The column rules every port builds in, in the order the corpus lists them. +pub const BUILTIN_COLUMN_NAMING_STRATEGIES: [&str; 4] = + ["snake_case", "literal", "kebab-case", "pascal"]; +/// The table rules every port builds in. +pub const BUILTIN_TABLE_NAMING_RULES: [&str; 2] = ["snake_case", "literal"]; +/// The pluralizers every port builds in. +pub const BUILTIN_PLURALIZER_NAMES: [&str; 2] = ["standard", "none"]; +/// The pluralizer a project gets when `naming.collections` is absent. +pub const DEFAULT_PLURALIZER: &str = "standard"; +/// The default column strategy in every port. +pub const DEFAULT_COLUMN_NAMING_STRATEGY: &str = "snake_case"; +/// The default table rule in every port. +pub const DEFAULT_TABLE_NAMING_RULE: &str = "snake_case"; + +/// The port name every unknown-strategy message carries. +const NAMING_PORT: &str = "Rust"; + +/// The kinds of naming strategy a project selects in `naming` (ADR-0058). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NamingKind { + Columns, + Tables, + Collections, +} + +impl NamingKind { + /// The key in the `naming` block. + pub fn key(self) -> &'static str { + match self { + NamingKind::Columns => "columns", + NamingKind::Tables => "tables", + NamingKind::Collections => "collections", + } + } + + fn label(self) -> &'static str { + match self { + NamingKind::Columns => "column-naming", + NamingKind::Tables => "table-naming", + NamingKind::Collections => "collection-naming (pluralizer)", + } + } + + fn builtins(self) -> &'static [&'static str] { + match self { + NamingKind::Columns => &BUILTIN_COLUMN_NAMING_STRATEGIES, + NamingKind::Tables => &BUILTIN_TABLE_NAMING_RULES, + NamingKind::Collections => &BUILTIN_PLURALIZER_NAMES, + } + } +} + +/// The named strategies a project may select: the built-ins and the application's. +#[derive(Clone)] +pub struct NamingRegistry { + columns: IndexMap, + tables: IndexMap, + collections: IndexMap, +} + +impl fmt::Debug for NamingRegistry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NamingRegistry") + .field("columns", &self.columns.keys().collect::>()) + .field("tables", &self.tables.keys().collect::>()) + .field("collections", &self.collections.keys().collect::>()) + .finish() + } +} + +impl Default for NamingRegistry { + fn default() -> Self { + Self::builtin() + } +} + +fn func(f: impl Fn(&str) -> String + Send + Sync + 'static) -> NamingFunction { + Arc::new(f) +} + +impl NamingRegistry { + /// A registry holding only the built-ins. + pub fn builtin() -> Self { + let mut columns: IndexMap = IndexMap::new(); + columns.insert("snake_case".into(), func(to_snake_case)); + columns.insert("literal".into(), func(str::to_string)); + columns.insert("kebab-case".into(), func(to_kebab_case)); + columns.insert("pascal".into(), func(to_pascal_column)); + let mut tables: IndexMap = IndexMap::new(); + tables.insert("snake_case".into(), func(to_snake_case)); + tables.insert("literal".into(), func(str::to_string)); + let mut collections: IndexMap = IndexMap::new(); + collections.insert("standard".into(), func(pluralize)); + collections.insert("none".into(), func(str::to_string)); + Self { + columns, + tables, + collections, + } + } + + fn map(&self, kind: NamingKind) -> &IndexMap { + match kind { + NamingKind::Columns => &self.columns, + NamingKind::Tables => &self.tables, + NamingKind::Collections => &self.collections, + } + } + + /// Register under `name`. A built-in cannot be replaced; registering a name of your + /// own again replaces it (an application registers once at startup). + pub fn register( + &mut self, + kind: NamingKind, + name: &str, + apply: impl Fn(&str) -> String + Send + Sync + 'static, + ) -> Result<(), MetaError> { + if name.is_empty() { + return Err(MetaError::code( + ERR_UNKNOWN, + format!("a {} strategy needs a non-empty name", kind.label()), + )); + } + if kind.builtins().contains(&name) { + return Err(MetaError::code( + ERR_UNKNOWN, + format!( + "\"{name}\" is a built in {} strategy and cannot be replaced; register yours under another name", + kind.label() + ), + )); + } + let map = match kind { + NamingKind::Columns => &mut self.columns, + NamingKind::Tables => &mut self.tables, + NamingKind::Collections => &mut self.collections, + }; + map.insert(name.to_string(), func(apply)); + Ok(()) + } + + /// Register a named column strategy. + pub fn register_column_strategy( + &mut self, + name: &str, + apply: impl Fn(&str) -> String + Send + Sync + 'static, + ) -> Result<(), MetaError> { + self.register(NamingKind::Columns, name, apply) + } + + /// Register a named table rule. + pub fn register_table_rule( + &mut self, + name: &str, + apply: impl Fn(&str) -> String + Send + Sync + 'static, + ) -> Result<(), MetaError> { + self.register(NamingKind::Tables, name, apply) + } + + /// Register a named pluralizer (an object name in, its collection name out). + pub fn register_pluralizer( + &mut self, + name: &str, + apply: impl Fn(&str) -> String + Send + Sync + 'static, + ) -> Result<(), MetaError> { + self.register(NamingKind::Collections, name, apply) + } + + pub fn has_column_strategy(&self, name: &str) -> bool { + self.columns.contains_key(name) + } + + pub fn has_table_rule(&self, name: &str) -> bool { + self.tables.contains_key(name) + } + + pub fn has_pluralizer(&self, name: &str) -> bool { + self.collections.contains_key(name) + } + + /// Whether a strategy of `kind` is registered under `name`. + pub fn has(&self, kind: NamingKind, name: &str) -> bool { + self.map(kind).contains_key(name) + } + + /// Every registered column strategy name: built-ins in corpus order, then the application's. + pub fn column_strategy_names(&self) -> Vec<&str> { + self.columns.keys().map(String::as_str).collect() + } + + /// Every registered table rule name. + pub fn table_rule_names(&self) -> Vec<&str> { + self.tables.keys().map(String::as_str).collect() + } + + /// Every registered pluralizer name. + pub fn pluralizer_names(&self) -> Vec<&str> { + self.collections.keys().map(String::as_str).collect() + } + + /// What every port says when a config names a strategy nothing registered answers. + /// Same words as the reference, with this port's name. + pub fn unknown_strategy_message(&self, kind: NamingKind, name: &str) -> String { + let builtins = kind.builtins(); + let registered: Vec<&str> = self + .map(kind) + .keys() + .map(String::as_str) + .filter(|n| !builtins.contains(n)) + .collect(); + format!( + "\"naming.{}\" names \"{name}\", which no {} strategy registered in the \ + {NAMING_PORT} port answers (built in: {}; registered by the application: {}). \ + Register it before .metaobjects/config.json is read, or correct the name.", + kind.key(), + kind.label(), + builtins.join(", "), + if registered.is_empty() { + "none".to_string() + } else { + registered.join(", ") + }, + ) + } + + fn get(&self, kind: NamingKind, name: &str) -> Result<&NamingFunction, MetaError> { + self.map(kind) + .get(name) + .ok_or_else(|| MetaError::code(ERR_UNKNOWN, self.unknown_strategy_message(kind, name))) + } + + /// The column strategy registered as `name`; an error naming it when nothing answers. + pub fn column_strategy(&self, name: &str) -> Result<&NamingFunction, MetaError> { + self.get(NamingKind::Columns, name) + } + + /// The table rule registered as `name`. + pub fn table_rule(&self, name: &str) -> Result<&NamingFunction, MetaError> { + self.get(NamingKind::Tables, name) + } + + /// The pluralizer registered as `name`. + pub fn pluralizer(&self, name: &str) -> Result<&NamingFunction, MetaError> { + self.get(NamingKind::Collections, name) + } + + /// `name` cased by the table rule registered as `rule`. + pub fn apply_table_naming_rule(&self, name: &str, rule: &str) -> Result { + Ok(self.table_rule(rule)?(name)) + } + + /// `name` through the column strategy registered as `strategy`: the one door every + /// column resolution goes through. An unregistered name is an error, never a silent + /// fallback to the default. + pub fn apply_column_naming_strategy( + &self, + name: &str, + strategy: &str, + ) -> Result { + Ok(self.column_strategy(strategy)?(name)) + } +} + +// ---- the project setting ----------------------------------------------------- + +/// The project's physical-naming rules: `naming` in `.metaobjects/config.json` (ADR-0058). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PhysicalNaming { + /// The column strategy name. + pub columns: String, + /// The table rule name. + pub tables: String, + /// The pluralizer name for an object with no `@collectionName`; `None` is + /// [`DEFAULT_PLURALIZER`] for collection names, and "not configured" for REST segments. + pub collections: Option, +} + +impl Default for PhysicalNaming { + fn default() -> Self { + Self { + columns: DEFAULT_COLUMN_NAMING_STRATEGY.to_string(), + tables: DEFAULT_TABLE_NAMING_RULE.to_string(), + collections: None, + } + } +} + +/// A registry and the project setting, passed to every node-level resolver. +#[derive(Debug, Clone, Copy)] +pub struct NamingCtx<'a> { + pub registry: &'a NamingRegistry, + pub naming: &'a PhysicalNaming, +} + +impl<'a> NamingCtx<'a> { + pub fn new(registry: &'a NamingRegistry, naming: &'a PhysicalNaming) -> Self { + Self { registry, naming } + } +} + +// ---- collection names and segments --------------------------------------------- + +/// snake_case a collection name with an acronym-aware split: a trailing plural `s` or +/// `es` after a capital is a suffix of the acronym, not a word (`FAQs` becomes `faqs`, +/// `TaxIDs` becomes `tax_ids`, `PDFBoxes` becomes `pdf_boxes`). +pub fn snake_collection_name(s: &str) -> String { + if let Some(t) = s.strip_suffix('s') { + if t.ends_with(|c: char| c.is_ascii_uppercase()) { + return format!("{}s", to_snake_case(t)); + } + if let Some(u) = t.strip_suffix('e') + && u.ends_with(|c: char| c.is_ascii_uppercase()) + { + return format!("{}es", to_snake_case(u)); + } + } + to_snake_case(s) +} + +/// The REST collection segment for an object named `name` +/// (`fixtures/naming-conformance/collection-segments.json`): a declared +/// `@collectionName` wins, snake-cased; else a configured pluralizer's output over the +/// name, snake-cased the same way; else the historical rule, snake_case then [`pluralize`]. +pub fn collection_segment_of( + registry: &NamingRegistry, + name: &str, + declared: Option<&str>, + configured_pluralizer: Option<&str>, +) -> Result { + if let Some(d) = declared { + return Ok(snake_collection_name(d)); + } + if let Some(p) = configured_pluralizer { + return Ok(snake_collection_name(®istry.pluralizer(p)?(name))); + } + Ok(pluralize(&to_snake_case(name))) +} + +const OBJECT_ATTR_COLLECTION_NAME: &str = "collectionName"; + +/// The collection name an object declares itself (`@collectionName`), if any. +pub fn declared_collection_name(tree: &Tree, obj: NodeId) -> Option { + // ADR-0039: own-only on purpose. A name inherited from an abstract base would give + // every subtype one collection. + match tree.own_attr(obj, OBJECT_ATTR_COLLECTION_NAME) { + Some(a) => a + .value + .as_str() + .filter(|s| !s.is_empty()) + .map(str::to_string), + None => None, + } +} + +/// An object's collection name in its own casing: its `@collectionName`, else the +/// project's pluralizer over its name. +pub fn collection_name_of( + tree: &Tree, + obj: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + if let Some(d) = declared_collection_name(tree, obj) { + return Ok(d); + } + let p = ctx + .naming + .collections + .as_deref() + .unwrap_or(DEFAULT_PLURALIZER); + Ok(ctx.registry.pluralizer(p)?(&tree.node(obj).name)) +} + +/// The REST collection segment an object is served under. +pub fn collection_segment( + tree: &Tree, + obj: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + collection_segment_of( + ctx.registry, + &tree.node(obj).name, + declared_collection_name(tree, obj).as_deref(), + ctx.naming.collections.as_deref(), + ) +} + +// ---- node-level resolvers -------------------------------------------------------- + +const TYPE_FIELD: &str = "field"; +const TYPE_OBJECT: &str = "object"; +const TYPE_SOURCE: &str = "source"; +const SUBTYPE_RDB: &str = "rdb"; +const SUBTYPE_VALUE: &str = "value"; +const ATTR_COLUMN: &str = "column"; +const ATTR_FLATTENED_PREFIX: &str = "flattenedColumnPrefix"; +const ATTR_SCHEMA: &str = "schema"; +const ATTR_KIND: &str = "kind"; +const ATTR_ROLE: &str = "role"; +const ATTR_TABLE: &str = "table"; +const ATTR_DISCRIMINATOR: &str = "discriminator"; +const ATTR_DISCRIMINATOR_VALUE: &str = "discriminatorValue"; +const DEFAULT_SOURCE_KIND: &str = "table"; +const DEFAULT_SOURCE_ROLE: &str = "primary"; +const ROLE_PRIMARY: &str = "primary"; +const READ_ONLY_KINDS: [&str; 4] = ["view", "materializedView", "storedProc", "tableFunction"]; + +/// The kind-matching physical-name alias of a `source.rdb` `@kind`. +fn physical_name_attr_for_kind(kind: &str) -> Option<&'static str> { + match kind { + "table" => Some("table"), + "view" => Some("view"), + "materializedView" => Some("materializedView"), + "storedProc" => Some("proc"), + "tableFunction" => Some("function"), + _ => None, + } +} + +fn str_attr<'t>(tree: &'t Tree, id: NodeId, name: &str) -> Option<&'t str> { + tree.attr(id, name) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) +} + +/// True for a `source.rdb` node. +pub fn is_rdb_source(tree: &Tree, id: NodeId) -> bool { + let n = tree.node(id); + n.type_name == TYPE_SOURCE && n.sub_type == SUBTYPE_RDB +} + +/// The effective `@kind` of a source (default `table`). +pub fn source_effective_kind(tree: &Tree, source: NodeId) -> &str { + str_attr(tree, source, ATTR_KIND).unwrap_or(DEFAULT_SOURCE_KIND) +} + +/// The effective `@role` of a source (default `primary`). +pub fn source_role(tree: &Tree, source: NodeId) -> &str { + str_attr(tree, source, ATTR_ROLE).unwrap_or(DEFAULT_SOURCE_ROLE) +} + +/// True when the source's effective kind is read-only. +pub fn source_is_read_only(tree: &Tree, source: NodeId) -> bool { + READ_ONLY_KINDS.contains(&source_effective_kind(tree, source)) +} + +/// Resolved physical SQL name of a source, by the four-step rule (FR-016, ADR-0018): +/// the kind-matching alias, then `@table` for a non-table kind, then the source's own +/// structural name cased by the table rule, then the owning entity's name cased by the +/// table rule through the frozen legacy pluralizer. +pub fn source_physical_name( + tree: &Tree, + source: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + let kind = source_effective_kind(tree, source); + let canonical = physical_name_attr_for_kind(kind); + if let Some(attr) = canonical + && let Some(v) = str_attr(tree, source, attr) + { + return Ok(v.to_string()); + } + if canonical != Some(ATTR_TABLE) + && let Some(v) = str_attr(tree, source, ATTR_TABLE) + { + return Ok(v.to_string()); + } + let node = tree.node(source); + if !node.name.is_empty() { + return ctx + .registry + .apply_table_naming_rule(&node.name, &ctx.naming.tables); + } + if let Some(owner) = node.parent { + let owner_name = &tree.node(owner).name; + if !owner_name.is_empty() { + let cased = ctx + .registry + .apply_table_naming_rule(owner_name, &ctx.naming.tables)?; + return Ok(pluralize_table_name_legacy(&cased)); + } + } + Ok(String::new()) +} + +/// The resolved address of a source, rendered as the primary-source divergence refusal +/// compares it: `"schema"."name" (kind)`. +pub fn source_address_key( + tree: &Tree, + source: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + // RAW on purpose: an absent @schema is not folded into a dialect default. + let qualifier = str_attr(tree, source, ATTR_SCHEMA) + .map(|s| format!("\"{s}\".")) + .unwrap_or_default(); + Ok(format!( + "{qualifier}\"{}\" ({})", + source_physical_name(tree, source, ctx)?, + source_effective_kind(tree, source) + )) +} + +/// The `@role: primary` source of an entity, and the one place the divergence refusal +/// lives. Effective children, so a TPH subtype resolves to its base's source. `None` +/// when the object declares no primary source. Several primaries on distinct physical +/// addresses are refused. +pub fn primary_rdb_source( + tree: &Tree, + entity: NodeId, + ctx: &NamingCtx<'_>, +) -> Result, MetaError> { + let primaries: Vec = tree + .children(entity) + .iter() + .copied() + .filter(|&c| is_rdb_source(tree, c) && source_role(tree, c) == ROLE_PRIMARY) + .collect(); + let Some(&first) = primaries.first() else { + return Ok(None); + }; + let mut distinct: Vec = Vec::new(); + for &p in &primaries { + let key = source_address_key(tree, p, ctx)?; + if !distinct.contains(&key) { + distinct.push(key); + } + } + if distinct.len() > 1 { + distinct.sort(); + return Err(MetaError::code( + ERR_UNKNOWN, + format!( + "{}: role=primary sources disagree on the object's physical address — {}. \ + Every consumer binds ONE address. Give them a matching @kind, @schema \ + and physical name, or drop the extra role=primary declaration.", + tree.node(entity).name, + distinct.join(" vs ") + ), + )); + } + Ok(Some(first)) +} + +/// The table name of an entity: its primary source's physical name, else the entity name +/// cased by the table rule through the frozen legacy pluralizer. +pub fn resolve_table_name( + tree: &Tree, + entity: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + if let Some(source) = primary_rdb_source(tree, entity, ctx)? { + return source_physical_name(tree, source, ctx); + } + let cased = ctx + .registry + .apply_table_naming_rule(&tree.node(entity).name, &ctx.naming.tables)?; + Ok(pluralize_table_name_legacy(&cased)) +} + +/// The schema declared on an entity's primary source, if any. +pub fn resolve_table_schema( + tree: &Tree, + entity: NodeId, + ctx: &NamingCtx<'_>, +) -> Result, MetaError> { + Ok(primary_rdb_source(tree, entity, ctx)? + .and_then(|s| str_attr(tree, s, ATTR_SCHEMA).map(str::to_string))) +} + +/// A field's column: its `@column`, else its name through the column strategy +/// (`strategy` defaults to the project's). +pub fn resolve_column_name_with( + tree: &Tree, + field: NodeId, + ctx: &NamingCtx<'_>, + strategy: &str, +) -> Result { + // ADR-0039: resolving. A concrete field may inherit @column via extends. + if let Some(col) = str_attr(tree, field, ATTR_COLUMN) { + return Ok(col.to_string()); + } + ctx.registry + .apply_column_naming_strategy(&tree.node(field).name, strategy) +} + +/// [`resolve_column_name_with`] under the project's column strategy. +pub fn resolve_column_name( + tree: &Tree, + field: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + resolve_column_name_with(tree, field, ctx, &ctx.naming.columns) +} + +/// The text before each member's column when `field` (a flattened `field.object`) +/// expands its value object into the owning table: its `@flattenedColumnPrefix` +/// verbatim (`""` allowed), else its own resolved column and `_`. +pub fn resolve_flattened_column_prefix( + tree: &Tree, + field: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + // ADR-0039: resolving. The prefix and @column may be inherited through extends. + if let Some(prefix) = tree + .attr(field, ATTR_FLATTENED_PREFIX) + .and_then(|v| v.as_str()) + { + return Ok(prefix.to_string()); + } + Ok(resolve_column_name(tree, field, ctx)? + "_") +} + +/// The column a member of a flattened value object gets in the owning table. +pub fn resolve_flattened_column_name( + tree: &Tree, + field: NodeId, + member: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + Ok(resolve_flattened_column_prefix(tree, field, ctx)? + + &resolve_column_name(tree, member, ctx)?) +} + +/// An index's database name: the metamodel `name` with any package qualifier stripped. +/// An empty name is refused, as nothing could be emitted. +pub fn resolve_index_name( + type_name: &str, + sub_type: &str, + name: &str, +) -> Result { + let short = strip_package(name); + if short.is_empty() { + return Err(MetaError::code( + ERR_UNKNOWN, + format!( + "{type_name}.{sub_type} declares an empty name; an index's database name IS \ + its metamodel name, so there is nothing to emit. Give it a name." + ), + )); + } + Ok(short.to_string()) +} + +/// Per-entity `{name <-> column}` maps, built once per entity. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EntityNameMap { + pub js_to_db: HashMap, + pub db_to_js: HashMap, +} + +/// Build the name map over the entity's effective fields (a TPH subtype's map covers the +/// inherited base fields and its own). +pub fn build_name_map( + tree: &Tree, + entity: NodeId, + ctx: &NamingCtx<'_>, +) -> Result { + let mut map = EntityNameMap::default(); + for &child in tree.children(entity).iter() { + if tree.node(child).type_name != TYPE_FIELD { + continue; + } + let col = resolve_column_name(tree, child, ctx)?; + let name = tree.node(child).name.clone(); + map.db_to_js.insert(col.clone(), name.clone()); + map.js_to_db.insert(name, col); + } + Ok(map) +} + +// ---- collection-name collision refusal ------------------------------------------- + +/// Where the generated entity modules live: one directory, or one per metadata package. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OutputLayout { + #[default] + Flat, + Package, +} + +/// Which name sets a run emits, and the layout of its entity modules. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CollectionNameScopes { + pub layout: OutputLayout, + /// Whether the pluralized module names are checked. + pub modules: bool, + /// Whether the REST segments are checked. + pub routes: bool, +} + +impl Default for CollectionNameScopes { + fn default() -> Self { + Self { + layout: OutputLayout::Flat, + modules: true, + routes: true, + } + } +} + +fn is_abstract(tree: &Tree, obj: NodeId) -> bool { + tree.node(obj).is_abstract +} + +/// True when the object emits instance artifacts: not abstract and declaring or +/// inheriting a `source.rdb` (#248: participation derives from a declared source). +pub fn emits_instance_artifacts(tree: &Tree, obj: NodeId) -> bool { + !is_abstract(tree, obj) && tree.children(obj).iter().any(|&c| is_rdb_source(tree, c)) +} + +/// True when the object is a TPH subtype: it declares `@discriminatorValue` and an +/// ancestor declares `@discriminator`. +pub fn is_tph_subtype(tree: &Tree, obj: NodeId) -> bool { + // ADR-0039: own-only on purpose. A subtype declares its OWN @discriminatorValue and + // the base level is found by walking each ancestor's OWN @discriminator. + let has_value = tree + .own_attr(obj, ATTR_DISCRIMINATOR_VALUE) + .and_then(|a| a.value.as_str()) + .is_some_and(|s| !s.is_empty()); + if !has_value { + return false; + } + let mut seen = vec![obj]; + let mut cur = tree.node(obj).super_node; + while let Some(n) = cur { + if seen.contains(&n) { + break; + } + seen.push(n); + // ADR-0039: own-only, see above. + if tree + .own_attr(n, ATTR_DISCRIMINATOR) + .and_then(|a| a.value.as_str()) + .is_some_and(|s| !s.is_empty()) + { + return true; + } + cur = tree.node(n).super_node; + } + false +} + +fn capitalize_first(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + +fn collision(message: String) -> MetaError { + MetaError::code(ERR_COLLECTION_NAME_COLLISION, message) +} + +/// Refuse two objects that claim one generated name in ONE scope. There is no run-wide +/// rule: a name collides only where the artifact carrying it lives. The pluralized names +/// are exports of the entity modules (one scope under the flat layout, one per package +/// under the package layout); the REST segment is unique across every routed object. +/// Counted over the objects that emit those names ([`emits_instance_artifacts`]), so an +/// abstract or sourceless object is in no scope. Deterministic: the first object to +/// claim a name owns it, and the error names the second. The error code is +/// `ERR_COLLECTION_NAME_COLLISION`. +pub fn assert_no_collection_name_collisions( + tree: &Tree, + objects: &[NodeId], + scopes: &CollectionNameScopes, + ctx: &NamingCtx<'_>, +) -> Result<(), MetaError> { + if scopes.modules { + assert_no_module_name_collisions(tree, objects, scopes.layout, ctx)?; + } + if scopes.routes { + assert_no_route_segment_collisions(tree, objects, ctx)?; + } + Ok(()) +} + +fn assert_no_module_name_collisions( + tree: &Tree, + objects: &[NodeId], + layout: OutputLayout, + ctx: &NamingCtx<'_>, +) -> Result<(), MetaError> { + let mut owner: HashMap<(String, String), NodeId> = HashMap::new(); + for &obj in objects { + if tree.node(obj).sub_type == SUBTYPE_VALUE || !emits_instance_artifacts(tree, obj) { + continue; + } + let plural = capitalize_first(&collection_name_of(tree, obj, ctx)?); + let scope = match layout { + OutputLayout::Package => tree.effective_package(obj), + OutputLayout::Flat => String::new(), + }; + let key = (scope.clone(), plural.clone()); + match owner.get(&key) { + Some(&existing) if tree.resolution_key(existing) != tree.resolution_key(obj) => { + return Err(collision(format!( + "\"{}\" and \"{}\" both pluralize to the collection name \"{plural}\" in one \ + module scope ({}; generated hook/query/finder/list names, the collection \ + variable) — rename one entity, give one a distinct @collectionName, or \ + place the modules by package (outputLayout: \"package\"). Default PHYSICAL \ + table names are unaffected by this rule.", + tree.resolution_key(existing), + tree.resolution_key(obj), + if scope.is_empty() { + "the entity modules' directory".to_string() + } else { + format!("package {scope}") + } + ))); + } + Some(_) => {} + None => { + owner.insert(key, obj); + } + } + } + Ok(()) +} + +fn assert_no_route_segment_collisions( + tree: &Tree, + objects: &[NodeId], + ctx: &NamingCtx<'_>, +) -> Result<(), MetaError> { + let mut owner: HashMap = HashMap::new(); + for &obj in objects { + if tree.node(obj).sub_type == SUBTYPE_VALUE + || !emits_instance_artifacts(tree, obj) + || is_tph_subtype(tree, obj) + { + continue; + } + let segment = collection_segment(tree, obj, ctx)?; + match owner.get(&segment) { + Some(&existing) if tree.resolution_key(existing) != tree.resolution_key(obj) => { + return Err(collision(format!( + "\"{}\" and \"{}\" both resolve to the REST collection segment \"{segment}\" \ + — rename one entity, or give one a distinct @collectionName, so its route \ + segment is distinct.", + tree.resolution_key(existing), + tree.resolution_key(obj), + ))); + } + Some(_) => {} + None => { + owner.insert(segment, obj); + } + } + } + Ok(()) +} + +/// Every top-level `object.*` of a loaded tree, in declaration order: the set a run +/// hands to [`assert_no_collection_name_collisions`]. +pub fn top_level_objects(tree: &Tree, root: NodeId) -> Vec { + tree.children(root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_OBJECT) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn snake_case_handles_acronyms() { + for (input, want) in [ + ("URLHost", "url_host"), + ("TaxID", "tax_id"), + ("FAQs", "fa_qs"), + ("HTTPRequest", "http_request"), + ("requestURL", "request_url"), + ("createdAt", "created_at"), + ("address_line1", "address_line1"), + ("line1Item", "line1_item"), + ("ABcDEf", "a_bc_d_ef"), + ("ID", "id"), + ("", ""), + ("already_snake", "already_snake"), + ] { + assert_eq!(to_snake_case(input), want, "{input}"); + } + } + + #[test] + fn kebab_and_pascal() { + assert_eq!(to_kebab_case("unitPriceCents"), "unit-price-cents"); + assert_eq!(to_kebab_case("URLHost"), "url-host"); + assert_eq!(to_pascal_column("createdAt"), "CreatedAt"); + assert_eq!(to_pascal_column("requestURL"), "RequestURL"); + assert_eq!(to_pascal_column("address_line1"), "Address_line1"); + assert_eq!(to_pascal_column("npi"), "Npi"); + assert_eq!(to_pascal_column(""), ""); + // One UTF-16 unit in, one out: `ß` and a non-BMP letter stay as written. + assert_eq!(to_pascal_column("ßeta"), "ßeta"); + assert_eq!(to_pascal_column("\u{10428}x"), "\u{10428}x"); + assert_eq!(to_pascal_column("éa"), "Éa"); + } + + #[test] + fn package_helpers() { + assert_eq!(strip_package("a::b::C"), "C"); + assert_eq!(strip_package("C"), "C"); + assert_eq!(strip_package(""), ""); + assert_eq!(package_of_resolution_key("a::b::C"), "a::b"); + assert_eq!(package_of_resolution_key("C"), ""); + } + + #[test] + fn snake_collection_names_keep_plural_acronym_suffix() { + for (input, want) in [ + ("FAQs", "faqs"), + ("TaxIDs", "tax_ids"), + ("PDFBoxes", "pdf_boxes"), + ("queues", "queues"), + ("ConsignmentHistory", "consignment_history"), + ("Stats", "stats"), + ("Bs", "bs"), + ] { + assert_eq!(snake_collection_name(input), want, "{input}"); + } + } + + #[test] + fn pluralizers() { + assert_eq!(pluralize("Stats"), "Stats"); + assert_eq!(pluralize("Status"), "Statuses"); + assert_eq!(pluralize("Lens"), "Lens"); + assert_eq!(pluralize("s"), "ses"); + assert_eq!(pluralize("Category"), "Categories"); + assert_eq!(pluralize("Day"), "Days"); + assert_eq!(pluralize("BOX"), "BOXes"); + assert_eq!(pluralize("Match"), "Matches"); + assert_eq!(pluralize_table_name_legacy("Stats"), "Statses"); + assert_eq!(pluralize_table_name_legacy("y"), "ys"); + assert_eq!(pluralize_table_name_legacy("KEY"), "KEYs"); + assert_eq!(pluralize_table_name_legacy("COMPANY"), "COMPANies"); + } + + #[test] + fn registry_registration_rules() { + let mut r = NamingRegistry::builtin(); + assert!(r.has_column_strategy("pascal")); + assert!(!r.has_table_rule("pascal")); + assert!(r.has_pluralizer("none")); + assert!(r.register_column_strategy("pascal", |n| n.into()).is_err()); + assert!(r.register_column_strategy("", |n| n.into()).is_err()); + r.register_column_strategy("shout", |n| n.to_ascii_uppercase()) + .unwrap(); + // Registering again replaces. + r.register_column_strategy("shout", |n| format!("{n}!")) + .unwrap(); + assert_eq!(r.apply_column_naming_strategy("a", "shout").unwrap(), "a!"); + assert_eq!(r.column_strategy_names().last(), Some(&"shout")); + let err = r.apply_column_naming_strategy("a", "nope").unwrap_err(); + assert!(err.message.contains("\"naming.columns\" names \"nope\"")); + assert!(err.message.contains("registered by the application: shout")); + assert!(err.message.contains("Rust port")); + assert!( + NamingRegistry::default() + .unknown_strategy_message(NamingKind::Tables, "x") + .contains("built in: snake_case, literal; registered by the application: none") + ); + } + + #[test] + fn index_names() { + assert_eq!( + resolve_index_name("index", "lookup", "acme::by_name").unwrap(), + "by_name" + ); + assert!(resolve_index_name("index", "lookup", "").is_err()); + assert!(resolve_index_name("index", "lookup", "pkg::").is_err()); + } +} diff --git a/server/rust/metaobjects/src/parser.rs b/server/rust/metaobjects/src/parser.rs index ad19e8246c..352f1552a0 100644 --- a/server/rust/metaobjects/src/parser.rs +++ b/server/rust/metaobjects/src/parser.rs @@ -16,7 +16,8 @@ use crate::errors::{ use crate::json::{js_display, safe_whole_i64}; use crate::node::{Attr, Node, NodeId, PACKAGE_SEP, Tree}; use crate::registry::{SUBTYPE_BASE, TypeRegistry}; -use crate::source::{ErrorSource, JsonPath}; +use crate::source::{ErrorSource, JsonPath, YamlPosition}; +use crate::yaml::Positions; pub const TYPE_METADATA: &str = "metadata"; pub const SUBTYPE_ROOT: &str = "root"; @@ -48,7 +49,7 @@ pub const ATTR_SUBTYPE_PROPERTIES: &str = "properties"; /// (a bare string becomes a one-element list). pub const ATTR_SUBTYPE_STRINGARRAY: &str = "stringarray"; -const RESERVED_STRUCTURAL_KEYS: &[&str] = &[ +pub(crate) const RESERVED_STRUCTURAL_KEYS: &[&str] = &[ KEY_NAME, KEY_PACKAGE, KEY_EXTENDS, @@ -70,12 +71,25 @@ struct Ctx<'a> { registry: &'a TypeRegistry, file: &'a str, errors: Vec, + /// Set for a YAML document: where each node's key sits, by canonical path. + positions: Option<&'a Positions>, + /// The position of the node being built, stamped on the errors it raises. + cur_pos: Option, } impl Ctx<'_> { + /// Note that the walk entered the node at `path`. + fn enter(&mut self, path: &JsonPath) { + if let Some(p) = self.positions { + self.cur_pos = p.get(path.as_str()).copied(); + } + } + fn here(&self, path: &JsonPath) -> ErrorSource { if self.file.is_empty() { ErrorSource::Code + } else if self.positions.is_some() { + ErrorSource::yaml(self.file, path.as_str(), self.cur_pos) } else { ErrorSource::json(self.file, path.as_str()) } @@ -89,11 +103,25 @@ impl Ctx<'_> { /// Parse one document into `tree`. `file` names it in error envelopes. pub fn parse_document(doc: &Value, registry: &TypeRegistry, tree: &mut Tree, file: &str) -> Parsed { + parse_document_with(doc, registry, tree, file, None) +} + +/// [`parse_document`] for a document that came from YAML: errors carry the +/// `yaml` format and the position of the node they were raised in. +pub fn parse_document_with( + doc: &Value, + registry: &TypeRegistry, + tree: &mut Tree, + file: &str, + positions: Option<&Positions>, +) -> Parsed { let mut ctx = Ctx { tree, registry, file, errors: Vec::new(), + positions, + cur_pos: None, }; let root_path = JsonPath::root(); let Some(map) = doc.as_object() else { @@ -127,6 +155,7 @@ pub fn parse_document(doc: &Value, registry: &TypeRegistry, tree: &mut Tree, fil } let (wrapper, body) = wrappers[0]; let path = root_path.key(wrapper); + ctx.enter(&path); let root = build(&mut ctx, wrapper, body, &path, &Scope::root()); Parsed { root, @@ -411,6 +440,7 @@ fn build( let (cw, cbody) = entry.iter().next().expect("one entry"); let cpath = entry_path.key(cw); let (ctype, csub) = split_wrapper(cw); + ctx.enter(&cpath); if ctype == TYPE_ATTR { parse_attr_child(ctx, id, cw, csub, cbody, &cpath); } else { diff --git a/server/rust/metaobjects/src/source.rs b/server/rust/metaobjects/src/source.rs index 116648d1cd..3429650017 100644 --- a/server/rust/metaobjects/src/source.rs +++ b/server/rust/metaobjects/src/source.rs @@ -11,6 +11,13 @@ pub enum ErrorSource { files: Vec, json_path: String, }, + /// A location in one YAML document: the same path, plus the line and column of + /// the node's key when the parse knows them. + Yaml { + files: Vec, + json_path: String, + position: Option, + }, /// A reference that did not resolve: the referring node and the reference. Resolved { files: Vec, @@ -20,7 +27,22 @@ pub enum ErrorSource { }, } +/// A 1-indexed line and column in a YAML document. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct YamlPosition { + pub line: u32, + pub col: u32, +} + impl ErrorSource { + pub fn yaml(file: &str, json_path: impl Into, position: Option) -> Self { + ErrorSource::Yaml { + files: vec![file.to_string()], + json_path: json_path.into(), + position, + } + } + pub fn json(file: &str, json_path: impl Into) -> Self { ErrorSource::Json { files: vec![file.to_string()], @@ -33,6 +55,7 @@ impl ErrorSource { match self { ErrorSource::Code => "code", ErrorSource::Json { .. } => "json", + ErrorSource::Yaml { .. } => "yaml", ErrorSource::Resolved { .. } => "resolved", } } @@ -40,22 +63,35 @@ impl ErrorSource { pub fn files(&self) -> &[String] { match self { ErrorSource::Code => &[], - ErrorSource::Json { files, .. } | ErrorSource::Resolved { files, .. } => files, + ErrorSource::Json { files, .. } + | ErrorSource::Yaml { files, .. } + | ErrorSource::Resolved { files, .. } => files, } } pub fn json_path(&self) -> Option<&str> { match self { ErrorSource::Code => None, - ErrorSource::Json { json_path, .. } | ErrorSource::Resolved { json_path, .. } => { - Some(json_path) - } + ErrorSource::Json { json_path, .. } + | ErrorSource::Yaml { json_path, .. } + | ErrorSource::Resolved { json_path, .. } => Some(json_path), + } + } + + /// The YAML position, when this envelope has one. + pub fn yaml_position(&self) -> Option { + match self { + ErrorSource::Yaml { position, .. } => *position, + _ => None, } } /// Rewrite every file path with `f` (the conformance runner makes them relative). pub fn map_files(&mut self, f: impl Fn(&str) -> String) { - if let ErrorSource::Json { files, .. } | ErrorSource::Resolved { files, .. } = self { + if let ErrorSource::Json { files, .. } + | ErrorSource::Yaml { files, .. } + | ErrorSource::Resolved { files, .. } = self + { for file in files.iter_mut() { *file = f(file); } diff --git a/server/rust/metaobjects/src/sources.rs b/server/rust/metaobjects/src/sources.rs new file mode 100644 index 0000000000..4651b7e671 --- /dev/null +++ b/server/rust/metaobjects/src/sources.rs @@ -0,0 +1,242 @@ +//! Source resolution: a declared `sources` set in `.metaobjects/config.json` +//! becomes a canonically ordered, de-duplicated list of metadata files. +//! +//! Ported from the TypeScript SDK (`sources.ts`, `metadata-files.ts`). The whole +//! result is a pure function of the source SET, never of declaration order: +//! specs are processed in the order of their canonical JSON text. Within one +//! directory the order is files first (sorted by name), then subdirectories, +//! depth first, which is the order generated output has always followed. + +use std::collections::HashSet; +use std::path::{Component, Path, PathBuf}; + +use crate::errors::{ERR_SOURCE_KIND_UNSUPPORTED, ERR_SOURCE_UNRESOLVED, ERR_UNKNOWN, MetaError}; + +/// The default value of `sources`: the directory scanned when a config declares none. +/// A default, never a requirement. +pub const DEFAULT_METADATA_DIR: &str = "metaobjects"; +/// Where a project keeps its own tool state, `config.json` included. +pub const DEFAULT_METAOBJECTS_DIR: &str = ".metaobjects"; +/// `config.json`'s basename. +pub const CONFIG_FILE: &str = "config.json"; +/// A directory of drafts, skipped at every level of a source walk. +pub const PENDING_DIR: &str = "_pending"; +/// The metadata file extensions, matched case-insensitively, with the dot. +pub const METADATA_EXTENSIONS: &[&str] = &[".json", ".yaml", ".yml"]; + +/// One declared source. `Resource` and `Package` are declared so the config shape +/// is stable, but resolve nowhere yet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SourceSpec { + Path(String), + Resource(String), + Package(String), +} + +impl SourceSpec { + /// The spec as the canonical JSON text TypeScript orders by: `{"path":"a"}`. + pub fn canonical_json(&self) -> String { + let (key, value) = match self { + SourceSpec::Path(v) => ("path", v), + SourceSpec::Resource(v) => ("resource", v), + SourceSpec::Package(v) => ("package", v), + }; + format!( + "{{\"{key}\":{}}}", + serde_json::to_string(value).unwrap_or_default() + ) + } +} + +/// The default `sources`: exactly one `path` source, the default directory. +pub fn default_sources() -> Vec { + vec![SourceSpec::Path(DEFAULT_METADATA_DIR.to_string())] +} + +/// One resolved metadata file and the spec that contributed it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedSource { + /// Absolute path of one metadata file. + pub file: PathBuf, + /// The spec that contributed it (provenance for diagnostics). + pub spec: SourceSpec, +} + +/// True when `name` ends in a metadata extension, matched case-insensitively. +/// A dotfile such as `.json` has no extension, as in Node's `extname`. +pub fn is_metadata_file(name: &str) -> bool { + match name.rfind('.') { + Some(i) if i > 0 => { + let ext = name[i..].to_ascii_lowercase(); + METADATA_EXTENSIONS.contains(&ext.as_str()) + } + _ => false, + } +} + +/// `path.resolve`: make `p` absolute against `base` and collapse `.` and `..` +/// lexically. Symlinks are NOT resolved, so a reported path keeps a link's own name. +pub fn resolve_path(base: &Path, p: &Path) -> PathBuf { + let joined = if p.is_absolute() { + p.to_path_buf() + } else { + base.join(p) + }; + let mut out = PathBuf::new(); + for c in joined.components() { + match c { + Component::ParentDir => { + if !out.pop() { + out.push(".."); + } + } + Component::CurDir => {} + other => out.push(other.as_os_str()), + } + } + out +} + +/// `path.resolve(p)` against the process working directory. +pub fn absolutize(p: &Path) -> PathBuf { + let cwd = std::env::current_dir().unwrap_or_default(); + resolve_path(&cwd, p) +} + +/// UTF-16 code-unit order, the order JavaScript's default string sort uses. +fn utf16_cmp(a: &str, b: &str) -> std::cmp::Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} + +/// The declared set in canonical order, kind-validated across the WHOLE list +/// first: `resource` and `package` raise `ERR_SOURCE_KIND_UNSUPPORTED` before any +/// path is touched, in either declaration order. Returns the `path` values paired +/// with their spec. +pub fn ordered_path_specs(specs: &[SourceSpec]) -> Result, MetaError> { + let mut out = Vec::with_capacity(specs.len()); + for spec in specs { + match spec { + SourceSpec::Path(p) => out.push((p.clone(), spec.clone())), + SourceSpec::Resource(_) | SourceSpec::Package(_) => { + let kind = if matches!(spec, SourceSpec::Resource(_)) { + "resource" + } else { + "package" + }; + return Err(MetaError::code( + ERR_SOURCE_KIND_UNSUPPORTED, + format!( + "source kind \"{kind}\" is not supported by this toolchain yet; use a \"path\" source" + ), + )); + } + } + } + out.sort_by(|a, b| utf16_cmp(&a.1.canonical_json(), &b.1.canonical_json())); + Ok(out) +} + +/// Where a declared `path` source lives: absolute as written, otherwise relative +/// to the DECLARING config's directory, never to the working directory. +pub fn resolve_spec_path(config_dir: &Path, path: &str) -> PathBuf { + resolve_path(config_dir, Path::new(path)) +} + +fn io_error(message: String) -> MetaError { + MetaError::code(ERR_UNKNOWN, message) +} + +/// Recursively list metadata files under `dir`, excluding `_pending/` at any level. +/// Entries at a level are sorted by name; files come first, then subdirectories +/// depth first. Symlinked directories are followed; an entry that cannot be +/// stat'ed is skipped; a symlink that revisits a directory on the CURRENT walk +/// branch is an error (a diamond, reachable by two routes, is not). +pub fn list_metadata_files(dir: &Path) -> Result, MetaError> { + let mut branch = Vec::new(); + let mut out = Vec::new(); + walk(dir, &mut branch, &mut out)?; + Ok(out) +} + +fn walk(dir: &Path, branch: &mut Vec, out: &mut Vec) -> Result<(), MetaError> { + let real = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); + if branch.contains(&real) { + return Err(io_error(format!( + "symlink loop detected while expanding metadata directory: {} revisits {}", + dir.display(), + real.display() + ))); + } + branch.push(real); + let read = std::fs::read_dir(dir).map_err(|e| { + io_error(format!( + "cannot read metadata directory {}: {e}", + dir.display() + )) + })?; + let mut names: Vec = read + .filter_map(Result::ok) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort_by(|a, b| utf16_cmp(a, b)); + let mut subdirs = Vec::new(); + for name in names { + if name == PENDING_DIR { + continue; + } + let full = dir.join(&name); + // `metadata` follows symlinks, so a linked directory is walked. + let Ok(meta) = std::fs::metadata(&full) else { + continue; + }; + if meta.is_dir() { + subdirs.push(full); + } else if meta.is_file() && is_metadata_file(&name) { + out.push(full); + } + } + for sub in subdirs { + walk(&sub, branch, out)?; + } + branch.pop(); + Ok(()) +} + +/// Resolve a declared source SET to canonically ordered metadata files. A missing +/// `path` raises `ERR_SOURCE_UNRESOLVED`; a directory is walked, a file is taken +/// as is; the first contributor of a shared file wins. +pub fn resolve_sources( + config_dir: &Path, + specs: &[SourceSpec], +) -> Result, MetaError> { + let ordered = ordered_path_specs(specs)?; + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for (path, spec) in ordered { + let target = resolve_spec_path(config_dir, &path); + let Ok(meta) = std::fs::metadata(&target) else { + return Err(MetaError::code( + ERR_SOURCE_UNRESOLVED, + format!( + "source path \"{path}\" does not exist (resolved to {}, relative to {})", + target.display(), + config_dir.display() + ), + )); + }; + let found = if meta.is_dir() { + list_metadata_files(&target)? + } else { + vec![target] + }; + for file in found { + if seen.insert(file.clone()) { + out.push(ResolvedSource { + file, + spec: spec.clone(), + }); + } + } + } + Ok(out) +} diff --git a/server/rust/metaobjects/src/yaml.rs b/server/rust/metaobjects/src/yaml.rs new file mode 100644 index 0000000000..3b83195676 --- /dev/null +++ b/server/rust/metaobjects/src/yaml.rs @@ -0,0 +1,407 @@ +//! Authoring YAML to the canonical document the JSON parser reads. +//! +//! A front-end, as in every port (the TypeScript `core/parser-yaml.ts` and +//! `core/yaml-desugar.ts` are the reference): parse the text with a YAML 1.2 core +//! schema parser, apply the authoring sugar of ADR-0006, and hand the resulting +//! canonical `{ ".": { ... } }` document to the same parser that +//! reads JSON. The sugar: +//! +//! 1. a bare `type` key takes the type's default subtype; +//! 2. a scalar body becomes `{ name: }`; +//! 3. a trailing `[]` on the key is `isArray: true`; +//! 4. every body key that is not a reserved structural key is an inline attribute +//! and gets its `@` back (a key already written with `@` is left as it is). +//! +//! It also runs the YAML type-coercion guard: an unquoted `TRUE`, `0x1F` or `~` +//! given to an attribute declared `string` is reported as `ERR_YAML_COERCION`, +//! telling the author to quote it. +//! +//! The parse keeps the line and column of every node's key, so an error raised +//! while building a node can say where in the file it came from. Positions live +//! in a side table keyed by the node's canonical JSON path, so the canonical +//! document stays a plain `serde_json::Value`. + +use std::borrow::Cow; +use std::collections::HashMap; + +use saphyr::{LoadableYamlNode, MarkedYaml, Scalar, YamlData}; +use serde_json::{Map, Number, Value}; + +use crate::errors::{ERR_MALFORMED_YAML, ERR_YAML_COERCION, MetaError}; +use crate::json::js_display; +use crate::parser::{ + ATTR_PREFIX, ATTR_SUBTYPE_INT, ATTR_SUBTYPE_LONG, ATTR_SUBTYPE_STRING, + ATTR_SUBTYPE_STRINGARRAY, FUSED_KEY_SEP, KEY_CHILDREN, KEY_IS_ARRAY, KEY_NAME, + RESERVED_STRUCTURAL_KEYS, +}; +use crate::registry::TypeRegistry; +use crate::source::{ErrorSource, JsonPath, YamlPosition}; + +const ARRAY_SUFFIX: &str = "[]"; +const ATTR_SUBTYPE_CLASS: &str = "class"; +const ATTR_SUBTYPE_DOUBLE: &str = "double"; +const ATTR_SUBTYPE_BOOLEAN: &str = "boolean"; + +/// The position of each node's wrapper key, by the node's canonical JSON path. +pub type Positions = HashMap; + +/// One YAML document, desugared. +#[derive(Debug)] +pub struct Desugared { + /// The canonical document, ready for [`crate::parser::parse_document_with`]. + pub canonical: Value, + pub positions: Positions, + /// Problems the desugar collected without stopping: coercions, malformed + /// nodes. They precede the parser's own errors, as in every port. + pub errors: Vec, +} + +fn yaml_envelope(file: &str) -> ErrorSource { + ErrorSource::yaml(file, "$", None) +} + +/// Parse and desugar one YAML document. An `Err` is a document that could not be +/// read at all: a syntax error, more than one document, or nothing usable. +pub fn parse_yaml(text: &str, registry: &TypeRegistry, file: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let malformed = |message: String| { + MetaError::at( + ERR_MALFORMED_YAML, + format!("Invalid YAML: {message}"), + yaml_envelope(file), + ) + }; + let docs = MarkedYaml::load_from_str(text).map_err(|e| malformed(e.to_string()))?; + if docs.len() > 1 { + return Err(malformed( + "Source contains multiple documents. Please use YAML.parseAllDocuments()".into(), + )); + } + let mut d = Desugar { + registry, + file, + errors: Vec::new(), + positions: Positions::new(), + }; + let node = d.node(docs.first(), &JsonPath::root(), ""); + let Some(canonical) = node else { + // Nothing usable: the first problem is the error, as the other ports throw it. + let first = d.errors.into_iter().next().unwrap_or_else(|| { + MetaError::at(ERR_MALFORMED_YAML, "empty document", yaml_envelope(file)) + }); + return Err(first); + }; + Ok(Desugared { + canonical, + positions: d.positions, + errors: d.errors, + }) +} + +struct Desugar<'a> { + registry: &'a TypeRegistry, + file: &'a str, + errors: Vec, + positions: Positions, +} + +/// The text a mapping key reads as: a scalar's JavaScript `String(...)` form. +fn key_text(key: &MarkedYaml<'_>) -> Option { + match &unwrap_tag(key).data { + YamlData::Value(s) => Some(js_display(&scalar_value(s))), + YamlData::Representation(text, ..) => Some(text.to_string()), + _ => None, + } +} + +fn unwrap_tag<'a, 'i>(node: &'a MarkedYaml<'i>) -> &'a MarkedYaml<'i> { + let mut n = node; + while let YamlData::Tagged(_, inner) = &n.data { + n = inner; + } + n +} + +fn scalar_value(s: &Scalar<'_>) -> Value { + match s { + Scalar::Null => Value::Null, + Scalar::Boolean(b) => Value::Bool(*b), + Scalar::Integer(i) => Value::Number((*i).into()), + // JavaScript has one number type, and JSON has no NaN or Infinity. + Scalar::FloatingPoint(f) => Number::from_f64(f.0).map_or(Value::Null, Value::Number), + Scalar::String(s) => Value::String(s.to_string()), + } +} + +fn position(node: &MarkedYaml<'_>) -> YamlPosition { + let start = node.span.start; + YamlPosition { + line: u32::try_from(start.line()).unwrap_or(u32::MAX), + // The parser counts columns from 0; the envelope from 1. + col: u32::try_from(start.col() + 1).unwrap_or(u32::MAX), + } +} + +/// A YAML node as plain data. A mapping key that is not a scalar is dropped, as +/// the other ports drop it: the authoring grammar has only string keys. +fn to_value(node: &MarkedYaml<'_>) -> Value { + match &unwrap_tag(node).data { + YamlData::Value(s) => scalar_value(s), + YamlData::Representation(text, ..) => Value::String(text.to_string()), + YamlData::Sequence(items) => Value::Array(items.iter().map(to_value).collect()), + YamlData::Mapping(map) => { + let mut out = Map::new(); + for (k, v) in map { + if let Some(key) = key_text(k) { + out.insert(key, to_value(v)); + } + } + Value::Object(out) + } + _ => Value::Null, + } +} + +/// A mapping's entries with a usable key, in document order. +fn entries<'a, 'i>( + node: &'a MarkedYaml<'i>, +) -> Option, &'a MarkedYaml<'i>)>> { + match &unwrap_tag(node).data { + YamlData::Mapping(map) => Some( + map.iter() + .filter_map(|(k, v)| key_text(k).map(|text| (text, k, v))) + .collect(), + ), + _ => None, + } +} + +impl Desugar<'_> { + fn error(&mut self, code: &'static str, message: String) { + self.errors + .push(MetaError::at(code, message, yaml_envelope(self.file))); + } + + fn malformed(&mut self, message: String) { + self.error(ERR_MALFORMED_YAML, message); + } + + /// One node: a single-key mapping `{ "type.subType": body }`. `parent_path` is + /// the canonical JSON path the wrapper sits under; `at` names the node in + /// messages. + fn node( + &mut self, + input: Option<&MarkedYaml<'_>>, + parent_path: &JsonPath, + at: &str, + ) -> Option { + let Some(map) = input.and_then(entries) else { + self.malformed(format!("Node at {at} must be a mapping with one type key")); + return None; + }; + if map.len() != 1 { + let found = if map.is_empty() { + "none".to_string() + } else { + map.iter() + .map(|(k, ..)| k.as_str()) + .collect::>() + .join(", ") + }; + self.malformed(format!( + "Node at {at} must have exactly one type key (found: {found})" + )); + return None; + } + let (raw_key, key_node, raw_body) = &map[0]; + + // Sugar 3: a trailing `[]` on the key is `isArray`. + let (key, is_array) = match raw_key.strip_suffix(ARRAY_SUFFIX) { + Some(stripped) => (stripped, true), + None => (raw_key.as_str(), false), + }; + // Sugar 1: a bare `type` key takes the type's default subtype. + let canonical_key = self.resolve_key(key, at); + let path = parent_path.key(&canonical_key); + self.positions + .insert(path.as_str().to_string(), position(key_node)); + + let mut body = self.body(raw_body, &canonical_key, &path, at); + if is_array { + body.insert(KEY_IS_ARRAY.to_string(), Value::Bool(true)); + } + let mut wrapper = Map::new(); + wrapper.insert(canonical_key, Value::Object(body)); + Some(Value::Object(wrapper)) + } + + fn resolve_key(&mut self, key: &str, at: &str) -> String { + if key.contains(FUSED_KEY_SEP) { + return key.to_string(); + } + match self.registry.default_sub_type_of(key) { + Some(sub) => format!("{key}{FUSED_KEY_SEP}{sub}"), + None => { + self.malformed(format!( + "Cannot resolve subType for bare type key '{key}' at {at} — type '{key}' has no default subType; write the full 'type.subType'" + )); + key.to_string() + } + } + } + + /// Sugars 2 and 4 plus the coercion guard: a node body as a canonical mapping. + fn body( + &mut self, + raw: &MarkedYaml<'_>, + canonical_key: &str, + path: &JsonPath, + at: &str, + ) -> Map { + let raw = unwrap_tag(raw); + match &raw.data { + YamlData::Value(Scalar::Null) => return Map::new(), + YamlData::Value(s) if !matches!(s, Scalar::Null) => { + // A scalar body is the node's name. + let mut out = Map::new(); + out.insert(KEY_NAME.to_string(), scalar_value(s)); + return out; + } + YamlData::Representation(text, ..) => { + let mut out = Map::new(); + out.insert(KEY_NAME.to_string(), Value::String(text.to_string())); + return out; + } + YamlData::Sequence(_) => { + self.malformed(format!( + "Node body at {at} must be a scalar or mapping, not a list" + )); + return Map::new(); + } + _ => {} + } + let Some(map) = entries(raw) else { + return Map::new(); + }; + let schema = canonical_key + .split_once(FUSED_KEY_SEP) + .and_then(|(t, s)| self.registry.find(t, s)); + let mut out = Map::new(); + let mut children: Option = None; + for (key, _, value) in &map { + let (out_key, attr_name): (Cow<'_, str>, Option<&str>) = + if RESERVED_STRUCTURAL_KEYS.contains(&key.as_str()) { + (Cow::Borrowed(key), None) + } else if let Some(name) = key.strip_prefix(ATTR_PREFIX) { + (Cow::Borrowed(key), Some(name)) + } else { + (Cow::Owned(format!("{ATTR_PREFIX}{key}")), Some(key)) + }; + if key == KEY_CHILDREN { + // Children are desugared in place, below, so their positions are known. + children = Some(out.len()); + out.insert(KEY_CHILDREN.to_string(), Value::Null); + continue; + } + let value = to_value(value); + if let Some(name) = attr_name + && !name.is_empty() + && !RESERVED_STRUCTURAL_KEYS.contains(&name) + && let Some(def) = schema + && let Some(spec) = def.attr(name) + { + let value_type = if spec.is_array == Some(true) { + Some(ATTR_SUBTYPE_STRINGARRAY) + } else { + spec.value_type.as_deref() + }; + if let Some(value_type) = value_type { + self.check_coercion(name, &value, value_type, at); + } + } + out.insert(out_key.into_owned(), value); + } + if children.is_some() + && let Some((_, _, seq)) = map.iter().find(|(k, ..)| k == KEY_CHILDREN) + { + let seq = unwrap_tag(seq); + if let YamlData::Sequence(items) = &seq.data { + let children_path = path.key(KEY_CHILDREN); + let mut built = Vec::with_capacity(items.len()); + for (i, item) in items.iter().enumerate() { + let child_at = format!("{at}.{KEY_CHILDREN}[{i}]"); + // A child that could not be read is dropped, as in every port; + // the problem is already collected. + if let Some(child) = + self.node(Some(item), &children_path.index(built.len()), &child_at) + { + built.push(child); + } + } + out.insert(KEY_CHILDREN.to_string(), Value::Array(built)); + } else { + // A non-list `children` is left as written; the parser reports it. + out.insert(KEY_CHILDREN.to_string(), to_value(seq)); + } + } + out + } + + /// The coercion guard for one inline attribute: YAML read an unquoted value as + /// a boolean, number or null where the schema declares something else. + fn check_coercion(&mut self, name: &str, raw: &Value, value_type: &str, at: &str) { + let mismatch = |expected: &str| Some((name.to_string(), raw.clone(), expected.to_string())); + let found = match value_type { + ATTR_SUBTYPE_STRING | ATTR_SUBTYPE_CLASS => { + (!raw.is_string()).then(|| mismatch("string")).flatten() + } + ATTR_SUBTYPE_BOOLEAN => (!raw.is_boolean()).then(|| mismatch("boolean")).flatten(), + ATTR_SUBTYPE_INT | ATTR_SUBTYPE_LONG | ATTR_SUBTYPE_DOUBLE => { + (!raw.is_number()).then(|| mismatch("number")).flatten() + } + ATTR_SUBTYPE_STRINGARRAY => match raw { + // A bare string is the one-element shorthand, not a coercion. + Value::String(_) => None, + Value::Array(items) => { + let bad = items.iter().position(|v| !v.is_string()); + bad.map(|i| { + ( + format!("{name}[{i}]"), + items[i].clone(), + "string (in string-array)".to_string(), + ) + }) + } + _ => mismatch("string-array (or single string)"), + }, + // Object-shaped attributes accept any object or array. + _ => None, + }; + let Some((label, value, expected)) = found else { + return; + }; + let literal = match &value { + Value::Null => "null".to_string(), + Value::Object(_) | Value::Array(_) => value.to_string(), + other => js_display(other), + }; + self.error( + ERR_YAML_COERCION, + format!( + "Attribute '@{label}' at {at}: expected {expected} but got {} ({literal}). YAML 1.2 silently coerced an unquoted value — quote it in YAML: '@{label}: \"{literal}\"' not '@{label}: {literal}'.", + coerced_type_name(&value) + ), + ); + } +} + +fn coerced_type_name(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} diff --git a/server/rust/metaobjects/tests/config_reader.rs b/server/rust/metaobjects/tests/config_reader.rs new file mode 100644 index 0000000000..cc07cf7250 --- /dev/null +++ b/server/rust/metaobjects/tests/config_reader.rs @@ -0,0 +1,621 @@ +//! The `.metaobjects/config.json` reader, source walk, discovery and shipped +//! libraries: the shared config-block corpora plus the behaviour the source +//! resolution corpus cannot express. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, Ordering}; + +use metaobjects::collection::{discover_collection_root, resolve_collection}; +use metaobjects::config::{ + DependencyTransport, HandEditsPolicy, LoadedConfig, UnknownFieldsMode, WireDecimals, + WireDurations, WireNullMembers, parse_config, parse_config_text, +}; +use metaobjects::errors::{ + ERR_BAD_ATTR_VALUE, ERR_COLLECTION_NOT_FOUND, ERR_MALFORMED_JSON, ERR_SOURCE_UNRESOLVED, + ERR_UNKNOWN_LIBRARY, MetaError, +}; +use metaobjects::library::{ + known_library_tokens, library_manifests, library_packages, library_ref_text, library_refs, + library_sources, split_layer_token, +}; +use metaobjects::naming::NamingRegistry; +use metaobjects::sources::list_metadata_files; +use serde_json::{Value, json}; + +fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures") +} + +fn corpus(rel: &str) -> Value { + serde_json::from_str(&std::fs::read_to_string(fixtures().join(rel)).unwrap()).unwrap() +} + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-config-reader-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + fn write(&self, rel: &str, text: &str) { + let p = self.0.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } + fn config(&self, cfg: &Value) { + self.write(".metaobjects/config.json", &cfg.to_string()); + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn parse(block_key: &str, block: &Value) -> Result { + let mut doc = json!({ "schema_version": 1 }); + if !block.is_null() { + doc[block_key] = block.clone(); + } + parse_config(&doc, "config.json", &NamingRegistry::builtin()) +} + +fn rel_files(root: &Path, files: &[PathBuf]) -> Vec { + files + .iter() + .map(|f| f.strip_prefix(root).unwrap().to_string_lossy().into_owned()) + .collect() +} + +// --- shared config-block corpora ------------------------------------------ + +#[test] +fn api_block_corpus() { + let doc = corpus("api-contract-conformance/api-settings/config-blocks.json"); + for c in doc["cases"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let cfg = parse("api", &c["api"]) + .unwrap_or_else(|e| panic!("{name}: {e}")) + .config; + match &c["pagination"] { + Value::Null => assert!(cfg.api_pagination().is_none(), "{name}"), + p => { + let got = cfg + .api_pagination() + .unwrap_or_else(|| panic!("{name}: no pagination")); + assert_eq!( + u64::from(got.default_limit), + p["defaultLimit"].as_f64().unwrap() as u64, + "{name}" + ); + assert_eq!( + u64::from(got.max_limit), + p["maxLimit"].as_f64().unwrap() as u64, + "{name}" + ); + } + } + let want = c["unknownFields"].as_str().unwrap(); + let got = cfg + .api_unknown_fields() + .unwrap_or(UnknownFieldsMode::Reject); + assert_eq!(got.as_str(), want, "{name}"); + } + for c in doc["invalid"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let err = parse("api", &c["api"]).expect_err(name); + assert_eq!(err.code, ERR_BAD_ATTR_VALUE, "{name}"); + } +} + +#[test] +fn wire_block_corpus() { + let doc = corpus("wire-conformance/config-blocks.json"); + for c in doc["cases"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let w = parse("wire", &c["wire"]) + .unwrap_or_else(|e| panic!("{name}: {e}")) + .config + .wire_format(); + assert_eq!( + w.decimals.as_str(), + c["decimals"].as_str().unwrap(), + "{name}" + ); + assert_eq!( + w.null_members.as_str(), + c["nullMembers"].as_str().unwrap(), + "{name}" + ); + assert_eq!( + w.durations.as_str(), + c["durations"].as_str().unwrap(), + "{name}" + ); + } + for c in doc["invalid"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + assert!(parse("wire", &c["wire"]).is_err(), "{name}"); + } +} + +#[test] +fn wire_resolves_to_typed_values() { + let w = parse( + "wire", + &json!({"decimals": "string", "nullMembers": "omit", "durations": "iso"}), + ) + .unwrap() + .config + .wire_format(); + assert_eq!( + (w.decimals, w.null_members, w.durations), + ( + WireDecimals::String, + WireNullMembers::Omit, + WireDurations::Iso + ) + ); +} + +#[test] +fn enums_block_corpus() { + let doc = corpus("enum-length-conformance/cases.json"); + for c in doc["cases"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let d = parse("enums", &c["enums"]) + .unwrap_or_else(|e| panic!("{name}: {e}")) + .config + .enum_defaults(); + let want = c["enums"]["maxLength"].as_f64().map(|f| f as u64); + assert_eq!(d.max_length, want, "{name}"); + } + for c in doc["invalid"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + assert!(parse("enums", &c["enums"]).is_err(), "{name}"); + } +} + +#[test] +fn naming_block_corpus_for_builtin_strategies() { + // Cases that name an application-registered strategy need the real naming + // registry's `register` points; the built-in ones are checked here. + let doc = corpus("naming-conformance/physical-names/cases.json"); + let builtin = |v: &Value| { + v.as_object().is_none_or(|o| { + o.values().all(|s| { + matches!( + s.as_str(), + Some("snake_case" | "literal" | "kebab-case" | "pascal") + ) + }) + }) + }; + let mut ran = 0; + for c in doc["cases"].as_array().unwrap() { + if !builtin(&c["naming"]) { + continue; + } + let name = c["name"].as_str().unwrap(); + let n = parse("naming", &c["naming"]) + .unwrap_or_else(|e| panic!("{name}: {e}")) + .config + .physical_naming(); + assert_eq!( + n.columns, + c["naming"]["columns"].as_str().unwrap_or("snake_case"), + "{name}" + ); + assert_eq!( + n.tables, + c["naming"]["tables"].as_str().unwrap_or("snake_case"), + "{name}" + ); + ran += 1; + } + assert!(ran >= 6); + for c in doc["invalid"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let err = parse("naming", &c["naming"]).expect_err(name); + assert_eq!(err.code, ERR_BAD_ATTR_VALUE, "{name}"); + } +} + +// --- the reader ------------------------------------------------------------ + +#[test] +fn defaults_match_a_bare_schema_version() { + let l = parse_config( + &json!({"schema_version": 1}), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap(); + assert!(l.warnings.is_empty()); + let c = l.config; + assert!(c.pending_in_git && c.sources.is_empty() && c.dependencies.is_empty()); + assert_eq!( + ( + c.confidence_thresholds.pending_promote, + c.confidence_thresholds.drift_warn + ), + (0.8, 0.7) + ); + assert_eq!(c.wire_format(), Default::default()); + assert_eq!(c.physical_naming().columns, "snake_case"); +} + +#[test] +fn an_unknown_top_level_key_warns_and_resolves() { + let l = parse_config( + &json!({"schema_version": 1, "foo": 1}), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap(); + assert_eq!(l.warnings.len(), 1); + assert!(l.warnings[0].contains("unknown top-level key \"foo\" ignored")); +} + +#[test] +fn a_nested_typo_or_wrong_type_is_an_error() { + let n = NamingRegistry::builtin(); + for bad in [ + json!({"schema_version": 1, "migrate": {"scopee": ["x"]}}), + json!({"schema_version": 1, "migrate": {"d1": {"bindingg": "x"}}}), + json!({"schema_version": 1, "migrate": {"dialect": "mysql"}}), + json!({"schema_version": 1, "migrate": {"allow": ["drop-everything"]}}), + json!({"schema_version": 1, "migrate": {"checks": {"skipRedundant": "yes"}}}), + json!({"schema_version": 1, "scope": {"scopes": []}}), + json!({"schema_version": 1, "scope": {"include": [""]}}), + json!({"schema_version": 1, "verify": {"handEdits": "maybe"}}), + json!({"schema_version": 1, "verify": {"other": 1}}), + json!({"schema_version": 1, "requirements": {"inheret": []}}), + json!({"schema_version": 1, "csharp": {"outDir": ""}}), + json!({"schema_version": 1, "libraries": "iam"}), + json!({"schema_version": 1, "pending_in_git": "true"}), + json!({"schema_version": 1, "confidence_thresholds": {"drift_warn": 2}}), + json!([1]), + ] { + assert!(parse_config(&bad, "c.json", &n).is_err(), "{bad}"); + } +} + +#[test] +fn the_error_names_the_file_the_path_and_the_sources_hint() { + let err = parse_config( + &json!({"schema_version": 1, "sources": ["model"]}), + "/p/.metaobjects/config.json", + &NamingRegistry::builtin(), + ) + .unwrap_err(); + assert!( + err.message + .starts_with("/p/.metaobjects/config.json is not a valid MetaObjects config:") + ); + assert!(err.message.contains("sources[0]:")); + assert!(err.message.contains("never a bare string")); +} + +#[test] +fn extract_and_confidence_thresholds_ignore_unknown_keys_as_the_typescript_reader_does() { + let c = parse_config( + &json!({"schema_version": 1, "extract": {"metaignore": ".m", "x": 1}, "confidence_thresholds": {"y": 1}}), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap() + .config; + assert_eq!(c.extract_metaignore.as_deref(), Some(".m")); +} + +#[test] +fn migrate_verify_requirements_scope_and_csharp_are_kept() { + let c = parse_config( + &json!({ + "schema_version": 1, + "migrate": {"dialect": "postgres", "scope": ["a::**"], "conventions": "efcore", + "checks": {"skipRedundant": true}, "foreignKeyIndexes": true, + "d1": {"binding": "DB", "remote": false}, "allow": ["drop-table"]}, + "verify": {"handEdits": "fail"}, + "requirements": {"inherit": ["acme::common"]}, + "scope": {"include": ["a::**"], "exclude": ["a::x"]}, + "csharp": {"outDir": "gen", "providers": [{"assembly": "p.dll", "type": "P.Prov"}]} + }), + "c.json", + &NamingRegistry::builtin(), + ) + .unwrap() + .config; + let m = c.migrate.unwrap(); + assert_eq!(m.dialect.as_deref(), Some("postgres")); + assert_eq!(m.checks_skip_redundant, Some(true)); + assert_eq!(m.d1.unwrap().binding.as_deref(), Some("DB")); + assert_eq!(c.hand_edits, Some(HandEditsPolicy::Fail)); + assert_eq!(c.requirements_inherit.unwrap(), ["acme::common"]); + assert_eq!(c.scope.unwrap().exclude.unwrap(), ["a::x"]); + assert_eq!(c.csharp.unwrap().providers.unwrap()[0].type_name, "P.Prov"); +} + +#[test] +fn dependencies_are_validated_and_names_must_be_unique() { + let n = NamingRegistry::builtin(); + let ok = parse_config( + &json!({"schema_version": 1, "dependencies": [ + {"name": "a", "path": "../a"}, + {"name": "b", "npm": "@x/b", "dir": "m"}, + {"name": "c", "maven": "g:a", "version": "1"}]}), + "c.json", + &n, + ) + .unwrap() + .config; + assert_eq!(ok.dependencies.len(), 3); + assert!(matches!( + ok.dependencies[2].transport, + DependencyTransport::Maven { .. } + )); + for bad in [ + json!([{"name": "a", "path": "x"}, {"name": "a", "path": "y"}]), + json!([{"name": "A", "path": "x"}]), + json!([{"name": "a"}]), + json!([{"name": "a", "path": "x", "npm": "y"}]), + json!([{"name": "a", "path": "x", "dir": "d"}]), + json!([{"name": "a", "maven": "g:a"}]), + json!([{"name": "a", "path": "x", "pathh": "typo"}]), + ] { + assert!( + parse_config( + &json!({"schema_version": 1, "dependencies": bad}), + "c.json", + &n + ) + .is_err(), + "{bad}" + ); + } +} + +#[test] +fn malformed_json_is_a_coded_error() { + let e = parse_config_text("{ nope", "c.json", &NamingRegistry::builtin()).unwrap_err(); + assert_eq!(e.code, ERR_MALFORMED_JSON); +} + +// --- collection, discovery, walk ---------------------------------------------- + +#[test] +fn collection_carries_the_declared_settings_and_unresolved_dependencies() { + let s = Scratch::new(); + s.write("model/meta.a.json", "{}"); + s.config(&json!({ + "schema_version": 1, "sources": [{"path": "model"}], + "naming": {"columns": "literal"}, "wire": {"decimals": "string"}, + "api": {"unknownFields": "drop"}, "enums": {"maxLength": 16}, + "migrate": {"conventions": "efcore", "checks": {"skipRedundant": true}, "foreignKeyIndexes": true, "scope": ["a::**"]}, + "verify": {"handEdits": "fail"}, "dependencies": [{"name": "d", "path": "../d"}], "foo": 1 + })); + let c = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap(); + assert_eq!(c.physical_naming.columns, "literal"); + assert_eq!(c.wire_format.decimals, WireDecimals::String); + assert_eq!(c.api_unknown_fields, Some(UnknownFieldsMode::Drop)); + assert_eq!(c.enum_defaults.max_length, Some(16)); + assert_eq!(c.schema_conventions.as_deref(), Some("efcore")); + assert!(c.skip_redundant_checks && c.foreign_key_indexes); + assert_eq!(c.hand_edits, Some(HandEditsPolicy::Fail)); + assert_eq!(c.migrate_scope.as_deref(), Some(&["a::**".to_string()][..])); + assert_eq!(c.dependencies.len(), 1); + assert_eq!(c.warnings.len(), 1); + assert_eq!(c.source_roots, [s.0.join("model")]); +} + +#[test] +fn discovery_finds_the_nearest_config_and_stops_at_git() { + let s = Scratch::new(); + s.write(".git/HEAD", ""); + s.write("a/.metaobjects/config.json", "{\"schema_version\":1}"); + s.write("a/b/.metaobjects/config.json", "{\"schema_version\":1}"); + s.write("a/b/c/d/.keep", ""); + s.write("x/y/.keep", ""); + let found = discover_collection_root(&s.0.join("a/b/c/d")); + assert_eq!((found.dir, found.has_config), (s.0.join("a/b"), true)); + // The repository boundary stops the walk: no config above `.git` is adopted. + let none = discover_collection_root(&s.0.join("x/y")); + assert!(!none.has_config); + assert_eq!(none.dir, s.0.join("x/y")); +} + +#[test] +fn a_repo_root_project_is_found_from_a_subdirectory() { + let s = Scratch::new(); + s.write(".git/HEAD", ""); + s.config(&json!({"schema_version": 1})); + s.write("metaobjects/meta.a.json", "{}"); + s.write("pkg/src/.keep", ""); + let c = resolve_collection(&s.0.join("pkg/src"), None, &NamingRegistry::builtin()).unwrap(); + assert_eq!(c.config_dir, s.0); + assert_eq!(rel_files(&s.0, &c.files), ["metaobjects/meta.a.json"]); +} + +#[test] +fn a_metadata_directory_handed_as_the_root_is_diagnosed() { + let s = Scratch::new(); + s.write(".git/HEAD", ""); + s.write("meta.a.json", "{\"metadata.root\": {}}"); + let e = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap_err(); + assert_eq!(e.code, ERR_COLLECTION_NOT_FOUND); + assert!(e.message.contains("looks like a metadata directory")); +} + +#[test] +fn a_walk_lists_files_before_subdirectories_and_skips_pending() { + let s = Scratch::new(); + for f in [ + "m/z.json", + "m/a/inner.json", + "m/_pending/draft.json", + "m/b.yaml", + "m/a/_pending/x.json", + ] { + s.write(f, "{}"); + } + let files = list_metadata_files(&s.0.join("m")).unwrap(); + assert_eq!( + rel_files(&s.0, &files), + ["m/b.yaml", "m/z.json", "m/a/inner.json"] + ); +} + +#[test] +fn a_directory_reachable_by_two_symlinks_is_a_diamond_not_a_cycle() { + let s = Scratch::new(); + s.write("m/real/meta.a.json", "{}"); + std::os::unix::fs::symlink(s.0.join("m/real"), s.0.join("m/one")).unwrap(); + std::os::unix::fs::symlink(s.0.join("m/real"), s.0.join("m/two")).unwrap(); + let files = list_metadata_files(&s.0.join("m")).unwrap(); + assert_eq!(files.len(), 3); +} + +#[test] +fn a_symlink_that_revisits_an_ancestor_raises_on_the_revisit() { + let s = Scratch::new(); + s.write("m/meta.a.json", "{}"); + std::os::unix::fs::symlink(s.0.join("m"), s.0.join("m/loop")).unwrap(); + let e = list_metadata_files(&s.0.join("m")).unwrap_err(); + assert!(e.message.contains("symlink loop detected")); +} + +#[test] +fn a_dangling_symlink_is_skipped() { + let s = Scratch::new(); + s.write("m/meta.a.json", "{}"); + std::os::unix::fs::symlink(s.0.join("nowhere"), s.0.join("m/dangling.json")).unwrap(); + assert_eq!(list_metadata_files(&s.0.join("m")).unwrap().len(), 1); +} + +#[test] +fn an_absolute_path_source_is_taken_as_written() { + let s = Scratch::new(); + s.write("elsewhere/meta.a.json", "{}"); + s.config(&json!({"schema_version": 1, "sources": [{"path": s.0.join("elsewhere").to_string_lossy()}]})); + let c = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap(); + assert_eq!(rel_files(&s.0, &c.files), ["elsewhere/meta.a.json"]); +} + +#[test] +fn a_missing_declared_path_is_unresolved_even_beside_a_default_directory() { + let s = Scratch::new(); + s.write("metaobjects/meta.a.json", "{}"); + s.config(&json!({"schema_version": 1, "sources": [{"path": "nope"}]})); + let e = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap_err(); + assert_eq!(e.code, ERR_SOURCE_UNRESOLVED); +} + +// --- libraries ---------------------------------------------------------------- + +#[test] +fn the_shipped_tokens_and_manifests_are_embedded() { + assert_eq!(known_library_tokens(), ["ai", "ai/db", "iam", "iam/db"]); + assert_eq!(library_manifests()["iam"].name, "iam"); + assert!(library_packages().contains("metaobjects::iam")); + assert_eq!(split_layer_token("iam/db"), ("iam", "db")); + assert_eq!(split_layer_token("iam"), ("iam", "")); + assert_eq!(split_layer_token("a/b/c"), ("a", "b/c")); +} + +#[test] +fn every_manifest_ref_has_embedded_text_matching_the_repo_file() { + for name in library_manifests().keys() { + for r in library_refs(name) { + let text = library_ref_text(&r).unwrap_or_else(|| panic!("{r} not embedded")); + let disk = + std::fs::read_to_string(fixtures().join("../library").join(format!("{r}.yaml"))) + .unwrap(); + assert_eq!(text, disk, "{r}"); + } + } +} + +fn ids(sel: &[&str]) -> Vec { + let sel: Vec = sel.iter().map(|s| (*s).to_string()).collect(); + library_sources(&sel) + .into_iter() + .map(|(id, _)| id) + .collect() +} + +#[test] +fn library_sources_order_core_first_and_a_layer_implies_its_core() { + assert_eq!( + ids(&["iam"]), + ["library:iam/model.yaml", "library:iam/requirements.yaml"] + ); + assert_eq!( + ids(&["iam/db"]), + [ + "library:iam/model.yaml", + "library:iam/requirements.yaml", + "library:iam/db.yaml" + ] + ); + // Every core layer first, even when a db layer is named before its core. + assert_eq!( + ids(&["iam/db", "ai"]), + [ + "library:iam/model.yaml", + "library:iam/requirements.yaml", + "library:ai/model.yaml", + "library:ai/requirements.yaml", + "library:iam/db.yaml" + ] + ); + assert_eq!(ids(&["iam", "iam", "iam/db"]).len(), 3); +} + +#[test] +fn an_unknown_layer_is_dropped_whole_not_reduced_to_its_core() { + assert!(ids(&["iam/database"]).is_empty()); + assert!(ids(&["nope"]).is_empty()); +} + +#[test] +fn an_unknown_library_in_a_config_is_refused_with_the_available_tokens() { + let s = Scratch::new(); + s.write("metaobjects/meta.a.json", "{}"); + s.config(&json!({"schema_version": 1, "libraries": ["iam/database"]})); + let e = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap_err(); + assert_eq!(e.code, ERR_UNKNOWN_LIBRARY); + assert!(e.message.contains("\"iam/database\"")); + assert!(e.message.contains("[\"ai\",\"ai/db\",\"iam\",\"iam/db\"]")); +} + +#[test] +fn read_sources_puts_libraries_first_then_own_files_and_reports_unreadable_ones() { + let s = Scratch::new(); + s.write("metaobjects/meta.a.json", "{\"a\":1}"); + s.write("metaobjects/bad.json", "x"); + s.config(&json!({"schema_version": 1, "libraries": ["ai"]})); + // Not valid UTF-8, so reading it as text fails while the rest still load. + std::fs::write(s.0.join("metaobjects/bad.json"), [0xff, 0xfe]).unwrap(); + let c = resolve_collection(&s.0, Some(&s.0), &NamingRegistry::builtin()).unwrap(); + let (pairs, errors) = c.read_sources(); + let ids: Vec<&str> = pairs.iter().map(|(i, _)| i.as_str()).collect(); + assert_eq!( + &ids[..2], + ["library:ai/model.yaml", "library:ai/requirements.yaml"] + ); + assert_eq!(ids.len(), 3); + assert!(ids[2].ends_with("metaobjects/meta.a.json") && Path::new(ids[2]).is_absolute()); + assert_eq!(errors.len(), 1); + assert!(errors[0].message.contains("bad.json")); +} diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 635c0a9dfd..b933daf43d 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,7 +1,7 @@ { "language": "rust", - "notes": "The Rust port is in preview. This step (the loader core) parses, merges, resolves extends and serializes; it does not yet run the validation passes (the unknown-attr provenance check, ERR_UNKNOWN_ATTR, among them), emit merge warnings, resolve the reporting rule that binds a bare entity name in the package its path already fixes, or run script.json operations. Every fixture listed here fails for one of those reasons and leaves the ledger when the step that covers it lands. The ledger may only shrink. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 256, + "notes": "The Rust port is in preview. The loader reads JSON and YAML, merges, resolves extends and serializes; it does not yet run the validation passes (the unknown-attr provenance check, ERR_UNKNOWN_ATTR, among them), emit merge warnings, resolve the reporting rule that binds a bare entity name in the package its path already fixes, or run script.json operations. Every fixture listed here fails for one of those reasons and leaves the ledger when the step that covers it lands. The ledger may only shrink. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", + "minPassing": 261, "fixtures": [ "error-agg-all-non-boolean", "error-agg-any-missing-filter", diff --git a/server/rust/metaobjects/tests/naming-conformance-expected-failures.json b/server/rust/metaobjects/tests/naming-conformance-expected-failures.json new file mode 100644 index 0000000000..cf540b9962 --- /dev/null +++ b/server/rust/metaobjects/tests/naming-conformance-expected-failures.json @@ -0,0 +1 @@ +{ "cases": [] } diff --git a/server/rust/metaobjects/tests/naming_conformance.rs b/server/rust/metaobjects/tests/naming_conformance.rs new file mode 100644 index 0000000000..1e540462e7 --- /dev/null +++ b/server/rust/metaobjects/tests/naming_conformance.rs @@ -0,0 +1,455 @@ +//! The shared naming corpus (`fixtures/naming-conformance/`): the pluralizer pair, the +//! collection-name collision refusal, the REST collection segments and the physical +//! names every port resolves through its naming door. +//! +//! `naming-conformance-expected-failures.json` beside this file is the ledger of cases +//! this port does not pass. It may only shrink, and it is empty. + +use std::collections::BTreeSet; +use std::path::PathBuf; + +use serde_json::Value; + +use metaobjects::errors::ERR_COLLECTION_NAME_COLLISION; +use metaobjects::loader::Loader; +use metaobjects::naming::{ + CollectionNameScopes, NamingCtx, NamingKind, NamingRegistry, OutputLayout, PhysicalNaming, + assert_no_collection_name_collisions, collection_segment_of, pluralize, + pluralize_table_name_legacy, resolve_column_name, resolve_flattened_column_name, + resolve_table_name, top_level_objects, +}; +use metaobjects::node::{NodeId, Tree}; +use metaobjects::providers::default_registry; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/naming-conformance") +} + +fn read_json(path: PathBuf) -> Value { + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}")); + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{path:?}: {e}")) +} + +fn ledger() -> BTreeSet { + let v = read_json( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/naming-conformance-expected-failures.json"), + ); + v["cases"] + .as_array() + .expect("cases array") + .iter() + .map(|c| c.as_str().expect("string").to_string()) + .collect() +} + +/// Run every named check; the ledger lists the ones allowed to fail, and a listed check +/// that passes fails the run (the ledger may only shrink). +fn run_checks(checks: Vec<(String, Result<(), String>)>) { + let expected = ledger(); + let mut problems = Vec::new(); + let mut seen = BTreeSet::new(); + for (name, result) in &checks { + seen.insert(name.clone()); + match (result, expected.contains(name)) { + (Err(e), false) => problems.push(format!("FAIL {name}: {e}")), + (Ok(()), true) => { + problems.push(format!("{name} passes now: remove it from the ledger")) + } + _ => {} + } + } + for name in &expected { + if !seen.contains(name) { + problems.push(format!("ledger names unknown check {name}")); + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); + assert!(!checks.is_empty()); +} + +fn eq(what: &str, got: &str, want: &str) -> Result<(), String> { + if got == want { + Ok(()) + } else { + Err(format!("{what}: got {got:?}, want {want:?}")) + } +} + +fn load(sources: &[(String, String)]) -> (Tree, NodeId) { + let registry = default_registry().expect("the built-in providers compose"); + let r = Loader::new(®istry).load_sources(sources); + assert!(r.errors.is_empty(), "{:?}", r.errors); + (r.tree, r.root) +} + +fn s(v: &Value) -> &str { + v.as_str().expect("string") +} + +// ---- pluralizers ---------------------------------------------------------------- + +#[test] +fn already_plural_pluralizer_pair() { + let d = read_json(corpus().join("already-plural-pluralize.json")); + let mut checks = Vec::new(); + for c in d["cases"].as_array().unwrap() { + let name = s(&c["name"]); + checks.push(( + format!("api:{name}"), + eq("apiPlural", &pluralize(name), s(&c["apiPlural"])), + )); + checks.push(( + format!("legacy:{name}"), + eq( + "legacyPlural", + &pluralize_table_name_legacy(name), + s(&c["legacyPlural"]), + ), + )); + } + run_checks(checks); +} + +// ---- collection segments ----------------------------------------------------------- + +#[test] +fn collection_segments() { + let d = read_json(corpus().join("collection-segments.json")); + let registry = NamingRegistry::builtin(); + let mut checks = Vec::new(); + for (i, c) in d["cases"].as_array().unwrap().iter().enumerate() { + let name = s(&c["name"]); + let got = collection_segment_of( + ®istry, + name, + c.get("collectionName").map(s), + c.get("pluralizer").map(s), + ) + .map_err(|e| e.message); + let result = got.and_then(|g| eq("segment", &g, s(&c["segment"]))); + checks.push((format!("segment:{i}:{name}"), result)); + } + run_checks(checks); +} + +// ---- collisions --------------------------------------------------------------------- + +/// One package's file: an entity with an `id` identity, and a source unless told not to. +fn entity_json(name: &str, is_abstract: bool, source: bool) -> String { + let source = if source { r#"{"source.rdb": {}},"# } else { "" }; + let abs = if is_abstract { + r#""abstract": true,"# + } else { + "" + }; + format!( + r#"{{"object.entity": {{"name": "{name}", {abs} "children": [{source} + {{"field.long": {{"name": "id"}}}}, + {{"identity.primary": {{"name": "id", "@fields": "id"}}}}]}}}}"# + ) +} + +fn file(package: &str, objects: &[String]) -> (String, String) { + ( + format!("meta.{}.json", package.replace("::", ".")), + format!( + r#"{{"metadata.root": {{"package": "{package}", "children": [{}]}}}}"#, + objects.join(",") + ), + ) +} + +fn refuse(tree: &Tree, root: NodeId, layout: OutputLayout) -> Result<(), metaobjects::MetaError> { + let registry = NamingRegistry::builtin(); + let naming = PhysicalNaming::default(); + let ctx = NamingCtx::new(®istry, &naming); + let scopes = CollectionNameScopes { + layout, + ..CollectionNameScopes::default() + }; + let objects = top_level_objects(tree, root); + let mut reversed = objects.clone(); + reversed.reverse(); + // Both orders reach the same verdict. + let a = assert_no_collection_name_collisions(tree, &objects, &scopes, &ctx); + let b = assert_no_collection_name_collisions(tree, &reversed, &scopes, &ctx); + assert_eq!(a.is_ok(), b.is_ok()); + a +} + +#[test] +fn collision_cases_are_refused() { + let d = read_json(corpus().join("already-plural-pluralize.json")); + let mut checks = Vec::new(); + for c in d["collisionCases"].as_array().unwrap() { + let (a, b, on) = (s(&c["entityA"]), s(&c["entityB"]), s(&c["collidesOn"])); + let (tree, root) = load(&[file( + "acme", + &[entity_json(a, false, true), entity_json(b, false, true)], + )]); + let result = match refuse(&tree, root, OutputLayout::Flat) { + Ok(()) => Err("accepted".to_string()), + Err(e) if e.code != ERR_COLLECTION_NAME_COLLISION => Err(format!("code {}", e.code)), + Err(e) if !e.message.contains(on) && !e.message.to_lowercase().contains(on) => { + Err(format!("message does not name {on}: {}", e.message)) + } + Err(_) => Ok(()), + }; + checks.push((format!("collision:{a}/{b}"), result)); + } + run_checks(checks); +} + +#[test] +fn shape_only_cases_are_accepted() { + let d = read_json(corpus().join("already-plural-pluralize.json")); + let mut checks = Vec::new(); + for (i, c) in d["shapeOnlyCases"].as_array().unwrap().iter().enumerate() { + let shape = &c["shapeOnly"]; + let emitting = &c["emitting"]; + let shape_file = file( + s(&shape["package"]), + &[entity_json( + s(&shape["name"]), + shape["abstract"].as_bool().unwrap(), + shape["source"].as_bool().unwrap(), + )], + ); + let emit_file = file( + s(&emitting["package"]), + &[entity_json(s(&emitting["name"]), false, true)], + ); + let mut result = Ok(()); + for sources in [ + [shape_file.clone(), emit_file.clone()], + [emit_file, shape_file], + ] { + let (tree, root) = load(&sources); + for layout in [OutputLayout::Flat, OutputLayout::Package] { + if let Err(e) = refuse(&tree, root, layout) { + result = Err(e.message); + } + } + } + checks.push((format!("shape-only:{i}:{}", s(&shape["name"])), result)); + } + run_checks(checks); +} + +#[test] +fn cross_package_collision_is_scoped() { + let d = read_json(corpus().join("already-plural-pluralize.json")); + let mut checks = Vec::new(); + for c in d["crossPackageCollisionCases"].as_array().unwrap() { + let (a, b) = (&c["entityA"], &c["entityB"]); + let (tree, root) = load(&[ + file(s(&a["package"]), &[entity_json(s(&a["name"]), false, true)]), + file(s(&b["package"]), &[entity_json(s(&b["name"]), false, true)]), + ]); + let on = s(&c["collidesOn"]); + // One scope (flat modules): refused, naming the colliding name. + let flat = match refuse(&tree, root, OutputLayout::Flat) { + Err(e) if e.code == ERR_COLLECTION_NAME_COLLISION && e.message.contains(on) => Ok(()), + other => Err(format!("flat layout: {other:?}")), + }; + // Two module scopes, routes unchecked: accepted. + let registry = NamingRegistry::builtin(); + let naming = PhysicalNaming::default(); + let ctx = NamingCtx::new(®istry, &naming); + let scopes = CollectionNameScopes { + layout: OutputLayout::Package, + modules: true, + routes: false, + }; + let pkg = assert_no_collection_name_collisions( + &tree, + &top_level_objects(&tree, root), + &scopes, + &ctx, + ) + .map_err(|e| e.message); + checks.push(("cross-package:flat".to_string(), flat)); + checks.push(("cross-package:package-modules".to_string(), pkg)); + } + run_checks(checks); +} + +// ---- physical names ------------------------------------------------------------------- + +/// What the config reader does with a `naming` block: refuse an unknown key, a block that +/// is not an object, and a name no registered strategy answers. +fn validate_block(registry: &NamingRegistry, block: &Value) -> Result { + let Some(obj) = block.as_object() else { + return Err("\"naming\" must be an object".to_string()); + }; + let mut naming = PhysicalNaming::default(); + for (key, value) in obj { + let kind = match key.as_str() { + "columns" => NamingKind::Columns, + "tables" => NamingKind::Tables, + "collections" => NamingKind::Collections, + other => return Err(format!("unknown key \"naming.{other}\"")), + }; + let name = value.as_str().ok_or("naming values are strings")?; + if !registry.has(kind, name) { + return Err(registry.unknown_strategy_message(kind, name)); + } + match kind { + NamingKind::Columns => naming.columns = name.to_string(), + NamingKind::Tables => naming.tables = name.to_string(), + NamingKind::Collections => naming.collections = Some(name.to_string()), + } + } + Ok(naming) +} + +/// The corpus's application strategies, registered through the registry's extension point. +fn registry_with(strategies: &[Value]) -> NamingRegistry { + let mut registry = NamingRegistry::builtin(); + for st in strategies { + let name = s(&st["name"]).to_string(); + let upper: Vec = st["upperCase"] + .as_array() + .map(|a| a.iter().map(|v| s(v).to_string()).collect()) + .unwrap_or_default(); + let prefix = st.get("prefix").map(s).unwrap_or("").to_string(); + let delegate = s(&st["delegate"]).to_string(); + let base = NamingRegistry::builtin(); + let apply = move |n: &str| -> String { + if upper.iter().any(|u| u == n) { + return n.to_ascii_uppercase(); + } + let inner = match delegate.as_str() { + "pascal" | "kebab-case" | "literal" => { + base.apply_column_naming_strategy(n, &delegate) + } + _ => base.apply_table_naming_rule(n, &delegate), + } + .expect("a built-in delegate"); + format!("{prefix}{inner}") + }; + match s(&st["for"]) { + "columns" => registry.register_column_strategy(&name, apply), + "tables" => registry.register_table_rule(&name, apply), + other => panic!("strategy for {other}"), + } + .expect("register"); + } + registry +} + +fn find_object(tree: &Tree, root: NodeId, name: &str) -> NodeId { + top_level_objects(tree, root) + .into_iter() + .find(|&o| tree.node(o).name == name) + .unwrap_or_else(|| panic!("no object {name}")) +} + +fn field_named(tree: &Tree, owner: NodeId, name: &str) -> NodeId { + tree.children(owner) + .iter() + .copied() + .find(|&c| tree.node(c).type_name == "field" && tree.node(c).name == name) + .unwrap_or_else(|| panic!("no field {name}")) +} + +#[test] +fn physical_names() { + let d = read_json(corpus().join("physical-names/cases.json")); + let text = std::fs::read_to_string(corpus().join("physical-names/meta.naming.json")).unwrap(); + let (tree, root) = load(&[("meta.naming.json".to_string(), text)]); + let registry = registry_with(d["strategies"].as_array().unwrap()); + let mut checks = Vec::new(); + + for c in d["cases"].as_array().unwrap() { + let case = s(&c["name"]); + let naming = match &c["naming"] { + Value::Null => Ok(PhysicalNaming::default()), + block => validate_block(®istry, block), + }; + let naming = match naming { + Ok(n) => n, + Err(e) => { + checks.push((format!("{case}:config"), Err(e))); + continue; + } + }; + let ctx = NamingCtx::new(®istry, &naming); + for (obj, want) in c["tables"].as_object().unwrap() { + let got = resolve_table_name(&tree, find_object(&tree, root, obj), &ctx) + .map_err(|e| e.message) + .and_then(|g| eq("table", &g, s(want))); + checks.push((format!("{case}:table:{obj}"), got)); + } + for (key, want) in c["columns"].as_object().unwrap() { + let parts: Vec<&str> = key.split('.').collect(); + let owner = find_object(&tree, root, parts[0]); + let field = field_named(&tree, owner, parts[1]); + let got = if parts.len() == 3 { + let target = tree + .attr(field, "objectRef") + .and_then(Value::as_str) + .expect("objectRef"); + let value_obj = + find_object(&tree, root, metaobjects::naming::strip_package(target)); + let member = field_named(&tree, value_obj, parts[2]); + resolve_flattened_column_name(&tree, field, member, &ctx) + } else { + resolve_column_name(&tree, field, &ctx) + } + .map_err(|e| e.message) + .and_then(|g| eq("column", &g, s(want))); + checks.push((format!("{case}:column:{key}"), got)); + } + } + + for c in d["invalid"].as_array().unwrap() { + let case = s(&c["name"]); + let result = match validate_block(®istry, &c["naming"]) { + Ok(_) => Err("accepted".to_string()), + Err(message) => { + let missing: Vec<&str> = c + .get("messageIncludes") + .and_then(Value::as_array) + .map(|a| a.iter().map(s).filter(|m| !message.contains(m)).collect()) + .unwrap_or_default(); + if missing.is_empty() { + Ok(()) + } else { + Err(format!("message {message:?} lacks {missing:?}")) + } + } + }; + checks.push((format!("invalid:{case}"), result)); + } + run_checks(checks); +} + +// ---- resolvers beyond the corpus -------------------------------------------------------- + +#[test] +fn a_conflicting_primary_source_pair_is_refused() { + let (tree, root) = load(&[( + "meta.a.json".to_string(), + r#"{"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "A", "children": [ + {"source.rdb": {"@table": "a_one", "@schema": "s1"}}, + {"source.rdb": {"name": "second", "@table": "a_two"}}]}}]}}"# + .to_string(), + )]); + let registry = NamingRegistry::builtin(); + let naming = PhysicalNaming::default(); + let ctx = NamingCtx::new(®istry, &naming); + let a = find_object(&tree, root, "A"); + let err = resolve_table_name(&tree, a, &ctx).unwrap_err(); + assert!( + err.message.contains("role=primary sources disagree"), + "{}", + err.message + ); + assert!( + err.message + .contains("\"a_two\" (table) vs \"s1\".\"a_one\" (table)") + ); +} diff --git a/server/rust/metaobjects/tests/project_load.rs b/server/rust/metaobjects/tests/project_load.rs new file mode 100644 index 0000000000..28e819d4dc --- /dev/null +++ b/server/rust/metaobjects/tests/project_load.rs @@ -0,0 +1,147 @@ +//! A whole project read the way the other ports read it: find the collection, +//! read its config, gather its files (YAML and JSON, plus the opted-in +//! libraries), and hand the text to the loader. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; + +use serde_json::json; + +use metaobjects::collection::resolve_collection; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::default_registry; + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-project-load-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + fn write(&self, rel: &str, text: &str) { + let p = self.0.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +const USERS_YAML: &str = "\ +metadata: + package: shop + children: + - object.entity: + name: User + children: + - field.long: id + - field.string[]: tags + - field.string: + name: email + required: true +"; + +const ORDERS_JSON: &str = r#"{ "metadata.root": { "package": "shop", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "field.long": { "name": "id" } }, + { "field.long": { "name": "userId", "@required": true } } + ] } } +] } }"#; + +fn load(dir: &Scratch) -> metaobjects::loader::LoadResult { + let mut registry = default_registry().expect("the built-in providers compose"); + registry.seal(); + let collection = + resolve_collection(&dir.0, None, &NamingRegistry::builtin()).expect("the project resolves"); + let (sources, read_errors) = collection.read_sources(); + assert!(read_errors.is_empty(), "{read_errors:?}"); + Loader::new(®istry).load_sources(&sources) +} + +#[test] +fn a_project_of_yaml_and_json_files_loads_as_one_model() { + let s = Scratch::new(); + s.write( + ".metaobjects/config.json", + &json!({ "schema_version": 1 }).to_string(), + ); + s.write("metaobjects/meta.users.yaml", USERS_YAML); + s.write("metaobjects/meta.orders.json", ORDERS_JSON); + // A file under `_pending` is not part of the model. + s.write("metaobjects/_pending/meta.draft.yaml", "not: [valid"); + let result = load(&s); + assert!(result.errors.is_empty(), "{:?}", result.errors); + let canonical = metaobjects::serializer::canonical_serialize(&result.tree, result.root); + assert!(canonical.contains("\"User\""), "{canonical}"); + assert!(canonical.contains("\"Order\""), "{canonical}"); + assert!( + canonical.contains("\"isArray\": true"), + "the `[]` key suffix becomes isArray: {canonical}" + ); +} + +#[test] +fn a_bad_yaml_file_reports_its_own_path_and_position() { + let s = Scratch::new(); + s.write( + ".metaobjects/config.json", + &json!({ "schema_version": 1 }).to_string(), + ); + s.write( + "metaobjects/meta.bad.yaml", + "metadata:\n children:\n - object.entity:\n name: A\n children:\n - field.nonesuch: x\n", + ); + let result = load(&s); + let err = result + .errors + .first() + .expect("an unknown subtype is an error"); + assert_eq!(err.source.format(), "yaml"); + assert!( + err.source.files()[0].ends_with("meta.bad.yaml"), + "{:?}", + err.source.files() + ); + let pos = err.source.yaml_position().expect("a position"); + assert_eq!( + (pos.line, pos.col), + (6, 13), + "the wrapper key's line and column" + ); +} + +#[test] +fn the_shipped_libraries_load_clean_from_their_embedded_yaml() { + let s = Scratch::new(); + s.write( + ".metaobjects/config.json", + &json!({ "schema_version": 1, "libraries": ["iam", "iam/db", "ai", "ai/db"] }).to_string(), + ); + s.write("metaobjects/meta.users.yaml", USERS_YAML); + let result = load(&s); + assert!(result.errors.is_empty(), "{:?}", result.errors); + let canonical = metaobjects::serializer::canonical_serialize(&result.tree, result.root); + assert!( + canonical.contains("\"User\""), + "the project's own entity is there" + ); + assert!( + canonical.len() > 20_000, + "the libraries added their design to the model ({} bytes)", + canonical.len() + ); +} diff --git a/server/rust/metaobjects/tests/source-resolution-expected-failures.json b/server/rust/metaobjects/tests/source-resolution-expected-failures.json new file mode 100644 index 0000000000..9afaa2d732 --- /dev/null +++ b/server/rust/metaobjects/tests/source-resolution-expected-failures.json @@ -0,0 +1,5 @@ +{ + "language": "rust", + "notes": "Case names of fixtures/source-resolution-conformance/cases.json that the Rust port does not pass yet. The ledger may only shrink; it is empty.", + "cases": [] +} diff --git a/server/rust/metaobjects/tests/source_resolution_conformance.rs b/server/rust/metaobjects/tests/source_resolution_conformance.rs new file mode 100644 index 0000000000..fbd7bdbff8 --- /dev/null +++ b/server/rust/metaobjects/tests/source_resolution_conformance.rs @@ -0,0 +1,168 @@ +//! The source-resolution gate: every case of the shared +//! `fixtures/source-resolution-conformance/cases.json` must resolve the same +//! file set (or fail the same way) as every other port. +//! +//! `tests/source-resolution-expected-failures.json` is a ledger of case names +//! known to fail. It may only shrink, and it is empty. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, Ordering}; + +use metaobjects::collection::resolve_collection; +use metaobjects::naming::NamingRegistry; +use serde_json::Value; + +fn fixture_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../fixtures/source-resolution-conformance") +} + +/// A fresh directory under `$DEV_SCRATCH` (RAM) or the system temp dir, removed on drop. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-source-resolution-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn materialize(root: &Path, case: &Value) { + for (rel, content) in case["tree"].as_object().unwrap() { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, content.as_str().unwrap()).unwrap(); + } + if let Some(links) = case.get("symlinks").and_then(Value::as_object) { + for (link, target) in links { + let link = root.join(link); + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(root.join(target.as_str().unwrap()), &link).unwrap(); + } + } + let from = root.join( + case.get("resolveFrom") + .and_then(Value::as_str) + .unwrap_or("."), + ); + if !case["config"].is_null() { + std::fs::create_dir_all(from.join(".metaobjects")).unwrap(); + std::fs::write( + from.join(".metaobjects/config.json"), + serde_json::to_string(&case["config"]).unwrap(), + ) + .unwrap(); + } + std::fs::create_dir_all(&from).unwrap(); +} + +/// Run one case; `Err` describes how it diverged. +fn run_case(case: &Value) -> Result<(), String> { + let scratch = Scratch::new(); + let root = scratch.0.clone(); + materialize(&root, case); + let from = root.join( + case.get("resolveFrom") + .and_then(Value::as_str) + .unwrap_or("."), + ); + let result = resolve_collection(&from, Some(&from), &NamingRegistry::builtin()); + match (case.get("expectFiles"), case.get("expectError")) { + (Some(files), None) => { + let c = result.map_err(|e| format!("unexpected error: {e}"))?; + let actual: Vec = c + .files + .iter() + .map(|f| { + f.strip_prefix(&root) + .unwrap_or_else(|_| panic!("{} is outside the case root", f.display())) + .to_string_lossy() + .replace('\\', "/") + }) + .collect(); + let expected: BTreeSet = files + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + let set: BTreeSet = actual.iter().cloned().collect(); + if set != expected { + return Err(format!("files {set:?} != expected {expected:?}")); + } + if actual.len() != expected.len() { + return Err(format!( + "{} files resolved, a duplicate collapsed: {actual:?}", + actual.len() + )); + } + Ok(()) + } + (None, Some(Value::String(code))) => match result { + Err(e) if e.code == code => Ok(()), + Err(e) => Err(format!("failed with {} not {code}: {}", e.code, e.message)), + Ok(_) => Err(format!("resolved, expected {code}")), + }, + (None, Some(Value::Bool(true))) => match result { + Err(e) if !e.code.is_empty() => Ok(()), + Err(_) => Err("raised an uncoded error".into()), + Ok(_) => Err("resolved, expected an error".into()), + }, + _ => Err("case has neither expectFiles nor expectError".into()), + } +} + +#[test] +fn every_case_resolves_as_pinned() { + let cases: Value = + serde_json::from_str(&std::fs::read_to_string(fixture_dir().join("cases.json")).unwrap()) + .unwrap(); + let ledger: Value = serde_json::from_str( + &std::fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/source-resolution-expected-failures.json"), + ) + .unwrap(), + ) + .unwrap(); + let expected_failures: BTreeSet<&str> = ledger["cases"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap()) + .collect(); + let (mut failed, mut unexpected_pass, mut passing) = (Vec::new(), Vec::new(), 0); + for case in cases["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + match (run_case(case), expected_failures.contains(name)) { + (Ok(()), false) => passing += 1, + (Ok(()), true) => unexpected_pass.push(name), + (Err(why), false) => failed.push(format!("{name}: {why}")), + (Err(_), true) => {} + } + } + assert!(failed.is_empty(), "cases failed:\n{}", failed.join("\n")); + assert!( + unexpected_pass.is_empty(), + "these cases pass now; remove them from the ledger: {unexpected_pass:?}" + ); + let total = cases["cases"].as_array().unwrap().len(); + assert!(total >= 27, "the corpus shrank to {total} cases"); + assert_eq!(passing, total - expected_failures.len()); +} diff --git a/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json new file mode 100644 index 0000000000..8911dde1c7 --- /dev/null +++ b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json @@ -0,0 +1,12 @@ +{ + "language": "rust", + "corpus": "fixtures/yaml-conformance", + "notes": "Every YAML-specific behaviour passes: the desugar, the coercion guard, positions, anchors, block scalars. The four fixtures below need passes that belong to the validation and reference-resolution step of this port, and leave the ledger when it lands: error-yaml-coerced-bool-in-int and error-yaml-coerced-num-in-enum expect the attribute-schema pass's ERR_BAD_ATTR_VALUE after the ERR_YAML_COERCION; yaml-ref-root-escape needs ADR-0059 R2 root-level `::` references and package-aware merging; yaml-reporting-via-of-bare needs ADR-0059 R3 (a bare `of` owner resolves in the package of the entity its via reaches). The ledger may only shrink and minPassing may only rise.", + "minPassing": 15, + "fixtures": [ + "error-yaml-coerced-bool-in-int", + "error-yaml-coerced-num-in-enum", + "yaml-ref-root-escape", + "yaml-reporting-via-of-bare" + ] +} diff --git a/server/rust/metaobjects/tests/yaml_conformance.rs b/server/rust/metaobjects/tests/yaml_conformance.rs new file mode 100644 index 0000000000..d9401ef5aa --- /dev/null +++ b/server/rust/metaobjects/tests/yaml_conformance.rs @@ -0,0 +1,173 @@ +//! The shared YAML corpus (`fixtures/yaml-conformance/`): each directory holds an +//! `input.yaml` and either an `expected.json` (the canonical serialization the +//! document must produce) or an `expected-errors.json` (the error envelopes, in +//! order). Fixtures this port does not pass yet are listed in +//! `yaml-conformance-expected-failures.json`; the ledger may only shrink, and +//! `minPassing` may only rise. + +use std::path::PathBuf; + +use serde_json::Value; + +use metaobjects::loader::Loader; +use metaobjects::providers::default_registry; +use metaobjects::serializer::canonical_serialize; + +const INPUT: &str = "input.yaml"; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/yaml-conformance") +} + +fn read_json(path: &std::path::Path) -> Value { + serde_json::from_str(&std::fs::read_to_string(path).unwrap()) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +fn check(dir: &std::path::Path) -> Vec { + let mut registry = default_registry().expect("the built-in providers compose"); + registry.seal(); + let text = std::fs::read_to_string(dir.join(INPUT)).unwrap(); + let result = Loader::new(®istry).load_sources(&[(INPUT.to_string(), text)]); + let mut failures = Vec::new(); + let errors_file = dir.join("expected-errors.json"); + if errors_file.is_file() { + let raw = read_json(&errors_file); + let wanted: Vec = match &raw { + Value::Array(items) => items.clone(), + other => other["errors"].as_array().cloned().unwrap_or_default(), + }; + if wanted.len() != result.errors.len() { + failures.push(format!( + "want {} errors, got {:?}", + wanted.len(), + result.errors.iter().map(|e| e.code).collect::>() + )); + return failures; + } + for (i, (w, g)) in wanted.iter().zip(&result.errors).enumerate() { + if w["code"].as_str() != Some(g.code) { + failures.push(format!( + "errors[{i}].code: want {}, got {}", + w["code"], g.code + )); + continue; + } + let Some(src) = w.get("source") else { continue }; + let want_format = src["format"].as_str().unwrap_or_default(); + if want_format != g.source.format() { + failures.push(format!( + "errors[{i}].format: want {want_format}, got {}", + g.source.format() + )); + } + let want_files: Vec<&str> = src["files"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + if want_files != g.source.files() { + failures.push(format!("errors[{i}].files: want {want_files:?}")); + } + if let Some(p) = src["jsonPath"].as_str() + && Some(p) != g.source.json_path() + { + failures.push(format!( + "errors[{i}].jsonPath: want {p}, got {:?}", + g.source.json_path() + )); + } + if let Some(pos) = src.get("yamlPosition") { + let got = g.source.yaml_position(); + let want = (pos["line"].as_u64(), pos["col"].as_u64()); + if got.map(|p| (Some(u64::from(p.line)), Some(u64::from(p.col)))) != Some(want) { + failures.push(format!( + "errors[{i}].yamlPosition: want {want:?}, got {got:?}" + )); + } + } + } + } else { + if !result.errors.is_empty() { + failures.push(format!( + "unexpected errors: {:?}", + result + .errors + .iter() + .map(|e| e.to_string()) + .collect::>() + )); + } + let want = std::fs::read_to_string(dir.join("expected.json")).unwrap(); + let got = canonical_serialize(&result.tree, result.root); + if want.trim() != got.trim() { + failures.push(format!("canonical mismatch; got:\n{got}")); + } + } + failures +} + +#[test] +fn yaml_corpus() { + let ledger_doc = read_json( + &PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/yaml-conformance-expected-failures.json"), + ); + assert_eq!(ledger_doc["language"], "rust"); + let min_passing = ledger_doc["minPassing"].as_u64().unwrap(); + let ledger: Vec = ledger_doc["fixtures"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + let mut dirs: Vec = std::fs::read_dir(corpus()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.join(INPUT).is_file()) + .collect(); + dirs.sort(); + let names: Vec = dirs + .iter() + .map(|d| d.file_name().unwrap().to_string_lossy().into_owned()) + .collect(); + let stale: Vec<&String> = ledger.iter().filter(|l| !names.contains(l)).collect(); + assert!(stale.is_empty(), "ledger names no fixture: {stale:?}"); + let only = std::env::var("MO_FIXTURE").ok(); + let (mut passed, mut fixed, mut unexpected) = (0u64, Vec::new(), Vec::new()); + for (dir, name) in dirs.iter().zip(&names) { + if only.as_deref().is_some_and(|o| o != name) { + continue; + } + let failures = check(dir); + match (failures.is_empty(), ledger.contains(name)) { + (true, false) => passed += 1, + (true, true) => fixed.push(name.clone()), + (false, true) => { + if only.is_some() { + eprintln!("{name} [known gap]: {}", failures.join("; ")); + } + } + (false, false) => unexpected.push(format!("{name}: {}", failures.join("; "))), + } + } + eprintln!( + "yaml corpus: {passed} of {} fixtures pass; {} on the ledger", + dirs.len(), + ledger.len() + ); + assert!( + unexpected.is_empty(), + "unlisted failures:\n{}", + unexpected.join("\n") + ); + assert!( + fixed.is_empty(), + "ledgered fixtures now pass; remove them: {fixed:?}" + ); + if only.is_none() { + assert!( + passed >= min_passing, + "{passed} pass but minPassing is {min_passing}" + ); + } +} From 68c2f9b62a375ecbf573e37251e29f3c665f8bc7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:22:18 -0500 Subject: [PATCH 2/6] no-mistakes(review): apply reviewer inline fixes --- docs/CONFORMANCE.md | 2 +- server/rust/metaobjects/examples/load_bench.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 311bb107fe..44e5341bab 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -75,7 +75,7 @@ of 526 green with the rest on `server/rust/metaobjects/tests/conformance-expecte (validation passes, merge warnings, the reporting short-name rule and the `script.json` fixtures, none of them built yet); `yaml-conformance`, 15 of 19 (the four on `yaml-conformance-expected-failures.json` wait for the attribute-schema pass and the -ADR-0059 reference rules); `source-resolution-conformance` (all 27 cases); and +ADR-0059 reference rules); `source-resolution-conformance` (all 28 cases); and `naming-conformance` (all of it). Those ledgers may only shrink. While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when the port leaves preview. A regression still diff --git a/server/rust/metaobjects/examples/load_bench.rs b/server/rust/metaobjects/examples/load_bench.rs index 52037d4bcf..7ae6ce4d63 100644 --- a/server/rust/metaobjects/examples/load_bench.rs +++ b/server/rust/metaobjects/examples/load_bench.rs @@ -134,7 +134,7 @@ fn main() { "yaml" => (false, true, false), "project" => (false, false, true), "all" => (true, true, true), - other => panic!("mode is json, yaml or all, not {other}"), + other => panic!("mode is json, yaml, project or all, not {other}"), }; assert!( FITNESS.contains(ROOT_PACKAGE), From c1b315cf209714c7443f2e0d8518919fe3ae0d6b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:27:48 -0500 Subject: [PATCH 3/6] no-mistakes(review): fix(rust): stable YAML sibling indices, per-element coercion errors --- server/rust/metaobjects/src/parser.rs | 6 ++ server/rust/metaobjects/src/yaml.rs | 81 ++++++++++--------- server/rust/metaobjects/tests/loader_edges.rs | 32 ++++++++ 3 files changed, 83 insertions(+), 36 deletions(-) diff --git a/server/rust/metaobjects/src/parser.rs b/server/rust/metaobjects/src/parser.rs index 352f1552a0..138be10198 100644 --- a/server/rust/metaobjects/src/parser.rs +++ b/server/rust/metaobjects/src/parser.rs @@ -423,6 +423,12 @@ fn build( ); continue; }; + // An empty child in a YAML document is the desugar's placeholder for + // a child that could not be read; the desugar already collected the + // problem, so the placeholder itself is skipped without an error. + if entry.is_empty() && ctx.positions.is_some() { + continue; + } if entry.len() != 1 { let message = if entry.is_empty() { format!("Child at {} has no type wrapper key", entry_path.as_str()) diff --git a/server/rust/metaobjects/src/yaml.rs b/server/rust/metaobjects/src/yaml.rs index 3b83195676..6a01922955 100644 --- a/server/rust/metaobjects/src/yaml.rs +++ b/server/rust/metaobjects/src/yaml.rs @@ -330,13 +330,13 @@ impl Desugar<'_> { let mut built = Vec::with_capacity(items.len()); for (i, item) in items.iter().enumerate() { let child_at = format!("{at}.{KEY_CHILDREN}[{i}]"); - // A child that could not be read is dropped, as in every port; - // the problem is already collected. - if let Some(child) = - self.node(Some(item), &children_path.index(built.len()), &child_at) - { - built.push(child); - } + // On a bad child keep an empty-object placeholder so sibling + // indices stay stable; the problem is already collected, and + // the parser skips the placeholder. + let child = self + .node(Some(item), &children_path.index(i), &child_at) + .unwrap_or_else(|| Value::Object(Map::new())); + built.push(child); } out.insert(KEY_CHILDREN.to_string(), Value::Array(built)); } else { @@ -351,47 +351,56 @@ impl Desugar<'_> { /// a boolean, number or null where the schema declares something else. fn check_coercion(&mut self, name: &str, raw: &Value, value_type: &str, at: &str) { let mismatch = |expected: &str| Some((name.to_string(), raw.clone(), expected.to_string())); - let found = match value_type { + let found: Vec<(String, Value, String)> = match value_type { ATTR_SUBTYPE_STRING | ATTR_SUBTYPE_CLASS => { - (!raw.is_string()).then(|| mismatch("string")).flatten() - } - ATTR_SUBTYPE_BOOLEAN => (!raw.is_boolean()).then(|| mismatch("boolean")).flatten(), - ATTR_SUBTYPE_INT | ATTR_SUBTYPE_LONG | ATTR_SUBTYPE_DOUBLE => { - (!raw.is_number()).then(|| mismatch("number")).flatten() + (!raw.is_string()).then(|| mismatch("string")).flatten().into_iter().collect() } + ATTR_SUBTYPE_BOOLEAN => (!raw.is_boolean()) + .then(|| mismatch("boolean")) + .flatten() + .into_iter() + .collect(), + ATTR_SUBTYPE_INT | ATTR_SUBTYPE_LONG | ATTR_SUBTYPE_DOUBLE => (!raw.is_number()) + .then(|| mismatch("number")) + .flatten() + .into_iter() + .collect(), ATTR_SUBTYPE_STRINGARRAY => match raw { // A bare string is the one-element shorthand, not a coercion. - Value::String(_) => None, - Value::Array(items) => { - let bad = items.iter().position(|v| !v.is_string()); - bad.map(|i| { + Value::String(_) => Vec::new(), + Value::Array(items) => items + .iter() + .enumerate() + .filter(|(_, v)| !v.is_string()) + .map(|(i, v)| { ( format!("{name}[{i}]"), - items[i].clone(), + v.clone(), "string (in string-array)".to_string(), ) }) - } - _ => mismatch("string-array (or single string)"), + .collect(), + _ => mismatch("string-array (or single string)") + .into_iter() + .collect(), }, // Object-shaped attributes accept any object or array. - _ => None, + _ => Vec::new(), }; - let Some((label, value, expected)) = found else { - return; - }; - let literal = match &value { - Value::Null => "null".to_string(), - Value::Object(_) | Value::Array(_) => value.to_string(), - other => js_display(other), - }; - self.error( - ERR_YAML_COERCION, - format!( - "Attribute '@{label}' at {at}: expected {expected} but got {} ({literal}). YAML 1.2 silently coerced an unquoted value — quote it in YAML: '@{label}: \"{literal}\"' not '@{label}: {literal}'.", - coerced_type_name(&value) - ), - ); + for (label, value, expected) in found { + let literal = match &value { + Value::Null => "null".to_string(), + Value::Object(_) | Value::Array(_) => value.to_string(), + other => js_display(other), + }; + self.error( + ERR_YAML_COERCION, + format!( + "Attribute '@{label}' at {at}: expected {expected} but got {} ({literal}). YAML 1.2 silently coerced an unquoted value — quote it in YAML: '@{label}: \"{literal}\"' not '@{label}: {literal}'.", + coerced_type_name(&value) + ), + ); + } } } diff --git a/server/rust/metaobjects/tests/loader_edges.rs b/server/rust/metaobjects/tests/loader_edges.rs index 2f0bd50c78..6e9617236b 100644 --- a/server/rust/metaobjects/tests/loader_edges.rs +++ b/server/rust/metaobjects/tests/loader_edges.rs @@ -147,3 +147,35 @@ fn a_symlink_cycle_is_walked_once() { std::fs::remove_dir_all(&dir).expect("clean up"); assert_eq!(found.expect("walk").len(), 1); } + +// The TypeScript reference keeps an empty-object placeholder for a YAML child +// that could not be desugared, so a later sibling's error keeps its source +// index (and its no-wrapper complaint is a warning there, not an error). +#[test] +fn a_bad_yaml_child_keeps_later_sibling_indices_stable() { + let r = load(&[( + "meta.a.yaml", + "metadata.root:\n name: test\n package: acme\n children:\n - object.entity:\n name: Thing\n children:\n - field.string: a\n field.int: b\n - field.nonesuch: c\n", + )]); + assert_eq!(codes(&r), ["ERR_MALFORMED_YAML", "ERR_UNKNOWN_SUBTYPE"]); + assert_eq!(r.errors[0].source.json_path(), Some("$")); + assert_eq!( + r.errors[1].source.json_path(), + Some("$['metadata.root'].children[0]['object.entity'].children[1]['field.nonesuch']") + ); +} + +// The TypeScript reference reports one ERR_YAML_COERCION per non-string element +// of a string-array value, not just the first. +#[test] +fn string_array_coercion_reports_every_bad_element() { + let r = load(&[( + "meta.a.yaml", + "metadata.root:\n name: test\n package: acme\n children:\n - object.entity:\n name: Thing\n children:\n - field.enum:\n name: color\n values: [true, false]\n", + )]); + assert_eq!(codes(&r), ["ERR_YAML_COERCION", "ERR_YAML_COERCION"]); + for (i, e) in r.errors.iter().enumerate() { + assert!(e.message.contains(&format!("'@values[{i}]'")), "{i}: {}", e.message); + assert_eq!(e.source.json_path(), Some("$"), "{i}: {:?}", e.source); + } +} From 1692e93eb7f2fe770b252828e4e815e0cf3cd4b3 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 16:06:50 -0500 Subject: [PATCH 4/6] no-mistakes(test): apply changes made during test validation --- server/rust/metaobjects/src/yaml.rs | 8 +++++--- server/rust/metaobjects/tests/loader_edges.rs | 6 +++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/server/rust/metaobjects/src/yaml.rs b/server/rust/metaobjects/src/yaml.rs index 6a01922955..5c3157dbc5 100644 --- a/server/rust/metaobjects/src/yaml.rs +++ b/server/rust/metaobjects/src/yaml.rs @@ -352,9 +352,11 @@ impl Desugar<'_> { fn check_coercion(&mut self, name: &str, raw: &Value, value_type: &str, at: &str) { let mismatch = |expected: &str| Some((name.to_string(), raw.clone(), expected.to_string())); let found: Vec<(String, Value, String)> = match value_type { - ATTR_SUBTYPE_STRING | ATTR_SUBTYPE_CLASS => { - (!raw.is_string()).then(|| mismatch("string")).flatten().into_iter().collect() - } + ATTR_SUBTYPE_STRING | ATTR_SUBTYPE_CLASS => (!raw.is_string()) + .then(|| mismatch("string")) + .flatten() + .into_iter() + .collect(), ATTR_SUBTYPE_BOOLEAN => (!raw.is_boolean()) .then(|| mismatch("boolean")) .flatten() diff --git a/server/rust/metaobjects/tests/loader_edges.rs b/server/rust/metaobjects/tests/loader_edges.rs index 6e9617236b..5083f9a8ea 100644 --- a/server/rust/metaobjects/tests/loader_edges.rs +++ b/server/rust/metaobjects/tests/loader_edges.rs @@ -175,7 +175,11 @@ fn string_array_coercion_reports_every_bad_element() { )]); assert_eq!(codes(&r), ["ERR_YAML_COERCION", "ERR_YAML_COERCION"]); for (i, e) in r.errors.iter().enumerate() { - assert!(e.message.contains(&format!("'@values[{i}]'")), "{i}: {}", e.message); + assert!( + e.message.contains(&format!("'@values[{i}]'")), + "{i}: {}", + e.message + ); assert_eq!(e.source.json_path(), Some("$"), "{i}: {:?}", e.source); } } From 9919be16931ac219ec4724a0da30cf9acf022409 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 16:19:19 -0500 Subject: [PATCH 5/6] no-mistakes(document): sync conformance corpus counts with Rust R3 --- docs/CONFORMANCE.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 44e5341bab..13e08c0ffb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -27,7 +27,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| | [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 526 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | -| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | +| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 18 / 19 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | | [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 18 | ✓ | ✓ | inherits via Java | ✓ | ✓ | @@ -47,7 +47,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ | -| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 25 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 28 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (serializer arm: the 9 publish cases' document bytes; no publisher) | @@ -434,12 +434,13 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. | `object-collection-name` | [features/migrations/physical-naming.md](features/migrations/physical-naming.md) (`@collectionName` and the `collections` pluralizer) | | `smoke-empty-metadata` | [features/entities.md](features/entities.md) | -### `fixtures/yaml-conformance/` (16) +### `fixtures/yaml-conformance/` (19) -All 16 fixtures → [features/yaml-authoring.md](features/yaml-authoring.md). The corpus -splits into 9 happy-path fixtures (sigil-free attrs, array suffix, anchor/alias, +All 19 fixtures → [features/yaml-authoring.md](features/yaml-authoring.md). The corpus +splits into 12 happy-path fixtures (sigil-free attrs, array suffix, anchor/alias, block scalars, mixed bare-and-prefixed, quoted leading zero, an overlay declared -before its base in one file, etc.) and 7 `error-yaml-*` fixtures that pin the +before its base in one file, parent-relative and root-escape `ref`s, a bare `of` +on a reporting measure, etc.) and 7 `error-yaml-*` fixtures that pin the YAML 1.1 coercion guards (bool / null / hex in string contexts; numeric in enum contexts; reserved-as-attr). @@ -532,9 +533,9 @@ that reads real views, so it runs full stack on Postgres, SQLite and MySQL port, and on D1's local runtime in TypeScript. The `decimal/` sub-corpus does the same over decimal columns. -### `fixtures/source-resolution-conformance/` (25 cases) +### `fixtures/source-resolution-conformance/` (28 cases) -All 25 cases → [features/metadata-sources.md](features/metadata-sources.md) (how a +All 28 cases → [features/metadata-sources.md](features/metadata-sources.md) (how a declared `sources` set resolves to a file list). Companion to `scope-conformance/` below — `sources` decides which files are read, `scope` filters what is emitted from them. The corpus is file-shaped: one committed @@ -784,8 +785,8 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 526 + yaml 16 + verify 45 -+ render 18 + persistence 67 + api-contract 139 + source-resolution 25 + scope 10 + +The fixtures in the nine corpora mapped above (metamodel 526 + yaml 19 + verify 45 ++ render 18 + persistence 67 + api-contract 139 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider From ca24c4bd3ea1a61a352a5d6fe2c24fb3166e18df Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 18:27:51 -0500 Subject: [PATCH 6/6] no-mistakes(document): fix Rust metamodel ledger counts after merge --- CHANGELOG.md | 7 ++++--- docs/CONFORMANCE.md | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 726194a890..6335cff10d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,9 +18,10 @@ here.** that reads packages, children, subtypes, attributes, `extends` and references, with the canonical serializer. The loader freezes the tree when it finishes, and a frozen tree memoizes its resolved reads (effective children, attrs and array-ness) for many concurrent readers, as - the other ports do. It passes `registry-conformance` byte for byte and 256 of the 510 - metamodel fixtures; the other 254 are on a ledger that may only shrink (the validation passes, - merge warnings, the reporting short-name rule and `script.json` fixtures it does not run yet). + the other ports do. It passes `registry-conformance` byte for byte and 261 of the 526 + metamodel fixtures; 254 of the rest are on a ledger that may only shrink (the validation passes, + merge warnings, the reporting short-name rule and `script.json` fixtures it does not run yet), + and 11 newer fixtures fail unlisted until those passes land. While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; a fixture that passed and regresses still fails it, because the ledger records how many fixtures must pass. Nothing is published and there is no codegen diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 13e08c0ffb..97d21cc83a 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -71,9 +71,10 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor **Rust (preview, ADR-0065) is not a column yet.** The sixth port runs five corpora today: `registry-conformance` (byte-identical manifest); the metamodel corpus, 261 -of 526 green with the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` +of 526 green, 254 of the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` (validation passes, merge warnings, the reporting short-name rule and the `script.json` -fixtures, none of them built yet); `yaml-conformance`, 15 of 19 (the four on +fixtures, none of them built yet) and 11 fixtures from the newer corpus failing unlisted +until those same validation passes land; `yaml-conformance`, 15 of 19 (the four on `yaml-conformance-expected-failures.json` wait for the attribute-schema pass and the ADR-0059 reference rules); `source-resolution-conformance` (all 28 cases); and `naming-conformance` (all of it). Those ledgers may only shrink. While the port is in