From d44f9e399d9d7c1e4060a9cb0ee7ad1a4445943f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 20:33:01 -0500 Subject: [PATCH 1/6] feat(rust): choose generators in metaobjects.config.json, eject writes no machine path, crates ready to publish B1: the project's generator list is metaobjects.config.json (cargo meta init writes it, gen --list shows configured against available); no eject needed to drop a generator. B2: eject names the exact crates.io release by default and takes --engine for a checkout or git revision; the crates drop publish = false, gain packaging metadata, and the rust lane runs cargo publish --dry-run. ADR-0065 Amendment 3 records it. Nothing is published. --- CHANGELOG.md | 7 + docs/ports/rust.md | 52 +++-- scripts/ci-local.sh | 12 +- server/rust/Cargo.toml | 6 +- server/rust/metaobjects-cli/Cargo.toml | 14 +- server/rust/metaobjects-cli/LICENSE | 202 ++++++++++++++++++ server/rust/metaobjects-cli/README.md | 21 ++ server/rust/metaobjects-cli/src/lib.rs | 157 +++++++++----- server/rust/metaobjects-cli/tests/cli.rs | 176 ++++++++++++++- server/rust/metaobjects-codegen/Cargo.toml | 9 +- server/rust/metaobjects-codegen/LICENSE | 202 ++++++++++++++++++ server/rust/metaobjects-codegen/README.md | 17 ++ server/rust/metaobjects-codegen/src/eject.rs | 151 ++++++++++--- server/rust/metaobjects-codegen/src/engine.rs | 43 +++- .../metaobjects-codegen/src/generator_list.rs | 195 +++++++++++++++++ server/rust/metaobjects-codegen/src/lib.rs | 3 +- server/rust/metaobjects/Cargo.toml | 9 +- server/rust/metaobjects/LICENSE | 202 ++++++++++++++++++ server/rust/metaobjects/README.md | 14 ++ server/rust/metaobjects/src/lib.rs | 2 +- .../metaobjects/tests/vendored_data_parity.rs | 7 + .../ADR-0065-rust-is-the-sixth-port.md | 57 ++++- 22 files changed, 1429 insertions(+), 129 deletions(-) create mode 100644 server/rust/metaobjects-cli/LICENSE create mode 100644 server/rust/metaobjects-cli/README.md create mode 100644 server/rust/metaobjects-codegen/LICENSE create mode 100644 server/rust/metaobjects-codegen/README.md create mode 100644 server/rust/metaobjects-codegen/src/generator_list.rs create mode 100644 server/rust/metaobjects/LICENSE create mode 100644 server/rust/metaobjects/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 30f73a5781..db1f44666c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,13 @@ here.** a report.** For a database whose unique index on the target is hand-made and not declared in the metadata. The default, `"refuse"`, is the 1.3.0 behavior; the refusal's hint now names the setting. See [Migrations and drift](docs/features/migrations-and-drift.md). +- **Rust (ADR-0065 Amendment 3).** A project now chooses its generators in `metaobjects.config.json` +(`{ "generators": [...] }`, written by `cargo meta init`) and no longer needs to eject to drop one; +`cargo meta gen --list` shows each as configured or not. `cargo meta eject` no longer writes the +path of the machine the tool was built on into `codegen/Cargo.toml`: the owned crate names the exact +crates.io release by default, and `--engine ` names a checkout or a git +revision. The three crates lose `publish = false`, carry their packaging metadata, and the `rust` lane +runs `cargo publish --dry-run`. Nothing is published. ## [1.3.0] — unreleased diff --git a/docs/ports/rust.md b/docs/ports/rust.md index a68f8ca742..65be0576d4 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -4,9 +4,11 @@ The Rust port is **in preview** ([ADR-0065](../../spec/decisions/ADR-0065-rust-i It reads a project, validates it, serializes it and generates code from it, and it is held to the same shared conformance corpora as the other five ports. Its command, `cargo meta`, runs the whole codegen loop on a JSON or YAML model: `init`, `gen`, `verify --codegen` and `eject`. Three generators -ship: `entity`, `client` and `commands`. **Nothing is published**: there is no crate on crates.io, so -there is nothing to `cargo add` or `cargo install` from a registry. You work from a checkout of this -repository. +ship: `entity`, `client` and `commands`, and a project chooses which of them run in +`metaobjects.config.json`. The three crates are **ready to publish but not published**: they package and +build from their packages (a `cargo publish --dry-run` runs in the `rust` lane), and there is no release +on crates.io yet, so there is nothing to `cargo add` or `cargo install` from a registry. You work from a +checkout of this repository until the first release. This page says what runs today, what does not exist yet, and how to build and test it. For the decisions behind the port (why Rust, the layout, the preview rules), read the ADR. @@ -47,7 +49,7 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log | Command | What it does | |---|---| -| `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed) and a first `metaobjects/meta.app.yaml`. It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | +| `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed), a first `metaobjects/meta.app.yaml` and `metaobjects.config.json`, the list of generators to run (see [Choosing generators](#choosing-generators)). It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | | `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` is the only gate the port ships, so a bare `verify` runs it. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | @@ -55,6 +57,24 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log `gen` and `verify` share `--project `, `--out ` (default `generated`), `--generators `, `--strict` and `--timings`. `gen` adds `--force` and `--list`. `cargo meta --help` is the reference. +### Choosing generators + +The generators a project runs are the list in `metaobjects.config.json` at the project root, the way the +other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, +`metaobjects.config.yaml`). `cargo meta init` writes every shipped generator; delete a line to stop +running one, and no eject is needed: + +```json +{ "generators": ["entity", "client", "commands"] } +``` + +The file takes that one key and no options: a layer is only a generator, so there are no layer settings. +A project with no such file runs every generator. A generator that leaves the list has its files removed +on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the +file, for a name nothing offers, a duplicate, an unknown key, or a generator listed without one it +builds on (`client` needs `entity`; `commands` needs both). `cargo meta gen --list` shows each generator +as `[configured]` or `[not configured]`, and `--generators` narrows one run to some of the list. + **Exit codes** are the ones every port's tool uses: 0 success, 1 the run failed (a model that does not load, a refused file, drift), 2 a usage error. An unknown flag names the flags the command takes. An owned generator crate that fails to build, or a generator in it that panics, is a failed run: 1, @@ -231,7 +251,13 @@ and tells you the two lines of `codegen/main.rs` to change; it never edits that This is **not a plugin contract**. Nothing discovers or loads a third-party generator, and the engine's Rust API carries no stability promise while the port is in preview: an owned copy is pinned -to the engine checkout its `Cargo.toml` points at. +to the exact engine its `Cargo.toml` names. + +The owned crate's `Cargo.toml` names no machine. By default the three engine crates are the crates.io +release the tool is, pinned exactly (`metaobjects = "="`), since an owned copy is that release's +source. Until a release exists, or to build against your own changes, eject with +`--engine `: a directory is a checkout's `server/rust` (relative to the project +root), and a git URL names a repository and an optional revision. ### Conformance @@ -295,14 +321,14 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to TypeScript; change the model or own the generator instead. - **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. - **Templates and prompts.** No render engine, no payload value objects and no output parser. -- **Publication.** The crate sets `publish = false`. There is no crates.io release, no version policy - beyond ADR-0065 (the port starts on its own `0.x` line when it publishes, and joins the lockstep - numbers only when it leaves preview), and `Cargo.toml` is not a stable interface. - -**A note on the name `cargo-meta`.** The crates.io name `cargo-meta` is held by an unrelated crate. The -plan is to publish the CLI crate under another name that installs a `cargo-meta` binary, so the command -you type is still `cargo meta`. That is a plan, not a promise: the crate name is not chosen, and -nothing is reserved. +- **Publication.** The crates are publishable and the lane proves they package (`cargo publish + --dry-run`), but nothing is published: there is no crates.io release yet, and publishing waits for + the owner's go ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) Amendment 3). + +**A note on the name `cargo-meta`.** The crates.io name `cargo-meta` is held by an unrelated crate, so the +CLI package is `metaobjects-cli` and installs a `cargo-meta` binary: the command you type is still +`cargo meta`. Nothing is reserved on crates.io; reserving a name is a publish, and waits for the +owner's go. The schema stays where it is for every port: migrations and database checks run in the Node `meta` tool ([ADR-0015](../../spec/decisions/ADR-0015-single-shared-migrate-engine.md); diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 22db44d6d2..2ecc689f30 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -838,7 +838,7 @@ gate_conf_python() { if [ "$NO_INTEG" -eq 1 ] || ! docker info >/dev/null 2>&1; then skip_integ=""; fi ( cd server/python && uv run --extra integration pytest tests/ $skip_integ -q -n "${MO_CI_PY_WORKERS:-8}" ) } -# The Rust port (preview, ADR-0065). The whole workspace suite, not a cherry-pick: the +# The Rust port (ADR-0065). The whole workspace suite, not a cherry-pick: the # registry-conformance and metamodel corpora, the unit tests, and the codegen tests (which run # `cargo check` on generated crates), a few seconds once built. --locked # so a stale Cargo.lock fails here instead of being rewritten. The build goes to the @@ -849,7 +849,15 @@ gate_conf_rust() { && cargo clippy --locked --all-targets -q -- -D warnings \ && cargo test --locked -q -- --nocapture \ && gate_rust_load_bench \ - && gate_rust_gen_bench ) + && gate_rust_gen_bench \ + && gate_rust_publish_dry_run ) +} +# The crates are publishable (ADR-0065 Amendment 3), so a change that would make `cargo publish` +# refuse them fails here, not on the day somebody publishes: package all three, build each +# from its packaged copy, and stop short of uploading. --allow-dirty because this checks the +# packaging, not the working tree; nothing is uploaded, ever, by this gate. +gate_rust_publish_dry_run() { + cargo publish --dry-run --workspace --locked --allow-dirty } # Load time per phase and per validation pass on the 20x fitness model. Record only: # it prints a table and never fails on a number, so a slowdown is read in the log and diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index a63b5acfb8..2be70283ca 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -1,5 +1,5 @@ -# The Rust port of MetaObjects (preview). ADR-0065 records why it exists and how it -# differs from the other five ports. +# The Rust port of MetaObjects. ADR-0065 records why it exists and how it differs from the +# other ports; its Amendment 3 records that it is a full, publishable language. # # Three crates: # `metaobjects` metamodel registry, loader, canonical serializer. @@ -16,6 +16,8 @@ edition = "2024" rust-version = "1.94" license = "Apache-2.0" repository = "https://github.com/metaobjectsdev/metaobjects" +homepage = "https://metaobjects.dev" +authors = ["MetaObjects contributors"] [workspace.dependencies] # `preserve_order` keeps object keys in document order, which the loader needs: diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index 4646cd99c5..c4d7b9a5ad 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -1,15 +1,19 @@ [package] name = "metaobjects-cli" -description = "The `cargo meta` command for MetaObjects on Rust (preview)." +description = "The `cargo meta` command for MetaObjects on Rust: init, gen, verify and eject." version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -# Not published yet. The crates.io name `cargo-meta` belongs to an unrelated crate, so this -# package is `metaobjects-cli` and only its binary is called `cargo-meta`; that binary name -# is what makes cargo's external-subcommand rule run it for `cargo meta ...`. -publish = false +homepage.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["metadata", "codegen", "cargo", "cli", "schema"] +categories = ["development-tools", "development-tools::cargo-plugins", "command-line-utilities"] +# The crates.io name `cargo-meta` belongs to an unrelated crate, so this package is +# `metaobjects-cli` and only its binary is called `cargo-meta`; that binary name is what makes +# cargo's external-subcommand rule run it for `cargo meta ...`. [lib] name = "metaobjects_cli" diff --git a/server/rust/metaobjects-cli/LICENSE b/server/rust/metaobjects-cli/LICENSE new file mode 100644 index 0000000000..387490ed86 --- /dev/null +++ b/server/rust/metaobjects-cli/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 MetaObjects Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/server/rust/metaobjects-cli/README.md b/server/rust/metaobjects-cli/README.md new file mode 100644 index 0000000000..595f1924a9 --- /dev/null +++ b/server/rust/metaobjects-cli/README.md @@ -0,0 +1,21 @@ +# metaobjects-cli + +`cargo meta`: MetaObjects for Rust. Install it and run it inside a project: + +```bash +cargo install metaobjects-cli +cargo meta init # scaffold a project and its generator list +cargo meta gen # generate the crates from the model +cargo meta verify # fail when the generated crates drift from the model +cargo meta eject # copy a generator into the project to own it +``` + +The package is `metaobjects-cli` because the crates.io name `cargo-meta` belongs to another +crate; the binary it installs is `cargo-meta`, so the command is still `cargo meta`. + +`metaobjects.config.json` lists the generators a project runs. Schema migrations are the Node +`meta` command's, for every server language. + +- Documentation: +- Source and the Rust port's page: (`docs/ports/rust.md`) +- License: Apache-2.0 diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4d949c3eea..a7945e762e 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -1,4 +1,4 @@ -//! The `cargo meta` command (preview). +//! The `cargo meta` command. //! //! Cargo runs `cargo-` for `cargo ` and passes `` as the first argument, so //! the binary accepts both `cargo-meta meta gen` (how cargo calls it) and `cargo-meta gen`. @@ -19,29 +19,31 @@ use std::path::{Path, PathBuf}; use metaobjects::collection::discover_collection_root; use metaobjects::timing::{LoadTimings, ms, render_table}; -use metaobjects_codegen::eject::{self, CopyState, EjectError}; +use metaobjects_codegen::eject::{self, CopyState, EjectError, EngineSource}; use metaobjects_codegen::engine::{ ChangeKind, OWNED_MANIFEST, Outcome, RunError, RunOptions, RunReport, VerifyReport, }; +use metaobjects_codegen::generator_list::{self, GENERATOR_LIST_FILE}; use metaobjects_codegen::{Generator, run, shipped_generators, verify}; /// The tool's name in messages. const TOOL: &str = "cargo meta"; const USAGE: &str = "\ -cargo meta: MetaObjects for Rust (preview) +cargo meta: MetaObjects for Rust USAGE: cargo meta init [--project ] cargo meta gen [OPTIONS] [ENTITY...] cargo meta verify [--codegen] [--full] [OPTIONS] - cargo meta eject ... [--force] + cargo meta eject ... [--force] [--engine ] cargo meta eject --undo [...] [--force] cargo meta eject --list COMMANDS: - init Scaffold a project: .metaobjects/config.json, a first metadata file and the - ignore rules for the generation state. Writes only what is missing. + init Scaffold a project: .metaobjects/config.json, a first metadata file, the + ignore rules for the generation state and metaobjects.config.json, the list of + generators to run. Writes only what is missing. gen Generate Rust crates from the project's model. Skips the whole run when the model, the project config and the generators are unchanged; writes only files whose bytes changed; removes a generated file nothing emits any more; refuses @@ -50,19 +52,23 @@ COMMANDS: without writing anything. Exits 1 on drift. eject Copy a shipped generator into codegen/generators/ to own and change. --undo takes back copies that are still identical to the shipped generator. + The owned crate builds against this release of the engine from crates.io; + --engine names a checkout or a git revision instead. OPTIONS (gen and verify): --project The project root (the directory holding .metaobjects/config.json). Default: the nearest one at or above the current directory. --out Where the crates are written, relative to the project root and a sub-directory of it. Default: generated - --generators Run only these generators (`cargo meta gen --list` names them). + --generators Run only these generators, from the project's list + (`cargo meta gen --list` shows both). --strict Load strictly: an attribute no provider declares is an error. --timings Print the time spent in each stage. OPTIONS (gen): --force Render and compare even when nothing changed. - --list List the generators, and how each owned copy compares. + --list List the generators: which the project's list runs, and how each + owned copy compares. OPTIONS (verify): --codegen The generated-code gate. It is the only gate this port ships, so a @@ -74,6 +80,9 @@ OPTIONS (everywhere): -h, --help Print this help. -V, --version Print the version. +GENERATORS: a project chooses what runs in metaobjects.config.json, `{ \"generators\": [..] }`, +by name. Edit the list; no eject is needed. With no such file every generator runs. + ENTITY names limit `gen` to the crates that contain them plus the crates those depend on. Such a run never skips, never stores the skip key and never removes a file. @@ -124,6 +133,7 @@ const VERIFY_FLAGS: &[Flag] = &[ switch("--timings"), ]; const EJECT_FLAGS: &[Flag] = &[ + valued("--engine"), switch("--force"), switch("--list"), valued("--project"), @@ -339,25 +349,84 @@ fn unchanged_copy_notice(project_root: &Path) -> Option { }) } -fn list_generators(out: &mut dyn Write, root: &Path, generators: &[Box]) { +/// `gen --list`: every generator, whether the project's list runs it, and how an owned copy +/// compares. Returns the exit status: 1 when the project's list cannot be used. +fn list_generators( + out: &mut dyn Write, + err: &mut dyn Write, + root: &Path, + generators: &[Box], +) -> i32 { + let listed = match generator_list::read(root) { + Ok(listed) => listed, + Err(e) => { + let _ = writeln!(err, "{TOOL}: {e}"); + return 1; + } + }; + let owns = eject::owns_generators(root); + let mut available: Vec<&str> = eject::REFERENCES.iter().map(|r| r.name).collect(); + for g in generators { + if !available.contains(&g.name()) { + available.push(g.name()); + } + } + let mut status = 0; + match &listed { + None => { + let _ = writeln!( + out, + "No {GENERATOR_LIST_FILE}: every generator runs. `{TOOL} init` writes one to choose from." + ); + } + Some(names) => { + let _ = writeln!( + out, + "{GENERATOR_LIST_FILE} runs: {}", + if names.is_empty() { + "nothing (the list is empty)".to_string() + } else { + names.join(", ") + } + ); + // An owned crate may carry generators this command cannot see without building it. + if !owns && let Err(e) = generator_list::check(names, &available) { + let _ = writeln!(err, "{TOOL}: {e}"); + status = 1; + } + } + } + let on = |name: &str| match &listed { + None => String::new(), + Some(names) if names.iter().any(|n| n == name) => " [configured]".to_string(), + Some(_) => " [not configured]".to_string(), + }; let copies = eject::owned_copies(root); for r in eject::REFERENCES { - let owned = copies.iter().find(|c| c.reference == r); - let state = match owned { + let state = match copies.iter().find(|c| c.reference == r) { Some(c) => format!(" [owned: {}]", c.state), None => String::new(), }; let _ = writeln!( out, - "{} - {} (layer: {}){state}", - r.name, r.summary, r.layer + "{} - {} (layer: {}){}{state}", + r.name, + r.summary, + r.layer, + on(r.name) ); } for g in generators { if eject::reference(g.name()).is_none() { - let _ = writeln!(out, "{} - a generator of this project", g.name()); + let _ = writeln!( + out, + "{} - a generator of this project{}", + g.name(), + on(g.name()) + ); } } + status } fn cmd_gen( @@ -369,8 +438,12 @@ fn cmd_gen( ) -> Result { let s = split(args, "gen", GEN_FLAGS)?; if s.has("--list") { - list_generators(out, &project_root(&s, cwd), generators); - return Ok(0); + return Ok(list_generators( + out, + err, + &project_root(&s, cwd), + generators, + )); } let mut options = run_options(&s, cwd, generators)?; options.force = s.has("--force"); @@ -503,20 +576,21 @@ fn cmd_verify( fn cmd_eject( args: &[String], cwd: &Path, - engine_root: &Path, out: &mut dyn Write, err: &mut dyn Write, ) -> Result { let s = split(args, "eject", EJECT_FLAGS)?; + let engine = s + .value("--engine") + .map_or_else(EngineSource::default, EngineSource::parse); let root = project_root(&s, cwd); if s.has("--list") { - list_generators(out, &root, &[]); - return Ok(0); + return Ok(list_generators(out, err, &root, &[])); } let result = if s.has("--undo") { eject::undo(&root, &s.words, s.has("--force")) } else { - eject::eject(&root, &s.words, s.has("--force"), engine_root) + eject::eject(&root, &s.words, s.has("--force"), &engine) }; match result { Ok(lines) => { @@ -534,20 +608,21 @@ fn cmd_eject( } /// What `init` writes when it is missing: a path from the project root and its text. -fn init_files() -> [(&'static str, &'static str); 3] { +fn init_files() -> [(&'static str, String); 4] { [ ( ".metaobjects/config.json", - "{\n \"schema_version\": 1,\n \"migrate\": {\n \"foreignKeyIndexes\": true\n },\n \"verify\": {\n \"handEdits\": \"fail\"\n },\n \"api\": {\n \"pagination\": {\n \"defaultLimit\": 50,\n \"maxLimit\": 1000\n },\n \"unknownFields\": \"reject\"\n }\n}\n", + "{\n \"schema_version\": 1,\n \"migrate\": {\n \"foreignKeyIndexes\": true\n },\n \"verify\": {\n \"handEdits\": \"fail\"\n },\n \"api\": {\n \"pagination\": {\n \"defaultLimit\": 50,\n \"maxLimit\": 1000\n },\n \"unknownFields\": \"reject\"\n }\n}\n".to_string(), ), ( ".metaobjects/.gitignore", - "# The generation state. `.hashes/` is committed: it is one hash per generated\n# path (one file per model package), and the only thing that lets `gen` tell \"this file is exactly what I wrote\" from\n# \"somebody edited this\" on a machine that did not generate it. Everything else here (the\n# skip key) describes one machine's last run and is not.\n#\n# The glob form matters: `.gen-state/` (a directory) would stop git descending, and the\n# negation below could never take effect.\n.gen-state/*\n!.gen-state/.hashes/\n", + "# The generation state. `.hashes/` is committed: it is one hash per generated\n# path (one file per model package), and the only thing that lets `gen` tell \"this file is exactly what I wrote\" from\n# \"somebody edited this\" on a machine that did not generate it. Everything else here (the\n# skip key) describes one machine's last run and is not.\n#\n# The glob form matters: `.gen-state/` (a directory) would stop git descending, and the\n# negation below could never take effect.\n.gen-state/*\n!.gen-state/.hashes/\n".to_string(), ), ( "metaobjects/meta.app.yaml", - "metadata:\n package: app\n children: []\n", + "metadata:\n package: app\n children: []\n".to_string(), ), + (GENERATOR_LIST_FILE, generator_list::scaffold()), ] } @@ -596,6 +671,7 @@ fn cmd_init( let _ = writeln!( out, "next: declare your objects in metaobjects/ (JSON or YAML), then run `{TOOL} gen`.\n\ + Choose the generators `gen` runs by editing {GENERATOR_LIST_FILE}.\n\ Commit .metaobjects/.gen-state/.hashes/ with the generated crates.\n\ Schema migrations are the Node `meta` command's (`meta migrate`), for every server language." ); @@ -603,9 +679,9 @@ fn cmd_init( } /// Who is running the command line. -enum Host<'a> { +enum Host { /// `cargo-meta` itself, with the shipped generators. - Shipped { engine_root: &'a Path }, + Shipped, /// A project's `codegen/` crate, with the generator list it declares. Owned, } @@ -652,7 +728,7 @@ fn dispatch( args: &[String], cwd: &Path, generators: &[Box], - host: &Host<'_>, + host: &Host, out: &mut dyn Write, err: &mut dyn Write, ) -> i32 { @@ -674,7 +750,7 @@ fn dispatch( return 0; } let result = match (command.as_str(), host) { - ("gen" | "verify", Host::Shipped { .. }) => { + ("gen" | "verify", Host::Shipped) => { // Owned generators are a build of the project's own crate. `--list` reads files // and needs no build. let flags = if command == "gen" { @@ -699,8 +775,8 @@ fn dispatch( } ("gen", Host::Owned) => cmd_gen(tail, cwd, generators, out, err), ("verify", Host::Owned) => cmd_verify(tail, cwd, generators, out, err), - ("init", Host::Shipped { .. }) => cmd_init(tail, cwd, out, err), - ("eject", Host::Shipped { engine_root }) => cmd_eject(tail, cwd, engine_root, out, err), + ("init", Host::Shipped) => cmd_init(tail, cwd, out, err), + ("eject", Host::Shipped) => cmd_eject(tail, cwd, out, err), ("init" | "eject", Host::Owned) => Err(Usage(format!( "`{command}` is not a command of a project's codegen crate; run `{TOOL} {command}`" ))), @@ -723,26 +799,7 @@ fn dispatch( /// Run the command line with the shipped generators. Returns the process exit status. pub fn main_with(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { - let engine_root = eject::default_engine_root(); - main_with_engine(args, cwd, &engine_root, out, err) -} - -/// [`main_with`], naming the engine checkout an ejected `codegen/Cargo.toml` points at. -pub fn main_with_engine( - args: &[String], - cwd: &Path, - engine_root: &Path, - out: &mut dyn Write, - err: &mut dyn Write, -) -> i32 { - dispatch( - args, - cwd, - &shipped_generators(), - &Host::Shipped { engine_root }, - out, - err, - ) + dispatch(args, cwd, &shipped_generators(), &Host::Shipped, out, err) } /// The command line of a project's `codegen/` crate: `gen` and `verify` over the generator diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index bb8e8815cd..f0465c248d 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -219,6 +219,7 @@ fn init_scaffolds_a_project_that_loads_and_never_overwrites() { ".metaobjects/config.json", ".metaobjects/.gitignore", "metaobjects/meta.app.yaml", + "metaobjects.config.json", ] { assert!(out.contains(&format!("wrote {rel}")), "{out}"); assert!(p.exists(rel)); @@ -247,6 +248,111 @@ fn init_scaffolds_a_project_that_loads_and_never_overwrites() { ); } +#[test] +fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_available() { + let p = Project::empty("init-list"); + ok(&p.run(&["meta", "init"])); + let list: serde_json::Value = serde_json::from_str(&p.read("metaobjects.config.json")).unwrap(); + assert_eq!( + list["generators"], + serde_json::json!(["entity", "client", "commands"]) + ); + let out = ok(&p.run(&["meta", "gen", "--list"])); + assert!( + out.contains("metaobjects.config.json runs: entity, client, commands"), + "{out}" + ); + assert_eq!(out.matches("[configured]").count(), 3, "{out}"); + // An edited list is never overwritten by a second init. + p.write( + "metaobjects.config.json", + "{ \"generators\": [\"entity\"] }", + ); + let out = ok(&p.run(&["meta", "init"])); + assert!( + out.contains("kept metaobjects.config.json (already exists)"), + "{out}" + ); + let out = ok(&p.run(&["meta", "gen", "--list"])); + assert!(out.contains("runs: entity\n"), "{out}"); + assert_eq!(out.matches("[not configured]").count(), 2, "{out}"); +} + +#[test] +fn the_generator_list_changes_what_runs_without_an_eject() { + let p = Project::new("list-narrows"); + ok(&p.run(&["meta", "gen"])); + let full = p.generated(); + assert!(full.keys().any(|k| k.contains("shop_client/")), "{full:?}"); + assert!(full.keys().any(|k| k.contains("shop_cli/")), "{full:?}"); + + // Leave `commands` out: its crates are swept, the rest is untouched. + p.write( + "metaobjects.config.json", + "{ \"generators\": [\"entity\", \"client\"] }", + ); + ok(&p.run(&["meta", "gen"])); + let narrowed = p.generated(); + assert!( + !narrowed.keys().any(|k| k.contains("shop_cli/")), + "{narrowed:?}" + ); + assert!(narrowed.keys().any(|k| k.contains("shop_client/"))); + ok(&p.run(&["meta", "verify", "--full"])); + assert!(!p.exists("codegen"), "no eject happened"); + + // `--generators` picks from the list, not past it. + let out = p.run(&["meta", "gen", "--generators", "commands"]); + assert_eq!(out.status.code(), Some(1)); + let err = text(&out.stderr); + assert!( + err.contains("commands is not in the \"generators\" list"), + "{err}" + ); + + // Put it back and the crates come back. + p.write( + "metaobjects.config.json", + "{ \"generators\": [\"entity\", \"client\", \"commands\"] }", + ); + ok(&p.run(&["meta", "gen"])); + assert_eq!(p.generated(), full); +} + +#[test] +fn a_generator_list_that_cannot_be_used_fails_by_name_and_writes_nothing() { + let p = Project::new("list-bad"); + for (list, wants) in [ + ( + "{ \"generators\": [\"nope\"] }", + "\"nope\", which is not available", + ), + ( + "{ \"generators\": [\"client\"] }", + "\"client\" without \"entity\"", + ), + ( + "{ \"generators\": [\"entity\"], \"layers\": [] }", + "unknown key \"layers\"", + ), + ("{ \"generators\": ", "not valid JSON"), + ] { + p.write("metaobjects.config.json", list); + for args in [ + vec!["meta", "gen"], + vec!["meta", "verify"], + vec!["meta", "gen", "--list"], + ] { + let out = p.run(&args); + assert_eq!(out.status.code(), Some(1), "{list} {args:?}"); + let err = text(&out.stderr); + assert!(err.contains(wants), "{list}: {err}"); + assert!(err.contains("metaobjects.config.json"), "{err}"); + } + assert!(!p.exists("generated"), "nothing written for {list}"); + } +} + #[test] fn init_does_not_add_an_empty_model_beside_one_that_exists() { let p = Project::new("init-existing"); @@ -390,6 +496,72 @@ fn gen_list_names_the_generators_and_how_an_owned_copy_compares() { ); } +/// The manifest `eject` writes names no machine: not the checkout the binary was built in, and +/// not the user's home. The default is the exact crates.io release; `--engine` is a choice. +#[test] +fn eject_writes_a_manifest_that_names_no_machine_and_takes_the_engine_by_flag() { + let built_in = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + let version = env!("CARGO_PKG_VERSION"); + + let p = Project::new("eject-engine-default"); + let out = ok(&p.run(&["meta", "eject", "entity"])); + let manifest = p.read("codegen/Cargo.toml"); + assert!(!manifest.contains(&built_in), "{manifest}"); + assert!(!out.contains(&built_in), "{out}"); + assert!( + !manifest + .lines() + .any(|l| !l.starts_with('#') && l.contains("{ path =")), + "{manifest}" + ); + for name in ["metaobjects", "metaobjects-cli", "metaobjects-codegen"] { + assert!( + manifest.contains(&format!("{name} = \"={version}\"")), + "{name}: {manifest}" + ); + } + assert!( + out.contains(&format!("the engine is crates.io, exactly {version}")), + "{out}" + ); + + // A checkout named relative to the project root is written relative to `codegen/`. + let p = Project::new("eject-engine-path"); + ok(&p.run(&[ + "meta", + "eject", + "entity", + "--engine", + "../checkout/server/rust", + ])); + let manifest = p.read("codegen/Cargo.toml"); + assert!( + manifest.contains("metaobjects = { path = \"../../checkout/server/rust/metaobjects\" }"), + "{manifest}" + ); + assert!(!manifest.contains(&built_in), "{manifest}"); + + // A git revision. + let p = Project::new("eject-engine-git"); + ok(&p.run(&[ + "meta", + "eject", + "entity", + "--engine=https://example.com/mo.git#abc123", + ])); + let manifest = p.read("codegen/Cargo.toml"); + assert!( + manifest.contains( + "metaobjects-codegen = { git = \"https://example.com/mo.git\", rev = \"abc123\" }" + ), + "{manifest}" + ); +} + #[test] fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identical_copies() { let p = Project::new("eject"); @@ -497,7 +669,9 @@ fn an_ejected_generator_builds_and_writes_what_the_shipped_one_writes() { // anything outside the engine, would not build here. let own = |name: &str| { let p = Project::new(&format!("owned-{name}")); - ok(&p.run(&["meta", "eject", name])); + // Nothing is on crates.io yet, so the scratch crate builds against this checkout. + let engine = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".."); + ok(&p.run(&["meta", "eject", name, "--engine", engine.to_str().unwrap()])); // The scratch crate resolves the versions the repository pins, without the network. std::fs::copy( PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../Cargo.lock"), diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml index bbaa36a98d..dfdc4ad635 100644 --- a/server/rust/metaobjects-codegen/Cargo.toml +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -1,13 +1,16 @@ [package] name = "metaobjects-codegen" -description = "MetaObjects code generation for Rust (preview): the run engine and the entity generator." +description = "MetaObjects code generation for Rust: the run engine and the entity, client and commands generators." version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -# Not published yet: the first crates.io release is a separate, approved step. -publish = false +homepage.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["metadata", "codegen", "code-generation", "schema", "rest"] +categories = ["development-tools", "development-tools::build-utils"] build = "build.rs" [dependencies] diff --git a/server/rust/metaobjects-codegen/LICENSE b/server/rust/metaobjects-codegen/LICENSE new file mode 100644 index 0000000000..387490ed86 --- /dev/null +++ b/server/rust/metaobjects-codegen/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 MetaObjects Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/server/rust/metaobjects-codegen/README.md b/server/rust/metaobjects-codegen/README.md new file mode 100644 index 0000000000..a4f5be08af --- /dev/null +++ b/server/rust/metaobjects-codegen/README.md @@ -0,0 +1,17 @@ +# metaobjects-codegen + +The code-generation engine of the MetaObjects Rust port, and its generators: `entity` (serde +structs, enums, value objects and request bodies, with `validate()`), `client` (a typed HTTP +client for the REST API the model implies) and `commands` (command-line commands over that +client). + +The engine decides whether anything changed, renders through the generators, writes only the +files whose bytes changed, and refuses to overwrite a generated file somebody edited. The +generated code imports ordinary crates.io crates and nothing from MetaObjects. + +You normally run it through `cargo meta` (`metaobjects-cli`). A project that wants to own a +generator copies it with `cargo meta eject`, and that copy builds against this crate. + +- Documentation: +- Source and the Rust port's page: (`docs/ports/rust.md`) +- License: Apache-2.0 diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index a8fc59ff50..47a6fc8b29 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -17,8 +17,8 @@ //! `crate::`, which is what lets one text compile in both places. //! //! This is not a plugin contract. Nothing discovers or loads a third-party generator, and -//! the engine's Rust API carries no stability promise while the port is in preview: an owned -//! copy is pinned to the engine checkout its `Cargo.toml` points at. +//! the engine's Rust API carries no stability promise between releases: an owned copy is +//! pinned to the exact engine its `Cargo.toml` names (see [`EngineSource`]). //! //! Nothing is recorded about an eject. What a project owns is what is on disk under //! `codegen/generators/`, and "identical" is decided by comparing a copy with the shipped @@ -43,6 +43,8 @@ pub struct Reference { pub tier: &'static str, /// The layer an adopter selects it by, in the shared generator registry's words. pub layer: &'static str, + /// The shipped generators it builds on: a project's generator list names them too. + pub needs: &'static [&'static str], /// One line for `gen --list`. pub summary: &'static str, /// The shipped source, which is also the owned copy's text. @@ -74,6 +76,7 @@ pub const REFERENCES: &[Reference] = &[ layer: "model", module: "entity", type_name: "EntityGenerator", + needs: &[], summary: "model crates, one per metadata package: serde structs, enums, value \ objects, create and patch inputs, validate()", source: include_str!("entity.rs"), @@ -84,6 +87,7 @@ pub const REFERENCES: &[Reference] = &[ layer: "client", module: "client", type_name: "ClientGenerator", + needs: &["entity"], summary: "client crates, one per package with served entities: a typed HTTP \ client and list query per entity (needs entity)", source: include_str!("client.rs"), @@ -94,6 +98,7 @@ pub const REFERENCES: &[Reference] = &[ layer: "client", module: "commands", type_name: "CommandsGenerator", + needs: &["entity", "client"], summary: "command crates, one per package with served entities: clap commands \ over the client (needs entity and client; Rust only)", source: include_str!("commands.rs"), @@ -255,16 +260,114 @@ fn resolve(names: &[String]) -> Result, EjectError> { Ok(out) } +/// Where an owned generator crate gets the engine it builds against: the three crates +/// `metaobjects`, `metaobjects-codegen` and `metaobjects-cli`. +/// +/// The default names no machine. An owned copy is the engine's own source, so it is pinned to +/// the exact engine release it was ejected from; a checkout or a git revision is a choice the +/// project makes out loud with `--engine`, and what it writes is that choice, never the path +/// the running binary was built in. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum EngineSource { + /// The crates.io release this tool is (`=`). + #[default] + Registry, + /// A checkout's `server/rust` directory, as the project named it. A relative path is + /// relative to the project root. + Path(PathBuf), + /// A git repository, and the revision to build (a branch, tag or commit), if any. + Git { url: String, rev: Option }, +} + +impl EngineSource { + /// What `--engine` was given: a URL (`https://...`, `ssh://...`, `git@host:...`), with an + /// optional `#`, names a git repository; anything else is a directory. + pub fn parse(spec: &str) -> Self { + if spec.contains("://") || spec.starts_with("git@") { + let (url, rev) = match spec.split_once('#') { + Some((url, rev)) if !rev.is_empty() => (url, Some(rev.to_string())), + Some((url, _)) => (url, None), + None => (spec, None), + }; + EngineSource::Git { + url: url.to_string(), + rev, + } + } else { + EngineSource::Path(PathBuf::from(spec)) + } + } + + /// One phrase for the message `eject` prints. + pub fn describe(&self) -> String { + match self { + EngineSource::Registry => { + format!("crates.io, exactly {}", env!("CARGO_PKG_VERSION")) + } + EngineSource::Path(p) => format!("the checkout at {}", p.display()), + EngineSource::Git { url, rev: Some(r) } => format!("{url} at {r}"), + EngineSource::Git { url, rev: None } => url.clone(), + } + } + + /// The dependency line for one engine crate, as written in `codegen/Cargo.toml`. + fn dependency(&self, name: &str) -> String { + match self { + EngineSource::Registry => format!("{name} = \"={}\"", env!("CARGO_PKG_VERSION")), + EngineSource::Path(root) => { + // `codegen/Cargo.toml` sits one directory below the project root. + let base = if root.is_absolute() { + root.clone() + } else { + Path::new("..").join(root) + }; + format!("{name} = {{ path = {} }}", toml_string(&base.join(name))) + } + EngineSource::Git { url, rev } => match rev { + Some(r) => format!( + "{name} = {{ git = {}, rev = {} }}", + toml_str(url), + toml_str(r) + ), + None => format!("{name} = {{ git = {} }}", toml_str(url)), + }, + } + } + + fn note(&self) -> &'static str { + match self { + EngineSource::Registry => { + "# The engine is the crates.io release this project ejected from, pinned exactly: an\n\ + # owned copy is that release's source. Upgrade the three versions together, then\n\ + # compare each copy with `cargo meta gen --list`. To build against a checkout or a\n\ + # git revision instead, replace each line with `{ path = \"...\" }` or\n\ + # `{ git = \"...\", rev = \"...\" }`, or eject with `--engine`.\n" + } + EngineSource::Path(_) => { + "# The engine is a checkout of the repository's `server/rust`. Change the three paths\n\ + # if it moves, or point them at a git revision or a crates.io release.\n" + } + EngineSource::Git { .. } => { + "# The engine is a git revision of the repository. Change the three entries to move to\n\ + # another revision, a checkout (`path`) or a crates.io release.\n" + } + } + } +} + +/// A string as a TOML basic string. +fn toml_str(text: &str) -> String { + format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\"")) +} + /// A path as a TOML basic string. fn toml_string(path: &Path) -> String { let text = path.to_string_lossy().replace('\\', "/"); - format!("\"{}\"", text.replace('"', "\\\"")) + toml_str(&text) } -/// The owned crate's manifest. `engine_root` is the directory holding the three engine -/// crates (a checkout's `server/rust`): nothing is published while the port is in preview. -pub fn scaffold_manifest(engine_root: &Path) -> String { - let dep = |name: &str| toml_string(&engine_root.join(name)); +/// The owned crate's manifest, with the engine from `engine`. +pub fn scaffold_manifest(engine: &EngineSource) -> String { format!( "# The generators this project owns (`cargo meta eject`). This crate is yours.\n\ # `cargo meta gen` and `cargo meta verify` build and run it while it exists.\n\ @@ -278,13 +381,11 @@ pub fn scaffold_manifest(engine_root: &Path) -> String { name = \"codegen\"\n\ path = \"main.rs\"\n\ \n\ - # The Rust port is in preview and nothing is published, so the engine is a path into\n\ - # a checkout. Change these three paths if that checkout moves, or point them at a git\n\ - # revision.\n\ + {}\ [dependencies]\n\ - metaobjects = {{ path = {} }}\n\ - metaobjects-cli = {{ path = {} }}\n\ - metaobjects-codegen = {{ path = {} }}\n\ + {}\n\ + {}\n\ + {}\n\ # What the shipped generators themselves import. Add your own beside it.\n\ serde_json = {{ version = \"1\", features = [\"preserve_order\"] }}\n\ \n\ @@ -295,9 +396,10 @@ pub fn scaffold_manifest(engine_root: &Path) -> String { \n\ # Its own workspace, so an enclosing one neither claims nor rejects it.\n\ [workspace]\n", - dep("metaobjects"), - dep("metaobjects-cli"), - dep("metaobjects-codegen"), + engine.note(), + engine.dependency("metaobjects"), + engine.dependency("metaobjects-cli"), + engine.dependency("metaobjects-codegen"), ) } @@ -346,7 +448,7 @@ pub fn eject( project_root: &Path, names: &[String], force: bool, - engine_root: &Path, + engine: &EngineSource, ) -> Result, EjectError> { if names.is_empty() { return Err(EjectError::Usage( @@ -384,10 +486,10 @@ pub fn eject( if manifest.exists() { lines.push(format!(" kept {OWNED_MANIFEST} (already yours)")); } else { - write_new(&manifest, &scaffold_manifest(engine_root))?; + write_new(&manifest, &scaffold_manifest(engine))?; lines.push(format!( - " wrote {OWNED_MANIFEST} (the engine is the checkout at {})", - engine_root.display() + " wrote {OWNED_MANIFEST} (the engine is {})", + engine.describe() )); } let main = project_root.join(OWNED_MAIN); @@ -514,12 +616,3 @@ pub fn undo(project_root: &Path, names: &[String], force: bool) -> Result PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .map(Path::to_path_buf) - .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR"))) -} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 40358c613a..d20c038d71 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -32,6 +32,7 @@ use crate::fingerprint::{ use crate::generator::{ ERR_OUT_DIR, ERR_PATH_COLLISION, EmittedFile, GenContext, GenError, Generator, }; +use crate::generator_list; use crate::hashes::{HASHES_DIR, HashManifest, content_hash}; use crate::project::{LoadedProject, load_project}; use crate::sha256::sha256_hex; @@ -199,6 +200,8 @@ pub enum RunError { /// Existing files are not what a previous run left (hand-edited, or unrecorded), so /// they were left alone. The rest of the run completed, and no skip key was stored. Refused(Refusal), + /// The project's generator list (`metaobjects.config.json`) is wrong. + GeneratorList(String), /// A file could not be read or written. Io(String), } @@ -242,7 +245,7 @@ impl std::fmt::Display for RunError { } Ok(()) } - RunError::Io(m) => write!(f, "{m}"), + RunError::GeneratorList(m) | RunError::Io(m) => write!(f, "{m}"), } } } @@ -359,14 +362,36 @@ fn prepare<'g>( // plan let start = Instant::now(); - let selected: Vec<&dyn Generator> = match &opts.generators { - None => generators.iter().map(AsRef::as_ref).collect(), - Some(names) => generators - .iter() - .map(AsRef::as_ref) - .filter(|g| names.iter().any(|n| n == g.name())) - .collect(), - }; + // The project's own list narrows what the host offers; `--generators` narrows it again, + // but only within the list, so a flag never runs what the project left out. + let listed = generator_list::read(&project_root).map_err(RunError::GeneratorList)?; + if let Some(names) = &listed { + let available: Vec<&str> = generators.iter().map(|g| g.name()).collect(); + generator_list::check(names, &available).map_err(RunError::GeneratorList)?; + } + if let (Some(listed), Some(flagged)) = (&listed, &opts.generators) + && let Some(out) = flagged.iter().find(|n| !listed.contains(n)) + { + return Err(RunError::GeneratorList(format!( + "the generator {out} is not in the \"generators\" list of {}; the project runs: {}", + generator_list::GENERATOR_LIST_FILE, + listed.join(", ") + ))); + } + let selected: Vec<&dyn Generator> = generators + .iter() + .map(AsRef::as_ref) + .filter(|g| { + listed + .as_ref() + .is_none_or(|l| l.iter().any(|n| n == g.name())) + }) + .filter(|g| { + opts.generators + .as_ref() + .is_none_or(|names| names.iter().any(|n| n == g.name())) + }) + .collect(); let out_dir = normalize(&if opts.out_dir.is_absolute() { opts.out_dir.clone() } else { diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs new file mode 100644 index 0000000000..1bfe090efa --- /dev/null +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -0,0 +1,195 @@ +//! The project's generator list: which generators `cargo meta gen` and `verify` run. +//! +//! A project chooses its generators in `metaobjects.config.json` at the project root, the way +//! `metaobjects.config.ts`, `codegen/Generators.cs`, the pom and `metaobjects.config.yaml` do in +//! the other ports, so changing the list never needs an eject: +//! +//! ```json +//! { "generators": ["entity", "client", "commands"] } +//! ``` +//! +//! The list names generators; it takes no options and carries no layer or set settings, because +//! a layer is only a generator. A project with no such file runs every generator its host +//! offers, which is what a project did before the file existed. A list may leave a generator +//! out; generated files of a generator that left the list are swept like those of any +//! generator that stops emitting them (an edited one is refused by name). +//! +//! The file is the tool's own, not the shared `.metaobjects/config.json`: that file's keys are +//! one contract across six ports, and a generator list is each port's own way of choosing. + +use std::path::Path; + +use crate::eject; + +/// The file that holds the list, from the project root. +pub const GENERATOR_LIST_FILE: &str = "metaobjects.config.json"; + +/// The one key the file takes. +const KEY: &str = "generators"; + +/// The list the project wrote, in the order it wrote it, or `None` when the project has no +/// such file. Anything wrong with the file is an error naming the file and what to change. +pub fn read(project_root: &Path) -> Result>, String> { + let path = project_root.join(GENERATOR_LIST_FILE); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("reading {GENERATOR_LIST_FILE}: {e}")), + }; + parse(&text).map(Some) +} + +/// The list in `text`, the contents of [`GENERATOR_LIST_FILE`]. +pub fn parse(text: &str) -> Result, String> { + let value: serde_json::Value = serde_json::from_str(text) + .map_err(|e| format!("{GENERATOR_LIST_FILE} is not valid JSON: {e}"))?; + let Some(object) = value.as_object() else { + return Err(format!( + "{GENERATOR_LIST_FILE} must be an object with a \"{KEY}\" list, as written by `cargo meta init`" + )); + }; + if let Some(unknown) = object.keys().find(|k| k.as_str() != KEY) { + return Err(format!( + "{GENERATOR_LIST_FILE} has an unknown key \"{unknown}\". The only key is \"{KEY}\": \ + the generators to run, by name. Generators take no options here, and a layer is just a generator" + )); + } + let Some(list) = object.get(KEY).and_then(|v| v.as_array()) else { + return Err(format!( + "{GENERATOR_LIST_FILE} needs a \"{KEY}\" list of generator names, \ + for example {}", + example() + )); + }; + let mut names: Vec = Vec::with_capacity(list.len()); + for item in list { + let Some(name) = item.as_str() else { + return Err(format!( + "{GENERATOR_LIST_FILE}: every entry of \"{KEY}\" is a generator name (a string), got {item}" + )); + }; + if names.iter().any(|n| n == name) { + return Err(format!( + "{GENERATOR_LIST_FILE}: \"{name}\" is listed twice; a generator runs once" + )); + } + names.push(name.to_string()); + } + Ok(names) +} + +/// Check a list against the generators a host offers: each name is one of them, and a shipped +/// generator that builds on another has it in the list too. +pub fn check(names: &[String], available: &[&str]) -> Result<(), String> { + if let Some(bad) = names.iter().find(|n| !available.contains(&n.as_str())) { + return Err(format!( + "{GENERATOR_LIST_FILE} lists the generator \"{bad}\", which is not available; \ + available: {}. (`cargo meta gen --list` shows them)", + available.join(", ") + )); + } + for name in names { + let Some(shipped) = eject::reference(name) else { + continue; + }; + if let Some(missing) = shipped + .needs + .iter() + .find(|n| !names.iter().any(|x| x == **n)) + { + return Err(format!( + "{GENERATOR_LIST_FILE} lists \"{name}\" without \"{missing}\", which it builds on; \ + add \"{missing}\" to \"{KEY}\" or take \"{name}\" out" + )); + } + } + Ok(()) +} + +/// Every shipped generator's name, in the order a run applies them: the list `cargo meta init` +/// writes. +pub fn shipped_names() -> Vec<&'static str> { + eject::REFERENCES.iter().map(|r| r.name).collect() +} + +fn example() -> String { + format!( + "{{ \"{KEY}\": [{}] }}", + shipped_names() + .iter() + .map(|n| format!("\"{n}\"")) + .collect::>() + .join(", ") + ) +} + +/// The text `cargo meta init` writes: every shipped generator, so a new project generates what +/// it always has and removes one by deleting a line. +pub fn scaffold() -> String { + let items = shipped_names() + .iter() + .map(|n| format!(" \"{n}\"")) + .collect::>() + .join(",\n"); + format!("{{\n \"{KEY}\": [\n{items}\n ]\n}}\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(list: &[&str]) -> Vec { + list.iter().map(ToString::to_string).collect() + } + + #[test] + fn the_scaffold_parses_and_names_every_shipped_generator_in_run_order() { + assert_eq!( + parse(&scaffold()).unwrap(), + s(&["entity", "client", "commands"]) + ); + assert!(check(&parse(&scaffold()).unwrap(), &shipped_names()).is_ok()); + } + + #[test] + fn a_file_that_is_not_a_list_of_names_is_refused_with_what_to_change() { + for (text, wants) in [ + ("{", "not valid JSON"), + ("[]", "must be an object"), + ("{}", "needs a \"generators\" list"), + ( + "{\"generators\": \"entity\"}", + "needs a \"generators\" list", + ), + ("{\"generators\": [1]}", "generator name (a string)"), + ("{\"generators\": [\"entity\", \"entity\"]}", "listed twice"), + ( + "{\"generators\": [], \"layers\": {}}", + "unknown key \"layers\"", + ), + ] { + let e = parse(text).unwrap_err(); + assert!(e.contains(wants), "{text}: {e}"); + assert!(e.contains(GENERATOR_LIST_FILE), "{e}"); + } + assert_eq!(parse("{\"generators\": []}").unwrap(), Vec::::new()); + } + + #[test] + fn a_name_nothing_offers_and_a_missing_dependency_are_refused() { + let available = shipped_names(); + let e = check(&s(&["entity", "nope"]), &available).unwrap_err(); + assert!( + e.contains("\"nope\"") && e.contains("available: entity, client, commands"), + "{e}" + ); + let e = check(&s(&["client"]), &available).unwrap_err(); + assert!(e.contains("\"client\" without \"entity\""), "{e}"); + let e = check(&s(&["entity", "commands"]), &available).unwrap_err(); + assert!(e.contains("\"commands\" without \"client\""), "{e}"); + assert!(check(&s(&["entity", "client"]), &available).is_ok()); + assert!(check(&s(&["entity"]), &available).is_ok()); + // A project's own generator has no declared dependencies. + assert!(check(&s(&["mine"]), &["mine"]).is_ok()); + } +} diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 130da0e5a6..9e37d4902e 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -1,4 +1,4 @@ -//! MetaObjects code generation for Rust (preview). +//! MetaObjects code generation for Rust. //! //! The run engine ([`engine`]) loads a project, decides whether anything changed //! ([`fingerprint`], ADR-0064), renders through [`generator::Generator`]s, and writes only the @@ -21,6 +21,7 @@ pub mod engine; pub mod entity; pub mod fingerprint; pub mod generator; +pub mod generator_list; pub mod hashes; pub mod names; pub mod plan; diff --git a/server/rust/metaobjects/Cargo.toml b/server/rust/metaobjects/Cargo.toml index 924c916d9f..5d3a79cac2 100644 --- a/server/rust/metaobjects/Cargo.toml +++ b/server/rust/metaobjects/Cargo.toml @@ -1,13 +1,16 @@ [package] name = "metaobjects" -description = "MetaObjects metamodel registry, loader and canonical serializer for Rust (preview)." +description = "MetaObjects metamodel registry, loader and canonical serializer for Rust." version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -# Not published yet: the first crates.io release is a separate, approved step. -publish = false +homepage.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["metadata", "metamodel", "codegen", "schema", "yaml"] +categories = ["development-tools", "parser-implementations"] [dependencies] serde_json.workspace = true diff --git a/server/rust/metaobjects/LICENSE b/server/rust/metaobjects/LICENSE new file mode 100644 index 0000000000..387490ed86 --- /dev/null +++ b/server/rust/metaobjects/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 MetaObjects Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/server/rust/metaobjects/README.md b/server/rust/metaobjects/README.md new file mode 100644 index 0000000000..0b7ce3c959 --- /dev/null +++ b/server/rust/metaobjects/README.md @@ -0,0 +1,14 @@ +# metaobjects + +The MetaObjects metamodel for Rust: the registry, the loader (JSON and YAML), the validation +passes, and the canonical serializer. It is the Rust port of the cross-language MetaObjects +standard, held to the same shared conformance corpora as the TypeScript, C#, Java, Kotlin and +Python ports. + +Most projects do not depend on this crate directly: they install the `cargo meta` command +(`metaobjects-cli`) and run its generators. Depend on `metaobjects` to read a project's model +from your own tool. + +- Documentation: +- Source and the Rust port's page: (`docs/ports/rust.md`) +- License: Apache-2.0 diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index c6834e6302..093ac7be36 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -1,4 +1,4 @@ -//! MetaObjects for Rust (preview). +//! MetaObjects for Rust. //! //! The metamodel registry, the JSON and YAML loader, project and source //! resolution (the `.metaobjects/config.json` reader, the library sources), diff --git a/server/rust/metaobjects/tests/vendored_data_parity.rs b/server/rust/metaobjects/tests/vendored_data_parity.rs index f8a34e7b3d..56abc87d35 100644 --- a/server/rust/metaobjects/tests/vendored_data_parity.rs +++ b/server/rust/metaobjects/tests/vendored_data_parity.rs @@ -46,6 +46,13 @@ fn vendored_copies_match_their_sources() { if !root.join("spec/metamodel").is_dir() { return; } + // Each crate carries the licence text it is published with. + for crate_dir in ["metaobjects", "metaobjects-codegen", "metaobjects-cli"] { + same( + &krate.join("..").join(crate_dir).join("LICENSE"), + &root.join("LICENSE"), + ); + } let data = krate.join("data"); same( &data.join("ERROR-CODES.json"), diff --git a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md index c0469c3d03..c96b4d8c6c 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -6,7 +6,9 @@ language port under `server/rust/`, in preview, and a `rust` CI lane. Amends nothing. **Amendment 1** (2026-11-19) records the command line, the shape of the generated crates and the `client` and `commands` generators. **Amendment 2** (2026-11-20) records the vendored copies of -repository data the crate builds from. +repository data the crate builds from. **Amendment 3** (2026-11-20) makes the crates publishable, +puts the generator list in the project's hands, and stops `eject` writing a machine's path; +it supersedes Decision 4 and Owner ruling 3. ## Context @@ -39,11 +41,11 @@ five". other build-tool-hosted ports spell theirs (`dotnet meta`, `mvn metaobjects:...`). A bare `meta` stays the Node schema CLI's. -4. **Preview, on a 0.x line, unpublished.** The crates are `publish = false` and nothing goes to - crates.io until the port leaves preview. When it publishes, it starts on its own `0.x` line - rather than joining the lockstep npm/Maven/PyPI/NuGet numbers, the way the source-only Angular - packages keep their own line (ADR-0048). It joins the convergent-publishing rule - (ADR-0035 Amendment 1) when it leaves preview. +4. **Publishable crates on the shared version line.** *(Rewritten by Amendment 3; the first + version of this decision kept the port unpublished, on its own `0.x` line.)* The three crates + carry the packaging metadata crates.io needs, and the lane proves they package. Publishing is a + separate step that waits for the owner's go, and joins the convergent-publishing rule + (ADR-0035 Amendment 1) as a fifth registry on the version line the other four share. 5. **Conformance is the definition of done, and gaps are ledgered, not hidden.** The metamodel runner keeps an expected-failures ledger in the format the other ports use. A fixture on the @@ -133,8 +135,9 @@ so they are not re-derived. 2. **No generator plugin contract for now.** Nothing discovers or loads a third-party generator. A project changes generation by owning a copy (ruling 5), and the engine's Rust API carries no stability promise while the port is in preview. -3. **Rust stays preview and unpublished.** Decision 4 stands unchanged. `cargo meta` is installed - from a checkout (`cargo install --path`). +3. **Rust stays unpublished until the owner says go.** *(Superseded by Amendment 3: the crates are + publishable, and nothing is published without that go.)* Until the first release, + `cargo meta` is installed from a checkout (`cargo install --path`). **The command line.** @@ -176,8 +179,8 @@ so they are not re-derived. - *One crate per package with Cargo features for the client and the commands.* A crate is one compilation unit: a model change would rebuild the client and the commands with it, and a consumer of the model alone would carry `reqwest` and `clap` in its lockfile. - - *A published MetaObjects support crate.* Nothing is published (ruling 3), and generated model - code that imports MetaObjects would break the promise the other ports' entity tier keeps. + - *A published MetaObjects support crate.* Generated model code that imports MetaObjects would + break the promise the other ports' entity tier keeps, published or not. - *The support code copied into every model crate*, which is what the first slice did. Two crates would then each have their own `Decimal`, so a value could not cross a package boundary without a conversion. @@ -255,3 +258,37 @@ cp spec/metamodel/.json server/rust/metaobjects/data/metamodel/ cp fixtures/conformance/ERROR-CODES.json server/rust/metaobjects/data/ rsync -a --delete library/ server/rust/metaobjects/data/library/ ``` + +### Amendment 3 (2026-11-20) — publishable crates, the project's generator list, and the owned crate's engine + +Rust is a full language in 1.3.0, so the preview-era decisions that kept it unpublished and its +generator list fixed are replaced. Three things change. + +1. **The crates are publishable.** `publish = false` is removed from `metaobjects`, + `metaobjects-codegen` and `metaobjects-cli`, and each carries a description, a README, the + licence text, keywords, categories, a homepage and authors. Decision 4 and Owner ruling 3 are + rewritten to say so. The `rust` lane runs `cargo publish --dry-run --workspace` (the + `gate_rust_publish_dry_run` step of `scripts/ci-local.sh`): it packages all three crates and + builds each from its package, so a change that would make publishing refuse them fails in + review. **Nothing is published.** Publishing, reserving a crate name and the renumbering of + the workspace onto the shared 1.3.0 line each wait for the owner's go; the one crates.io name + problem is unchanged (`cargo-meta` belongs to another crate, so the CLI package is + `metaobjects-cli` and its binary is `cargo-meta`). +2. **The project chooses its generators in `metaobjects.config.json`** at the project root, + `{ "generators": ["entity", "client", "commands"] }`, the way the other ports choose theirs + (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, `metaobjects.config.yaml`). Changing + the list needs no eject. `cargo meta init` writes it with every shipped generator, and + `gen --list` shows each generator as configured or not. The file takes one key and no options: + a layer is only a generator, so there are no layer settings. A name nothing offers, a duplicate, + an unknown key, or a shipped generator listed without one it builds on (`client` without + `entity`) is a failed run that names the file. A generator that leaves the list has its files + swept like any generator that stops emitting them, and an edited one is refused by name. + `--generators` still narrows a single run, but only within the list. A project with no such file + runs every generator, as before. The file is the tool's own and not a key of the shared + `.metaobjects/config.json`, whose keys are one contract across six ports. +3. **`eject` writes no machine's path.** The owned crate's `Cargo.toml` used to point at the + checkout the running binary was built in, which is a path on the build machine. It now names + the exact crates.io release (`metaobjects = "="`, because an owned copy is that + release's own source), and `--engine ` names a checkout or a git + revision when a project builds against one before a release exists. A relative directory is + relative to the project root. From d1dd48efd44162f23fa024f71e39b5ad846361e7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 20:40:32 -0500 Subject: [PATCH 2/6] feat(rust): cargo meta verify runs the business-rules gate (ADR-0066), held to rules-check-conformance --- CHANGELOG.md | 4 +- docs/CONFORMANCE.md | 4 +- docs/ports/rust.md | 9 +- server/rust/metaobjects-cli/src/lib.rs | 39 +- server/rust/metaobjects-cli/tests/cli.rs | 56 ++ server/rust/metaobjects-codegen/src/engine.rs | 26 + server/rust/metaobjects/src/config.rs | 5 +- server/rust/metaobjects/src/lib.rs | 1 + server/rust/metaobjects/src/rules_check.rs | 625 ++++++++++++++++++ server/rust/metaobjects/src/validate/mod.rs | 18 + server/rust/metaobjects/src/validate/rules.rs | 56 +- .../tests/rules_check_conformance.rs | 138 ++++ 12 files changed, 947 insertions(+), 34 deletions(-) create mode 100644 server/rust/metaobjects/src/rules_check.rs create mode 100644 server/rust/metaobjects/tests/rules_check_conformance.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index db1f44666c..fb6819d98f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,9 @@ here.** path of the machine the tool was built on into `codegen/Cargo.toml`: the owned crate names the exact crates.io release by default, and `--engine ` names a checkout or a git revision. The three crates lose `publish = false`, carry their packaging metadata, and the `rust` lane -runs `cargo publish --dry-run`. Nothing is published. +runs `cargo publish --dry-run`. Nothing is published. `cargo meta verify` now runs the business-rules +gate (ADR-0066) too: the same five findings, severities and message text as the other ports, under the +four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/rules-check-conformance/`. ## [1.3.0] — unreleased diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 48cc7f7811..ef04a89586 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -74,6 +74,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 578 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; +`rules-check-conformance` (all 16 cases, the `verify` business-rules gate); `yaml-conformance`, 18 of 19 (the one on `yaml-conformance-expected-failures.json`, `yaml-ref-root-escape`, waits for the ADR-0059 root-level `::` reference rules, which are reference resolution, not a validation pass); `source-resolution-conformance` (all 28 @@ -786,7 +787,8 @@ transition. The expectations are written from the TypeScript reference `server/typescript/packages/cli/test/rules-check-conformance.test.ts`, `server/csharp/MetaObjects.Conformance.Tests/RulesCheckConformanceTests.cs`, `server/java/metadata/src/test/java/com/metaobjects/conformance/RulesCheckConformanceTest.java` -and `server/python/tests/conformance/test_rules_check_conformance.py`. Kotlin inherits the Java +and `server/python/tests/conformance/test_rules_check_conformance.py` and +`server/rust/metaobjects/tests/rules_check_conformance.rs`. Kotlin inherits the Java gate through the shared Maven goal. ### `fixtures/cube-model/` (46 cases) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 65be0576d4..135035ae1c 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -51,7 +51,7 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log |---|---| | `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed), a first `metaobjects/meta.app.yaml` and `metaobjects.config.json`, the list of generators to run (see [Choosing generators](#choosing-generators)). It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | -| `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` is the only gate the port ships, so a bare `verify` runs it. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | +| `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | `gen` and `verify` share `--project `, `--out ` (default `generated`), `--generators `, @@ -275,6 +275,7 @@ outright. | `source-resolution-conformance` | all 28 cases | | `naming-conformance` | all of it | | `codegen-skip-conformance` | every case the port can meet, on both columns (what `gen` must do and what a local `verify --codegen` may do), including an edited owned generator and a forced CI verify ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). The three it cannot meet (two about templates, one about the three-way merge) are named with their reason in the runner. | +| `rules-check-conformance` | all 16 cases: the diagnostics (severity, code, node address, message text) and the summary of the `verify` business-rules gate, under each case's `rules` and `verify` settings | | `validation-conformance` | every case, through the generated `validate()`: each payload is read into the generated create body by a probe the real compiler builds | | `decimal-wire`, `duration-wire` | every vector, against the code the support crate carries | | `writer-conformance` | every `core` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)) | @@ -313,10 +314,8 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to - **Other generators.** There is no server-side route, ORM or repository generator, no template generator and no documentation generator. Projections and reports get no client yet. -- **Other gates.** `verify --codegen` is the only one. There is no template gate, no requirement gate - and no `fmt`. That includes the business-rules checks `verify` runs in the other ports (an unreachable state, a - permission name left to derive): the loader refuses a broken operation or lifecycle, and the port reads - and validates the `rules` and `verify.lifecycle` settings, but nothing reports on them. +- **Other gates.** `verify --codegen` and the business-rules gate are the ones it has. There is no + template gate, no requirement gate and no `fmt`. - **A three-way merge.** A hand-edited generated file is refused by name, as in every port but TypeScript; change the model or own the generator instead. - **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index a7945e762e..64bf4e286f 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -18,6 +18,7 @@ use std::io::Write; use std::path::{Path, PathBuf}; use metaobjects::collection::discover_collection_root; +use metaobjects::rules_check::Severity; use metaobjects::timing::{LoadTimings, ms, render_table}; use metaobjects_codegen::eject::{self, CopyState, EjectError, EngineSource}; use metaobjects_codegen::engine::{ @@ -521,6 +522,35 @@ fn verify_lines(r: &VerifyReport) -> (Vec, Vec) { (out, err) } +/// The rules gate's lines (all on stderr, as the other ports print them): nothing for a +/// model that declares no operation and no transition, else the summary, every finding and, +/// when any is an error, the count. +fn rules_lines(r: &VerifyReport) -> Vec { + let Some(s) = r.rules.summary else { + return Vec::new(); + }; + let mut lines = vec![format!( + "{TOOL} verify — rules: {} operation(s), {} lifecycle(s) with {} transition(s).", + s.operations, s.lifecycles, s.transitions + )]; + let errors = r.rules.errors().count(); + // Errors first, then warnings, each in the order the gate found them. + for severity in [Severity::Error, Severity::Warn] { + for d in r + .rules + .diagnostics + .iter() + .filter(|d| d.severity == severity) + { + lines.push(format!(" {} [{}]: {}", d.code, d.path, d.message)); + } + } + if errors > 0 { + lines.push(format!("{TOOL} verify — rules: {errors} error(s).")); + } + lines +} + fn cmd_verify( args: &[String], cwd: &Path, @@ -561,10 +591,17 @@ fn cmd_verify( for line in to_err { let _ = writeln!(err, "{line}"); } + for line in rules_lines(&report) { + let _ = writeln!(err, "{line}"); + } if s.has("--timings") { print_timings(out, &report.timings); } - Ok(if report.in_sync() { 0 } else { 1 }) + Ok(if report.in_sync() && !report.rules_failed() { + 0 + } else { + 1 + }) } Err(e) => { let _ = writeln!(err, "{TOOL} verify failed:\n{e}"); diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index f0465c248d..f6e05ffa81 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -804,3 +804,59 @@ fn an_owned_crate_that_breaks_exits_1_and_its_own_answers_pass_through() { assert_eq!(p.run(&["meta", "gen"]).status.code(), Some(code)); } } + +/// An order with a lifecycle whose `archived` state nothing reaches. +const LIFECYCLE_MODEL: &str = r#"{ "metadata.root": { "package": "shop", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.enum": { "name": "status", "@values": ["open", "closed", "archived"], "@default": "open", + "children": [ + { "transition.action": { "name": "close", "@from": ["open"], "@to": "closed", "@public": true } } + ] } } + ] } } +] } }"#; + +#[test] +fn verify_runs_the_rules_gate_and_a_setting_decides_whether_a_finding_fails_it() { + // A model with no operation and no transition prints nothing about rules. + let p = Project::new("rules-silent"); + p.run(&["meta", "gen"]); + let r = p.run(&["meta", "verify"]); + assert_eq!(r.status.code(), Some(0), "{}", text(&r.stderr)); + assert!(!text(&r.stderr).contains("rules:"), "{}", text(&r.stderr)); + + // A lifecycle is summarised on every run, and an unreachable state is a warning by default. + let p = Project::new("rules"); + std::fs::write(p.0.join("metaobjects/meta.shop.json"), LIFECYCLE_MODEL).unwrap(); + ok(&p.run(&["meta", "gen"])); + let r = p.run(&["meta", "verify"]); + let err = text(&r.stderr); + assert_eq!(r.status.code(), Some(0), "a warning never fails: {err}"); + assert!( + err.contains( + "cargo meta verify — rules: 0 operation(s), 1 lifecycle(s) with 1 transition(s)." + ), + "{err}" + ); + assert!( + err.contains("WARN_LIFECYCLE_UNREACHABLE_STATE [shop::Order.status]: state \"archived\" of \"status\""), + "{err}" + ); + assert!(!err.contains("error(s)"), "{err}"); + + // `verify.lifecycle.unreachable: error` turns the same finding into a failure. + std::fs::write( + p.0.join(".metaobjects/config.json"), + r#"{ "schema_version": 1, "verify": { "lifecycle": { "unreachable": "error" } } }"#, + ) + .unwrap(); + let r = p.run(&["meta", "verify"]); + let err = text(&r.stderr); + assert_eq!(r.status.code(), Some(1), "{err}"); + assert!( + err.contains("cargo meta verify — rules: 1 error(s)."), + "{err}" + ); +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index d20c038d71..e0e18dc1e4 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -21,8 +21,10 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use metaobjects::errors::MetaError; +use metaobjects::rules_check::{RulesCheckResult, check_rules}; use metaobjects::sources::{CONFIG_FILE, DEFAULT_METAOBJECTS_DIR}; use metaobjects::timing::LoadTimings; +use metaobjects::validate::util::ObjectIndex; use crate::fingerprint::{ self, ABSENT, InputEntry, KIND_CONFIG, KIND_ENGINE, KIND_EXTRA, KIND_FLAG, KIND_GENERATOR, @@ -710,12 +712,22 @@ pub struct VerifyReport { pub timings: LoadTimings, pub warnings: Vec, pub project_root: PathBuf, + /// The business-rules gate (ADR-0066) over the loaded model. It does not depend on + /// generated files, so it is part of every `verify`, rendered or not. + pub rules: RulesCheckResult, } impl VerifyReport { + /// Whether the generated files match the model. The rules gate is separate: see + /// [`VerifyReport::rules_failed`]. pub fn in_sync(&self) -> bool { self.drifted.is_empty() && self.missing.is_empty() && self.extra.is_empty() } + + /// Whether the rules gate has an error-severity finding (a warning never fails a run). + pub fn rules_failed(&self) -> bool { + self.rules.errors().next().is_some() + } } /// Compare what the generators would write with what is on disk, in memory. Nothing is @@ -747,6 +759,7 @@ pub fn verify( missing: Vec::new(), extra: Vec::new(), timings: p.timings, + rules: rules_of(&p.loaded), warnings: p.warnings, project_root: p.project_root, }); @@ -795,11 +808,24 @@ pub fn verify( missing, extra, timings: p.timings, + rules: rules_of(&p.loaded), warnings: p.warnings, project_root: p.project_root, }) } +/// The rules gate over a loaded project, under the project's own `rules.*` settings. +fn rules_of(loaded: &LoadedProject) -> RulesCheckResult { + let result = &loaded.result; + let objects = ObjectIndex::build(&result.tree, result.root); + check_rules( + &result.tree, + result.root, + &objects, + &loaded.collection.config.rules, + ) +} + /// Remove the now-empty directories above `path`, stopping at (and keeping) `stop`. fn remove_empty_parents(path: &Path, stop: &Path) { let mut cur = path.parent(); diff --git a/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index 054e5e86dd..5d9183f1b8 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -124,8 +124,9 @@ string_enum!( /// The business-rules settings (ADR-0066), from the `rules` and `verify` blocks, each /// absent key at its default. Every port reads the same keys with the same defaults. -/// This port validates and keeps them; nothing here reads them yet, because the checks -/// they tune live in `verify`, which the Rust port does not have. +/// The rules gate of `cargo meta verify` (`crate::rules_check`) reads them. `create` is the +/// one nothing here reads: it tunes what a generated create accepts, and no generator +/// emits one yet. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RulesSettings { pub permission_names: RulesPermissionNames, diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index 093ac7be36..8fda8ae594 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -18,6 +18,7 @@ pub mod node; pub mod parser; pub mod providers; pub mod registry; +pub mod rules_check; pub mod serializer; pub mod source; pub mod sources; diff --git a/server/rust/metaobjects/src/rules_check.rs b/server/rust/metaobjects/src/rules_check.rs new file mode 100644 index 0000000000..557ca0b764 --- /dev/null +++ b/server/rust/metaobjects/src/rules_check.rs @@ -0,0 +1,625 @@ +//! `cargo meta verify`: the business-rules gate (ADR-0066). +//! +//! The loader refuses a model whose operations or lifecycles are malformed. This gate reports +//! what loads clean but is almost certainly not what the author meant: a state nothing can +//! reach, a lifecycle that cannot move, a transition nothing can make, and (by setting) a +//! permission name the model derived instead of declaring. +//! +//! A port of the TypeScript reference (`cli/src/lib/rules-check.ts`), through the Python port +//! that mirrors it: the codes, severities, paths and message text are the contract, held by +//! `fixtures/rules-check-conformance/`. A model that declares no operation and no transition +//! gets no diagnostics and no summary: the gate is opt-in by declaration, so a project that +//! declares none sees no change. +//! +//! The four `rules.*` settings (`rules.permissions.names`, `rules.lifecycle.commands`, +//! `rules.lifecycle.create`, `verify.lifecycle.unreachable`) are read from the project's +//! config. `rules.lifecycle.create` changes nothing this gate reports. +//! +//! Checks, in the order they are reported: +//! +//! * `WARN_LIFECYCLE_UNREACHABLE_STATE`: states no transition reaches from the initial state +//! (severity: `verify.lifecycle.unreachable`) +//! * `WARN_LIFECYCLE_INITIAL_TERMINAL`: the initial state is one no transition leaves +//! * `WARN_TRANSITION_UNREACHABLE`: a transition whose every `@from` state is unreachable +//! (severity: `verify.lifecycle.unreachable`) +//! * `WARN_TRANSITION_PERMISSION_SHADOWED`: a transition declaring `@permission` or +//! `@public: true` that derives no command of its own, so the attribute is never read +//! * `WARN_PERMISSION_DERIVED_NAME`: a transition that derives its own command, or an +//! operation, with no `@permission` and not `@public` (severity: `rules.permissions.names`) +//! +//! Lifecycles are checked once per declaring field, so a lifecycle on an abstract base is +//! reported once, not once per inheritor. A derived command exists per concrete entity, so the +//! permission check runs per concrete entity and names it. Every read is resolving (ADR-0039). + +use serde_json::Value; + +use crate::config::{ + RulesLifecycleCommands, RulesPermissionNames, RulesSettings, VerifyLifecycleUnreachable, +}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::{TYPE_FIELD, TYPE_OBJECT}; +use crate::validate::Env; +use crate::validate::rules::{ + derive_operation_target, entity_lineage, entity_transitions, is_a, is_true, + lifecycle_transitions_of, resolve_object_on, str_attr, string_list, +}; +use crate::validate::util::ObjectIndex; + +pub const WARN_LIFECYCLE_UNREACHABLE_STATE: &str = "WARN_LIFECYCLE_UNREACHABLE_STATE"; +pub const WARN_LIFECYCLE_INITIAL_TERMINAL: &str = "WARN_LIFECYCLE_INITIAL_TERMINAL"; +pub const WARN_TRANSITION_UNREACHABLE: &str = "WARN_TRANSITION_UNREACHABLE"; +pub const WARN_PERMISSION_DERIVED_NAME: &str = "WARN_PERMISSION_DERIVED_NAME"; +pub const WARN_TRANSITION_PERMISSION_SHADOWED: &str = "WARN_TRANSITION_PERMISSION_SHADOWED"; + +const T_API: &str = "api"; +const T_OPERATION: &str = "operation"; +const T_SOURCE: &str = "source"; +const SUB_ENTITY: &str = "entity"; +const SUB_ENUM: &str = "enum"; +const SUB_COMMAND: &str = "command"; +const A_DEFAULT: &str = "default"; +const A_VALUES: &str = "values"; +const A_FROM: &str = "from"; +const A_TO: &str = "to"; +const A_PERMISSION: &str = "permission"; +const A_PUBLIC: &str = "public"; +const A_TRANSITIONS: &str = "transitions"; +const A_OBJECT_REF: &str = "objectRef"; + +/// How serious a finding is. The code keeps its `WARN_` prefix at every severity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Severity { + Warn, + Error, +} + +impl Severity { + /// The word the shared corpus writes. + pub fn as_str(self) -> &'static str { + match self { + Severity::Warn => "warn", + Severity::Error => "error", + } + } +} + +/// One finding: what is wrong, at which node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Diagnostic { + pub severity: Severity, + pub code: &'static str, + /// The package-qualified address of the node, `acme::shop::Order.status.submit`. + pub path: String, + pub message: String, +} + +/// What the model declares, for the line `verify` prints on every run that has any. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RulesSummary { + /// Declared operations, across every `api.operational`. + pub operations: usize, + /// Lifecycles: enum fields that declare at least one transition. + pub lifecycles: usize, + /// Declared transitions, across every lifecycle. + pub transitions: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RulesCheckResult { + pub diagnostics: Vec, + /// `None` when the model declares no operation and no transition. + pub summary: Option, +} + +impl RulesCheckResult { + pub fn errors(&self) -> impl Iterator { + self.diagnostics + .iter() + .filter(|d| d.severity == Severity::Error) + } +} + +/// One lifecycle: an enum field with at least one transition. +struct Lifecycle<'a> { + field: NodeId, + /// The enum's `@values`, in declaration order. + states: Vec<&'a str>, + /// The enum's `@default`; `None` only on a model the loader refused. + initial: Option<&'a str>, + transitions: Vec, +} + +fn quote_list>(xs: &[S]) -> String { + xs.iter() + .map(|x| format!("\"{}\"", x.as_ref())) + .collect::>() + .join(", ") +} + +/// A node's package-qualified address: `acme::shop::Order.status.submit`. +pub fn rules_address(tree: &Tree, node: NodeId) -> String { + let mut parts: Vec<&str> = Vec::new(); + let mut cur = node; + while let Some(parent) = tree.node(cur).parent { + let name = tree.node(cur).name.as_str(); + if !name.is_empty() { + parts.push(name); + } + cur = parent; + } + parts.reverse(); + let pkg = tree.effective_package(tree.top_level_of(node)); + if pkg.is_empty() { + parts.join(".") + } else { + format!("{pkg}{PACKAGE_SEP}{}", parts.join(".")) + } +} + +/// The permission name a node gets when it declares none, `.`: the path is +/// `` for a declared operation and `.` for a transition's +/// derived command, so two entities' transitions of one name ask about different permissions. +fn derived_permission_name(tree: &Tree, owner: NodeId, path: &str) -> String { + let pkg = tree.effective_package(tree.top_level_of(owner)); + if pkg.is_empty() { + path.to_string() + } else { + format!("{pkg}.{path}") + } +} + +fn needs_permission_name(tree: &Tree, node: NodeId) -> bool { + tree.attr(node, A_PERMISSION).is_none() && !is_true(tree, node, A_PUBLIC) +} + +fn entities(tree: &Tree, root: NodeId) -> Vec { + tree.children(root) + .iter() + .copied() + .filter(|&c| is_a(tree, c, TYPE_OBJECT, SUB_ENTITY)) + .collect() +} + +fn operations(tree: &Tree, root: NodeId) -> Vec { + tree.children(root) + .iter() + .copied() + .filter(|&a| tree.node(a).type_name == T_API) + .flat_map(|api| { + tree.children(api) + .iter() + .copied() + .filter(|&o| tree.node(o).type_name == T_OPERATION) + .collect::>() + }) + .collect() +} + +/// The lifecycles of an entity, in effective field order. +fn lifecycles_of<'a>(tree: &'a Tree, entity: NodeId) -> Vec> { + if !is_a(tree, entity, TYPE_OBJECT, SUB_ENTITY) { + return Vec::new(); + } + let lineage = entity_lineage(tree, entity); + let mut out = Vec::new(); + for &field in tree.children(entity).iter() { + if !is_a(tree, field, TYPE_FIELD, SUB_ENUM) { + continue; + } + let transitions = lifecycle_transitions_of(tree, &lineage, field); + if transitions.is_empty() { + continue; + } + out.push(Lifecycle { + field, + states: string_list(tree, field, A_VALUES), + initial: str_attr(tree, field, A_DEFAULT), + transitions, + }); + } + out +} + +/// Every lifecycle of the model, once per declaring field, in model order. +fn declared_lifecycles<'a>(tree: &'a Tree, root: NodeId) -> Vec> { + let mut seen: Vec = Vec::new(); + let mut out = Vec::new(); + for entity in entities(tree, root) { + for l in lifecycles_of(tree, entity) { + if seen.contains(&l.field) { + continue; + } + seen.push(l.field); + out.push(l); + } + } + out +} + +/// Whether an entity's lifecycles are live: it declares or inherits a source. A lifecycle on +/// an entity with no source loads and is inert: it derives no command. +fn lifecycle_is_live(tree: &Tree, entity: NodeId) -> bool { + tree.children(entity) + .iter() + .any(|&c| tree.node(c).type_name == T_SOURCE) +} + +fn transition_from(tree: &Tree, t: NodeId) -> Vec<&str> { + string_list(tree, t, A_FROM) +} + +fn reachable_states<'a>(tree: &'a Tree, l: &Lifecycle<'a>) -> Vec<&'a str> { + let Some(initial) = l.initial else { + return Vec::new(); + }; + let mut seen = vec![initial]; + let mut queue = vec![initial]; + while !queue.is_empty() { + let s = queue.remove(0); + for &t in &l.transitions { + let Some(to) = str_attr(tree, t, A_TO) else { + continue; + }; + if transition_from(tree, t).contains(&s) && !seen.contains(&to) { + seen.push(to); + queue.push(to); + } + } + } + seen +} + +/// The members no transition leaves (a self-transition counts as leaving). +fn terminal_states<'a>(tree: &Tree, l: &Lifecycle<'a>) -> Vec<&'a str> { + let leaving: Vec<&str> = l + .transitions + .iter() + .flat_map(|&t| transition_from(tree, t)) + .collect(); + l.states + .iter() + .copied() + .filter(|s| !leaving.contains(s)) + .collect() +} + +fn check_lifecycle( + tree: &Tree, + l: &Lifecycle<'_>, + settings: &RulesSettings, + out: &mut Vec, +) { + let where_ = rules_address(tree, l.field); + let Some(initial) = l.initial else { + return; // the loader refused this model (ERR_LIFECYCLE_NO_INITIAL) + }; + let field_name = tree.node(l.field).name.as_str(); + let reachable = reachable_states(tree, l); + let unreachable_severity = match settings.lifecycle_unreachable { + VerifyLifecycleUnreachable::Off => None, + VerifyLifecycleUnreachable::Warn => Some(Severity::Warn), + VerifyLifecycleUnreachable::Error => Some(Severity::Error), + }; + + if let Some(severity) = unreachable_severity { + let unreachable: Vec<&str> = l + .states + .iter() + .copied() + .filter(|s| !reachable.contains(s)) + .collect(); + if !unreachable.is_empty() { + let one = unreachable.len() == 1; + out.push(Diagnostic { + severity, + code: WARN_LIFECYCLE_UNREACHABLE_STATE, + path: where_.clone(), + message: format!( + "{} {} of \"{field_name}\" cannot be reached from the initial state \"{initial}\" by any transition. \ + Add the transition that leads there, or set verify.lifecycle.unreachable if only seeded data uses {}.", + if one { "state" } else { "states" }, + quote_list(&unreachable), + if one { "it" } else { "them" }, + ), + }); + } + } + + if terminal_states(tree, l).contains(&initial) { + out.push(Diagnostic { + severity: Severity::Warn, + code: WARN_LIFECYCLE_INITIAL_TERMINAL, + path: where_, + message: format!( + "the initial state \"{initial}\" of \"{field_name}\" is terminal: no transition leaves it, \ + so no row of this lifecycle can ever move." + ), + }); + } + + if let Some(severity) = unreachable_severity { + for &t in &l.transitions { + let from = transition_from(tree, t); + if from.is_empty() || from.iter().any(|s| reachable.contains(s)) { + continue; + } + out.push(Diagnostic { + severity, + code: WARN_TRANSITION_UNREACHABLE, + path: rules_address(tree, t), + message: format!( + "transition \"{}\" starts only from {}, which no transition reaches from \ + the initial state \"{initial}\", so it can never be made.", + tree.node(t).name, + quote_list(&from), + ), + }); + } + } +} + +/// One command's claim on a transition node, made for its target entity. +struct Claim { + target: NodeId, + op: NodeId, +} + +/// The operation's target: the declared `@objectRef` when it names an entity, else the +/// derived one. +fn operation_target(env: &Env<'_>, op: NodeId) -> Option { + if let Some(declared) = str_attr(env.tree, op, A_OBJECT_REF) { + return resolve_object_on(env, op, declared) + .filter(|&n| env.tree.node(n).sub_type == SUB_ENTITY); + } + derive_operation_target(env, op).map(|(entity, _)| entity) +} + +/// Each transition node the declared commands claim, with the claims on it in model order. +fn claimed_transitions(env: &Env<'_>, root: NodeId) -> Vec<(NodeId, Vec)> { + let tree = env.tree; + let mut claimed: Vec<(NodeId, Vec)> = Vec::new(); + for op in operations(tree, root) { + if tree.node(op).sub_type != SUB_COMMAND { + continue; + } + let Some(target) = operation_target(env, op) else { + continue; + }; + let names = string_list(tree, op, A_TRANSITIONS); + for t in entity_transitions(tree, target) { + if !names.contains(&tree.node(t).name.as_str()) { + continue; + } + let claim = Claim { target, op }; + match claimed.iter_mut().find(|(n, _)| *n == t) { + Some((_, claims)) => claims.push(claim), + None => claimed.push((t, vec![claim])), + } + } + } + claimed +} + +/// The claims that cover transition `t` on `entity`: those made for the entity or an entity +/// it extends. +fn claims_on<'c>( + tree: &Tree, + claimed: &'c [(NodeId, Vec)], + entity: NodeId, + t: NodeId, +) -> Vec<&'c Claim> { + let lineage = entity_lineage(tree, entity); + claimed + .iter() + .find(|(n, _)| *n == t) + .map(|(_, claims)| { + claims + .iter() + .filter(|c| lineage.contains(&c.target)) + .collect() + }) + .unwrap_or_default() +} + +/// Whether `t`, carried by `entity`, derives a command of its own under the setting. +fn derives_command( + tree: &Tree, + claimed: &[(NodeId, Vec)], + settings: &RulesSettings, + entity: NodeId, + t: NodeId, +) -> bool { + match settings.lifecycle_commands { + RulesLifecycleCommands::NoneDerived => false, + RulesLifecycleCommands::All => true, + RulesLifecycleCommands::Unclaimed => claims_on(tree, claimed, entity, t).is_empty(), + } +} + +/// The entities a transition can derive a command on: concrete, with a source. +fn command_entities(tree: &Tree, root: NodeId) -> Vec { + entities(tree, root) + .into_iter() + .filter(|&e| !tree.node(e).is_abstract && lifecycle_is_live(tree, e)) + .collect() +} + +/// A transition's `@permission` or `@public` is read only by the command derived from it. One +/// that derives no command for any concrete entity carrying it declares an attribute nothing +/// reads. +fn check_shadowed_permissions( + env: &Env<'_>, + root: NodeId, + settings: &RulesSettings, + out: &mut Vec, +) { + let tree = env.tree; + if settings.lifecycle_commands == RulesLifecycleCommands::All { + return; + } + let claimed = claimed_transitions(env, root); + let mut carriers: Vec<(NodeId, Vec)> = Vec::new(); + for entity in command_entities(tree, root) { + for t in entity_transitions(tree, entity) { + match carriers.iter_mut().find(|(n, _)| *n == t) { + Some((_, list)) => list.push(entity), + None => carriers.push((t, vec![entity])), + } + } + } + for (t, with_t) in &carriers { + let t = *t; + let permission = tree.attr(t, A_PERMISSION); + let is_public = is_true(tree, t, A_PUBLIC); + if permission.is_none() && !is_public { + continue; + } + if with_t + .iter() + .any(|&e| derives_command(tree, &claimed, settings, e, t)) + { + continue; + } + let declared = match permission { + Some(Value::String(p)) => format!("@permission \"{p}\""), + Some(other) => format!("@permission \"{other}\""), + None => "@public: true".to_string(), + }; + let mut claimers: Vec = Vec::new(); + for &e in with_t { + for c in claims_on(tree, &claimed, e, t) { + let api = tree + .node(c.op) + .parent + .map(|p| tree.node(p).name.as_str()) + .unwrap_or(""); + let label = format!("{api}.{}", tree.node(c.op).name); + if !claimers.contains(&label) { + claimers.push(label); + } + } + } + let why = if settings.lifecycle_commands == RulesLifecycleCommands::NoneDerived { + "rules.lifecycle.commands is \"none\": no command is derived from it".to_string() + } else { + let one = claimers.len() == 1; + format!( + "it derives no command of its own: it is made only by {}, which {} the policy about {} own permission", + quote_list(&claimers), + if one { "asks" } else { "ask" }, + if one { "its" } else { "their" }, + ) + }; + out.push(Diagnostic { + severity: Severity::Warn, + code: WARN_TRANSITION_PERMISSION_SHADOWED, + path: rules_address(tree, t), + message: format!( + "transition \"{}\" declares {declared}, but {why}, so the attribute is never read. \ + Remove it from the transition, or declare it on the command that makes the transition.", + tree.node(t).name, + ), + }); + } +} + +fn check_permission_names( + env: &Env<'_>, + root: NodeId, + settings: &RulesSettings, + out: &mut Vec, +) { + let tree = env.tree; + let severity = match settings.permission_names { + RulesPermissionNames::Derive => return, + RulesPermissionNames::Advise => Severity::Warn, + RulesPermissionNames::Require => Severity::Error, + }; + let advice = |kind: &str| { + format!("which changes if the {kind} is renamed. Declare @permission, or @public: true.") + }; + + if settings.lifecycle_commands != RulesLifecycleCommands::NoneDerived { + let claimed = claimed_transitions(env, root); + for entity in command_entities(tree, root) { + for t in entity_transitions(tree, entity) { + if !derives_command(tree, &claimed, settings, entity, t) + || !needs_permission_name(tree, t) + { + continue; + } + let field_name = tree + .node(t) + .parent + .map(|f| tree.node(f).name.as_str()) + .unwrap_or(""); + let entity_name = tree.node(entity).name.as_str(); + let t_name = tree.node(t).name.as_str(); + out.push(Diagnostic { + severity, + code: WARN_PERMISSION_DERIVED_NAME, + path: format!("{}.{field_name}.{t_name}", rules_address(tree, entity)), + message: format!( + "the command derived from transition \"{t_name}\" of \"{entity_name}\" has no @permission, \ + so it asks the policy about the derived name \"{}\", {}", + derived_permission_name(tree, entity, &format!("{entity_name}.{t_name}")), + advice("transition"), + ), + }); + } + } + } + + for op in operations(tree, root) { + if !needs_permission_name(tree, op) { + continue; + } + let n = tree.node(op); + out.push(Diagnostic { + severity, + code: WARN_PERMISSION_DERIVED_NAME, + path: rules_address(tree, op), + message: format!( + "operation.{} \"{}\" has no @permission, so it asks the policy about the \ + derived name \"{}\", {}", + n.sub_type, + n.name, + derived_permission_name(tree, op, &n.name), + advice("operation"), + ), + }); + } +} + +/// The rules gate over a loaded model. `objects` is the loader's index of the root's objects +/// (`ObjectIndex::build(tree, root)`). +pub fn check_rules( + tree: &Tree, + root: NodeId, + objects: &ObjectIndex, + settings: &RulesSettings, +) -> RulesCheckResult { + let env = Env { tree, objects }; + let lifecycles = declared_lifecycles(tree, root); + let ops = operations(tree, root); + if lifecycles.is_empty() && ops.is_empty() { + return RulesCheckResult { + diagnostics: Vec::new(), + summary: None, + }; + } + let mut diagnostics = Vec::new(); + for l in &lifecycles { + check_lifecycle(tree, l, settings, &mut diagnostics); + } + check_shadowed_permissions(&env, root, settings, &mut diagnostics); + check_permission_names(&env, root, settings, &mut diagnostics); + RulesCheckResult { + diagnostics, + summary: Some(RulesSummary { + operations: ops.len(), + lifecycles: lifecycles.len(), + transitions: lifecycles.iter().map(|l| l.transitions.len()).sum(), + }), + } +} diff --git a/server/rust/metaobjects/src/validate/mod.rs b/server/rust/metaobjects/src/validate/mod.rs index beb340bd04..b00aea731a 100644 --- a/server/rust/metaobjects/src/validate/mod.rs +++ b/server/rust/metaobjects/src/validate/mod.rs @@ -38,6 +38,24 @@ pub struct Ctx<'a> { pub naming: NamingCtx<'a>, } +/// The part of [`Ctx`] that reading a loaded model needs: its tree and its objects by key. +/// The `verify` rules gate runs after the load, when no registry is at hand, and reads +/// through this. +#[derive(Clone, Copy)] +pub struct Env<'a> { + pub tree: &'a Tree, + pub objects: &'a util::ObjectIndex, +} + +impl<'a> Ctx<'a> { + pub fn env(&self) -> Env<'a> { + Env { + tree: self.tree, + objects: self.objects, + } + } +} + /// What a pass writes. Errors and warnings are separate channels, as in every port. #[derive(Debug, Default)] pub struct Findings { diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs index 2b652e3759..cbe72cdd23 100644 --- a/server/rust/metaobjects/src/validate/rules.rs +++ b/server/rust/metaobjects/src/validate/rules.rs @@ -58,7 +58,7 @@ use crate::loader::split_child_tail; use crate::node::{NodeId, PACKAGE_SEP, Tree}; use crate::parser::{TYPE_FIELD, TYPE_OBJECT}; use crate::validate::field_expr::{condition_message, fields_by_name}; -use crate::validate::{Ctx, Findings}; +use crate::validate::{Ctx, Env, Findings}; pub const ERR_TRANSITION_UNKNOWN_STATE: &str = "ERR_TRANSITION_UNKNOWN_STATE"; pub const ERR_TRANSITION_NOT_ON_ENTITY: &str = "ERR_TRANSITION_NOT_ON_ENTITY"; @@ -246,7 +246,7 @@ fn label(tree: &Tree, node: NodeId) -> String { } /// A string-array attr read resolving; a bare string is one element. -fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { +pub(crate) fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { match tree.attr(node, attr) { Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), Some(Value::String(s)) => vec![s.as_str()], @@ -254,20 +254,20 @@ fn string_list<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Vec<&'a str> { } } -fn str_attr<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Option<&'a str> { +pub(crate) fn str_attr<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> Option<&'a str> { tree.attr(node, attr).and_then(Value::as_str) } -fn is_true(tree: &Tree, node: NodeId, attr: &str) -> bool { +pub(crate) fn is_true(tree: &Tree, node: NodeId, attr: &str) -> bool { tree.attr(node, attr) == Some(&Value::Bool(true)) } -fn is_a(tree: &Tree, node: NodeId, type_name: &str, sub_type: &str) -> bool { +pub(crate) fn is_a(tree: &Tree, node: NodeId, type_name: &str, sub_type: &str) -> bool { let n = tree.node(node); n.type_name == type_name && n.sub_type == sub_type } -fn is_entity(tree: &Tree, node: NodeId) -> bool { +pub(crate) fn is_entity(tree: &Tree, node: NodeId) -> bool { is_a(tree, node, TYPE_OBJECT, SUB_ENTITY) } @@ -292,7 +292,7 @@ impl Sink<'_> { // ---- lifecycle and target derivation ------------------------------------------------ /// The `transition.action` children of a field, resolving. -fn transitions_of(tree: &Tree, field: NodeId) -> Vec { +pub(crate) fn transitions_of(tree: &Tree, field: NodeId) -> Vec { tree.children(field) .iter() .copied() @@ -301,7 +301,7 @@ fn transitions_of(tree: &Tree, field: NodeId) -> Vec { } /// An entity and every entity it extends, nearest first. -fn entity_lineage(tree: &Tree, entity: NodeId) -> Vec { +pub(crate) fn entity_lineage(tree: &Tree, entity: NodeId) -> Vec { let mut out = Vec::new(); let mut cur = Some(entity); while let Some(e) = cur.filter(|e| !out.contains(e)) { @@ -314,7 +314,11 @@ fn entity_lineage(tree: &Tree, entity: NodeId) -> Vec { /// The transitions a field gives the entity whose lineage this is: those declared on a /// field of the entity itself or of an entity it extends. A transition reached only /// through the field's own `extends` of another entity's field is not one. -fn lifecycle_transitions_of(tree: &Tree, lineage: &[NodeId], field: NodeId) -> Vec { +pub(crate) fn lifecycle_transitions_of( + tree: &Tree, + lineage: &[NodeId], + field: NodeId, +) -> Vec { transitions_of(tree, field) .into_iter() .filter(|&t| { @@ -328,7 +332,7 @@ fn lifecycle_transitions_of(tree: &Tree, lineage: &[NodeId], field: NodeId) -> V /// Every transition of an object, across all its lifecycles (its enum fields with at /// least one transition), in effective field order. Only an `object.entity` has any. -fn entity_transitions(tree: &Tree, obj: NodeId) -> Vec { +pub(crate) fn entity_transitions(tree: &Tree, obj: NodeId) -> Vec { if !is_entity(tree, obj) { return Vec::new(); } @@ -342,7 +346,7 @@ fn entity_transitions(tree: &Tree, obj: NodeId) -> Vec { } /// The primary key field names of an entity: its effective `identity.primary` `@fields`. -fn primary_key_fields(tree: &Tree, entity: NodeId) -> Vec<&str> { +pub(crate) fn primary_key_fields(tree: &Tree, entity: NodeId) -> Vec<&str> { tree.children(entity) .iter() .copied() @@ -357,7 +361,7 @@ fn referrer_package_of(tree: &Tree, node: NodeId) -> String { } /// Resolve an object reference written on `node` (owner part only). -fn resolve_object_on(ctx: &Ctx<'_>, node: NodeId, reference: &str) -> Option { +pub(crate) fn resolve_object_on(ctx: &Env<'_>, node: NodeId, reference: &str) -> Option { ctx.objects.resolve( split_child_tail(reference).0, &referrer_package_of(ctx.tree, node), @@ -367,7 +371,7 @@ fn resolve_object_on(ctx: &Ctx<'_>, node: NodeId, reference: &str) -> Option(ctx: &Ctx<'a>, member: NodeId) -> Option<(NodeId, &'a str)> { +fn extended_member<'a>(ctx: &Env<'a>, member: NodeId) -> Option<(NodeId, &'a str)> { let tree = ctx.tree; let node = tree.node(member); let reference = node.super_ref.as_deref()?; @@ -391,7 +395,7 @@ fn extended_member<'a>(ctx: &Ctx<'a>, member: NodeId) -> Option<(NodeId, &'a str /// field of the entity is extended by exactly one field of the value. A value that /// borrows part of a composite key, or one key field twice (`fromId` and `toId`), names /// no single row of that entity, so it borrows nothing from it. -fn borrowed_key_entities(ctx: &Ctx<'_>, value: NodeId) -> Vec { +pub(crate) fn borrowed_key_entities(ctx: &Env<'_>, value: NodeId) -> Vec { let tree = ctx.tree; let mut counts: Vec<(NodeId, HashMap<&str, usize>)> = Vec::new(); for &f in tree.children(value).iter() { @@ -428,7 +432,7 @@ fn borrowed_key_entities(ctx: &Ctx<'_>, value: NodeId) -> Vec { /// The base entity of a projection: the entity its extended identity names, else the one /// entity its extended fields name. `None` when there is none or more than one. -fn projection_base_entity(ctx: &Ctx<'_>, projection: NodeId) -> Option { +pub(crate) fn projection_base_entity(ctx: &Env<'_>, projection: NodeId) -> Option { let tree = ctx.tree; let kids = tree.children(projection); let entity_named_by = |member: NodeId| { @@ -460,7 +464,7 @@ fn projection_base_entity(ctx: &Ctx<'_>, projection: NodeId) -> Option { /// How an operation's target was derived. #[derive(Clone, Copy, PartialEq, Eq)] -enum Via { +pub(crate) enum Via { /// The input borrows the target's key. Input, Output, @@ -473,7 +477,7 @@ enum Via { /// /// Whole keys of two entities, part of a key, or one key field borrowed twice derive /// nothing from the input. -fn derive_operation_target(ctx: &Ctx<'_>, op: NodeId) -> Option<(NodeId, Via)> { +pub(crate) fn derive_operation_target(ctx: &Env<'_>, op: NodeId) -> Option<(NodeId, Via)> { let tree = ctx.tree; if let Some(input) = str_attr(tree, op, A_INPUT_REF) .and_then(|r| resolve_object_on(ctx, op, r)) @@ -495,7 +499,11 @@ fn derive_operation_target(ctx: &Ctx<'_>, op: NodeId) -> Option<(NodeId, Via)> { /// Whether the operation addresses one row of its target by key: its input borrows the /// target's key, or it is a query with no input and no `@many` whose target comes from /// its output (a get by key). -fn operation_is_keyed(ctx: &Ctx<'_>, op: NodeId, derived: Option<(NodeId, Via)>) -> bool { +pub(crate) fn operation_is_keyed( + ctx: &Env<'_>, + op: NodeId, + derived: Option<(NodeId, Via)>, +) -> bool { let tree = ctx.tree; match derived { None => false, @@ -857,7 +865,7 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { Some(t) => format!("is an object.{}", tree.node(t).sub_type), }; if let Some(input_ref) = str_attr(tree, op, A_INPUT_REF) { - let input = resolve_object_on(ctx, op, input_ref); + let input = resolve_object_on(&ctx.env(), op, input_ref); if input.is_none_or(|i| tree.node(i).sub_type != SUB_VALUE) { sink.add( op, @@ -871,7 +879,7 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { } } if let Some(output_ref) = str_attr(tree, op, A_OUTPUT_REF) { - let output = resolve_object_on(ctx, op, output_ref); + let output = resolve_object_on(&ctx.env(), op, output_ref); let legal = output.is_some_and(|o| { [SUB_ENTITY, SUB_PROJECTION, SUB_VALUE].contains(&tree.node(o).sub_type.as_str()) }); @@ -889,10 +897,10 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { } // O2, O3 — the target. - let derived = derive_operation_target(ctx, op); + let derived = derive_operation_target(&ctx.env(), op); let mut target = derived.map(|(entity, _)| entity); if let Some(object_ref) = str_attr(tree, op, A_OBJECT_REF) { - let declared = resolve_object_on(ctx, op, object_ref); + let declared = resolve_object_on(&ctx.env(), op, object_ref); let Some(declared) = declared.filter(|&d| tree.node(d).sub_type == SUB_ENTITY) else { sink.add( op, @@ -966,7 +974,7 @@ fn check_operation(ctx: &Ctx<'_>, op: NodeId, sink: &mut Sink<'_>) { for (binding, path) in declared_paths(tree, op) { let found = placeholders(path); let expected = match target { - Some(t) if operation_is_keyed(ctx, op, derived) => primary_key_fields(tree, t), + Some(t) if operation_is_keyed(&ctx.env(), op, derived) => primary_key_fields(tree, t), _ => Vec::new(), }; if sorted(&found) == sorted(&expected) { @@ -1022,7 +1030,7 @@ fn ref_identity<'a>(ctx: &Ctx<'a>, op: NodeId, attr: &str) -> RefIdentity<'a> { None => RefIdentity::Absent, Some(v) => v .as_str() - .and_then(|r| resolve_object_on(ctx, op, r)) + .and_then(|r| resolve_object_on(&ctx.env(), op, r)) .map_or(RefIdentity::Raw(v), RefIdentity::Node), } } diff --git a/server/rust/metaobjects/tests/rules_check_conformance.rs b/server/rust/metaobjects/tests/rules_check_conformance.rs new file mode 100644 index 0000000000..ace2736091 --- /dev/null +++ b/server/rust/metaobjects/tests/rules_check_conformance.rs @@ -0,0 +1,138 @@ +//! The business-rules gate corpus (`fixtures/rules-check-conformance/`): each case loads +//! `input/` strictly, reads `options.json` (the `rules` and `verify` blocks, optional) +//! through the config reader, runs the gate and compares the diagnostics and the summary +//! with `expected.json`. Diagnostics compare as an unordered set of exact +//! (severity, code, path, message) records, as the other ports' runners do. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use metaobjects::config::parse_config; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::default_registry; +use metaobjects::rules_check::{RulesCheckResult, check_rules}; +use metaobjects::validate::util::ObjectIndex; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/rules-check-conformance") +} + +fn input_files(dir: &Path, out: &mut Vec) { + let mut entries: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().path()) + .collect(); + entries.sort(); + for p in entries { + if p.is_dir() { + input_files(&p, out); + } else if p.extension().is_some_and(|e| e == "yaml" || e == "json") { + out.push(p); + } + } +} + +fn run(case: &Path) -> RulesCheckResult { + let mut registry = default_registry().expect("the built-in providers compose"); + registry.seal(); + let mut files = Vec::new(); + input_files(&case.join("input"), &mut files); + let sources: Vec<(String, String)> = files + .iter() + .map(|f| { + ( + f.to_string_lossy().into_owned(), + std::fs::read_to_string(f).unwrap(), + ) + }) + .collect(); + let loaded = Loader::new(®istry).load_sources(&sources); + assert!( + loaded.errors.is_empty(), + "{}: the input must load clean: {:?}", + case.display(), + loaded.errors + ); + + let mut config = json!({ "schema_version": 1 }); + if let Ok(text) = std::fs::read_to_string(case.join("options.json")) { + let options: Value = serde_json::from_str(&text).unwrap(); + for (k, v) in options.as_object().unwrap() { + config[k] = v.clone(); + } + } + let settings = parse_config(&config, "options.json", &NamingRegistry::builtin()) + .expect("options.json is a valid config fragment") + .config + .rules; + + let objects = ObjectIndex::build(&loaded.tree, loaded.root); + check_rules(&loaded.tree, loaded.root, &objects, &settings) +} + +fn as_json(result: &RulesCheckResult) -> Value { + json!({ + "diagnostics": result.diagnostics.iter().map(|d| json!({ + "severity": d.severity.as_str(), + "code": d.code, + "path": d.path, + "message": d.message, + })).collect::>(), + "summary": result.summary.map(|s| json!({ + "operations": s.operations, + "lifecycles": s.lifecycles, + "transitions": s.transitions, + })), + }) +} + +fn sorted(diagnostics: &Value) -> Vec { + let mut v: Vec = diagnostics + .as_array() + .unwrap() + .iter() + .map(|d| d.to_string()) + .collect(); + v.sort(); + v +} + +#[test] +fn every_rules_check_case_reports_what_the_corpus_expects() { + let mut cases: Vec = std::fs::read_dir(corpus()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.join("expected.json").is_file()) + .collect(); + cases.sort(); + assert!( + cases.len() >= 16, + "the corpus has 16 cases; found {}", + cases.len() + ); + let mut failures = Vec::new(); + for case in &cases { + let expected: Value = + serde_json::from_str(&std::fs::read_to_string(case.join("expected.json")).unwrap()) + .unwrap(); + let actual = as_json(&run(case)); + let name = case.file_name().unwrap().to_string_lossy(); + if sorted(&actual["diagnostics"]) != sorted(&expected["diagnostics"]) { + failures.push(format!( + "{name}: diagnostics differ\n expected: {:#?}\n actual: {:#?}", + sorted(&expected["diagnostics"]), + sorted(&actual["diagnostics"]) + )); + } + let expected_summary = expected.get("summary").cloned().unwrap_or(Value::Null); + if actual["summary"] != expected_summary { + failures.push(format!( + "{name}: summary differs: expected {expected_summary}, actual {}", + actual["summary"] + )); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} From 9d05f800ae1c89c8e491bde48b98c140b9e0e16d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 04:54:09 -0500 Subject: [PATCH 3/6] no-mistakes(review): Retire Rust preview wording, fix verify help text --- .claude/rules/cross-language-porting.md | 2 +- docs/CONFORMANCE.md | 14 +++++------ docs/README.md | 2 +- docs/features/business-rules.md | 5 ++-- docs/features/cli.md | 7 +++--- docs/features/language-differences.md | 2 +- docs/features/own-your-codegen.md | 2 +- docs/features/stability-labels.md | 2 +- docs/ports/rust.md | 14 +++++------ server/rust/metaobjects-cli/src/lib.rs | 6 ++--- .../tests/metamodel_conformance.rs | 4 ++-- spec/conformance-tests.md | 2 +- ...-0064-skip-codegen-when-nothing-changed.md | 2 +- .../ADR-0065-rust-is-the-sixth-port.md | 24 +++++++++++++------ spec/decisions/README.md | 2 +- 15 files changed, 49 insertions(+), 41 deletions(-) diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 4966f27c3b..618d7897a2 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -18,7 +18,7 @@ New vocabulary goes in its own provider pack, never in `metaobjects-core-types` Preserve the following contracts exactly across all language ports: -**Metamodel subtype vocabularies (must be identical across languages):** the `registry-conformance` gate (`fixtures/registry-conformance/`) is the structural enforcer of this rule — each port emits its registry as a canonical manifest byte-matched to `expected-registry.json`. **All five shipped ports (TS / C# / Java / Kotlin / Python) plus Rust in preview (ADR-0065, byte-identical) are live + green** (SP-G Java/Kotlin reconciliation complete; the JVM runners compose from the defined metamodel provider set so codegen-base/om classpath SPI does not pollute the measured vocabulary). See `fixtures/registry-conformance/README.md`. +**Metamodel subtype vocabularies (must be identical across languages):** the `registry-conformance` gate (`fixtures/registry-conformance/`) is the structural enforcer of this rule — each port emits its registry as a canonical manifest byte-matched to `expected-registry.json`. **All five shipped ports (TS / C# / Java / Kotlin / Python) plus Rust (ADR-0065, byte-identical) are live + green** (SP-G Java/Kotlin reconciliation complete; the JVM runners compose from the defined metamodel provider set so codegen-base/om classpath SPI does not pollute the measured vocabulary). See `fixtures/registry-conformance/README.md`. - Filter operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `like`, `isNull` - Object subtypes: `entity` (owns data: own identity, writable sources, lifecycle), `value` (pure shape: NO identity, NO source, ever; constructed — by caller/embedding — never populated; may `extends` entity fields for shape; a value-hosted field may carry `origin.passthrough` but never an assembly origin), `projection` (derived read-only representation: fields `extends`-bound / origin-derived / self-declared-under-external-assembly, all read-only at subtype level; identity optional and MUST extend an entity identity; sources restricted to read-only `@kind`s; the declared field set IS the exposure — inclusive list, fail-closed). A field carrying `origin.*` is derived ⇒ read-only wherever it lives (incl. on entities). An entity's primary source must be a writable `@kind` (read-only kinds only in read role). See [ADR-0028](spec/decisions/ADR-0028-object-taxonomy-projection-value-purity.md). (FR-024 Phase E — `object.projection`/`value` are registered in `expected-registry.json` and the projection/value validation passes [identity pass-through, value-purity, projection-licensing, `@via` inference/cardinality, extends/origin agreement, derived-field providability] are enforced cross-port in all 5 ports. The **B4b** entity-primary-source-readonly cutover [the "writable `@kind`" clause above — `ERR_ENTITY_PRIMARY_SOURCE_READONLY`] + the projection codegen fan-out (read-only DTOs for view-kind projections; FR-015 proc-callables for proc-kind projections in TypeScript, C# and Kotlin ONLY — Java and Python ship no callable generator at all, so the cross-port claim does NOT cover that clause; api-docs label `object.projection` units as `projection` and document their generated `Dto`) are now shipped cross-port; the declared-API surface, the last third of FR-024, is registered since 1.3.0 by ADR-0066 — see the API bullet below.) **`report` (FR-044 Plan 1)** is a root object subtype registered in all five ports, with the `dimension.attribute` / `dimension.time` / `measure.aggregate` / `measure.ratio` / `segment.filter` children on `object.entity` and the relative-date filter value — loader-validated (`ERR_INVALID_DIMENSION` / `ERR_INVALID_MEASURE` / `ERR_INVALID_REPORT` / `ERR_REPORT_FOREIGN_MEASURE`, plus `ERR_BAD_ATTR_FILTER` for relative dates off a reporting host) and, since FR-044 Plan 2, **lowered only when it declares a read-only `source.rdb` of `@kind: view`**: `meta migrate` creates that view (TypeScript only, ADR-0015), every port reads it (persistence corpus, `report-shapes.json`), C# generates its typed row and Kotlin its Exposed table object, and, since FR-044 Plan 3, every port's generators **serve it as a keyless read-only projection** (GET list with filter/sort/paging on every derived field that has a filter band, `POST` 405, no `/{id}`; row type + filter allowlist + route/controller per port, gated by the api-contract `report/` sub-corpus in the generated lane). The client UI tier (hooks, grids, forms) and a report with no view source at all stay inert, gated by the 43 `reporting` conformance fixtures and the `codegen-noop` corpus. A served report is the predicate `servedReport` (TS) / `ReportRows.IsViewBacked` (C#) / `RestSurfaceGate.isServedReport` (Java, Kotlin) / `is_served_report` (Python): concrete, read source `@kind: view`. See [docs/features/reporting.md](docs/features/reporting.md). - Source subtypes: `rdb` (paradigm; ADR-0007). The pre-v2 `dbTable`/`dbView` subtypes are RETIRED — `source.rdb` + `@kind: table|view|materializedView|storedProc|tableFunction` is the form, with read-only-ness derived from `@kind`. Multi-source via `@role` (exactly one `primary` per object). Source physical name = `@table` (NOT `@name`); field physical name = `@column` (renamed from `@dbColumn`). Referential actions on relationships: `@onDelete` / `@onUpdate`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index ef04a89586..df26941fa8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -70,7 +70,7 @@ 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 these corpora +**Rust (ADR-0065) is not a column yet.** The sixth port runs these corpora today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 578 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; @@ -87,9 +87,9 @@ crate carries; the `core` cases of `writer-conformance` (ADR-0063); and `generator-registry-conformance`, with the eject contract's census, completeness and depth (ADR-0034 Amendment 8). It also runs the codegen-compile gate (below) with every shipped generator, and a scale gate over twenty copies of the fitness model. The ledgers above may -only shrink; the corpora without one assert each case outright. 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 +only shrink; the corpora without one assert each case outright. 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 ADR-0065 turns the warning off. A regression still fails: the ledger's `minPassing` (578) 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. @@ -249,7 +249,7 @@ Amendment 8). A gate, not a corpus: it has no fixtures of its own, and reads and emits what the packaged generator emits (depth). TypeScript: `cli/test/eject-contract.test.ts`. C#: `EjectContractTests`. Java: `EjectContractTest` in `maven-plugin`. Kotlin: `EjectContractTest` in `codegen-kotlin`. Python: - `tests/conformance/test_eject_contract.py`. Rust (preview) holds its three generators to + `tests/conformance/test_eject_contract.py`. Rust holds its three generators to the same assertions: census, completeness and the reference scan in `metaobjects-codegen/tests/generator_registry.rs`, and the ejected-alone build in `metaobjects-cli/tests/cli.rs`. @@ -341,7 +341,7 @@ manifest contains without moving these boundaries. — Python having no static compiler — importing the generated package (which is what resolves the imports BETWEEN modules) plus `ruff` F821 for the branches importing never executes. -- *Rust (preview) runs it too*, with `cargo check` and `rustfmt --check`, over every +- *Rust runs it too*, with `cargo check` and `rustfmt --check`, over every generator it ships: it has no framework-bound route tier to exclude, and its generated client and commands are driven over HTTP against a local stub in the same test. - *Every port excludes its framework-bound route tier* — TS `routesFile`, C# @@ -417,7 +417,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, YAML, source-resolution, naming, skip, validation, wire-vector, writer and generator-registry corpora; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | +| Rust | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, naming, skip, validation, wire-vector, writer and generator-registry corpora; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | 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/docs/README.md b/docs/README.md index 13a3b282d9..843b69773a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -61,7 +61,7 @@ docs/ ├── kotlin.md ├── csharp.md ├── python.md - └── rust.md # the Rust port, in preview: loader, validation, cargo meta (init/gen/verify/eject) and its three generators + └── rust.md # the Rust port: loader, validation, cargo meta (init/gen/verify/eject) and its three generators ``` If this list and `ls docs/features/` ever disagree, trust the directory listing — diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 013a9c348d..e0071d6310 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -10,9 +10,8 @@ The model never says *how* an operation works. That is code. The model says wher is needed, which moves are legal, and what a command may return, so all three can be checked. **What 1.3.0 ships.** The vocabulary, checked when it loads and by `verify`, in all five ports. -The Rust preview port loads the vocabulary and runs the same loader rules; its `verify` is the -codegen drift gate only, so the checks under "What `verify` reports" do not run there -([Rust port](../ports/rust.md)). +The Rust port loads the vocabulary and runs the same loader rules, and its `verify` runs the +same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). A requirement can claim an operation or a transition. Nothing is generated from the vocabulary yet: the service shells that enforce these rules at run time are later work (ADR-0067): service generators an app adds to its generator list, as it adds any generator. A lifecycle in a project diff --git a/docs/features/cli.md b/docs/features/cli.md index 2cb7085229..515c554652 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -41,7 +41,7 @@ command surface splits in two: | Java/Kotlin codegen | Maven plugin | `mvn metaobjects:generate` (`metaobjects:generate`) | Kotlin generators run through the same goal — see below. **No `--template-spec` flag, deliberately** — `` already loads a consumer class from the project classpath, so the declarative surface is `com.metaobjects.generator.template.TemplateScopeGenerator` wired as an ordinary `` with `