diff --git a/README.md b/README.md index bbfad24768..db9a1ca21f 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ first-week wedge plan — and `meta init` picks up from there. | Kotlin | **Maven Central `8.2.0`** — codegen tier on top of Java: 17 generators (entity, Exposed table, names, relations, repository, output-parser, output-prompt, render-helper, extractor, filter-allowlist, validator, Spring config, storedProc, Spring controller, requirement-tests, api-docs, report-export); 24 / 24 persistence-conformance | [`docs/ports/kotlin.md`](docs/ports/kotlin.md) | [`server/java/codegen-kotlin/`](server/java/codegen-kotlin/) · [`server/java/metadata-ktx/`](server/java/metadata-ktx/) | | C# | **NuGet `1.2.0`** — loader + conformance + EF Core codegen + render engine + `dotnet meta` CLI all shipped | [`docs/ports/csharp.md`](docs/ports/csharp.md) | [`server/csharp/`](server/csharp/) | | Python | **PyPI `1.2.0`** — loader + conformance + render + entity-model codegen + ObjectManager runtime shipped; schema migrations in your own tool or the Node `meta migrate` reference helper (ADR-0015) | [`docs/ports/python.md`](docs/ports/python.md) | [`server/python/`](server/python/) | -| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 584 / 584 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with the `entity`, `client` and `commands` generators (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | +| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 584 / 584 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with eleven generators — the model crate through the sqlx store, the service and its opt-in axum routes (`service-routes`) to a typed client and its commands (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix @@ -336,7 +336,7 @@ metaobjects/ │ ├── java/ # Java port (incl. codegen-kotlin + metadata-ktx) │ ├── csharp/ # C# port │ ├── python/ # Python port -│ └── rust/ # Rust port (ADR-0065 — crates not yet published; cargo meta + entity/client/commands generators) +│ └── rust/ # Rust port (ADR-0065 — crates not yet published; cargo meta + eleven generators through the axum transport) │ └── client/ └── web/ # universal browser packages (React, TanStack, Angular, framework-agnostic) diff --git a/changelog.d/rust-crates-release-path.md b/changelog.d/rust-crates-release-path.md new file mode 100644 index 0000000000..53efc40f99 --- /dev/null +++ b/changelog.d/rust-crates-release-path.md @@ -0,0 +1,6 @@ +- **The Rust crates join the release path (ADR-0065 Amendment 3).** The workspace version moves to + the shared line (1.3.0), and `scripts/release.mjs` publishes the four crates to crates.io after + npm, behind the same confirm, in dependency order, when a file they ship changed since the last + `rust-v*` tag (or they never shipped, or `expected-registry.json` moved); `--crates=publish|skip` + overrides. Its preflight checks the crates.io token and that the version is free before anything + is bumped. `docs/RELEASING.md` names crates.io as the fifth registry. Nothing is published. diff --git a/changelog.d/rust-generators-own-layout.md b/changelog.d/rust-generators-own-layout.md new file mode 100644 index 0000000000..8839acdd96 --- /dev/null +++ b/changelog.d/rust-generators-own-layout.md @@ -0,0 +1,16 @@ +- **Rust generators own their layout, take options and expose their parts (ADR-0063).** A + layout ratchet (`tests/layout_ratchet.rs`) parses every generator source with `syn` and fails + on a hand-typed line break or indentation run; its allowlist can only shrink, and it starts + empty but for six files whose strings are not generated code. Eight `rust` writer-conformance + cases pin the dialect (`use_list`, `doc`, `prose`, `doc_break`, `assign`), each a rustfmt fixed + point under the generated crates' `rustfmt.toml`. An entry in `metaobjects.config.json`'s + `generators` may now be `{"name": ..., "options": {...}}`: `Generator::configure` receives the + options, and the shipped generators take none and refuse any key with + `ERR_UNKNOWN_GENERATOR_OPTION`, also on a run `--generators` narrows. Each shipped generator + has a `*Parts` trait — eleven in all once the layer generators landed (`EntityParts`, + `ClientParts`, `CommandsParts`, `RenderHelperParts`, `OutputParserParts`, `OutputPromptParts`, + `RulesNamesParts`, `ContractTypesParts`, `RepositoryParts`, `ServiceParts`, + `ServiceRoutesParts`) — with one default method per output piece, so an owned + generator overrides one piece and keeps the rest. Generated output is byte-identical but for + one fix: `assign` now moves an array right-hand side to the next line when that is where + rustfmt puts it under those settings. diff --git a/changelog.d/rust-many-to-many-traversal.md b/changelog.d/rust-many-to-many-traversal.md new file mode 100644 index 0000000000..d8a31f1b31 --- /dev/null +++ b/changelog.d/rust-many-to-many-traversal.md @@ -0,0 +1,7 @@ +- **Rust port: many-to-many relationships are traversed (FR-018).** A many-to-many relationship + of a keyed entity gets `_of` in its store module, the related rows read through the + junction in one statement (hetero, directed self-join and `@symmetric` self-join, which keeps a + row relating a record to itself). The junction's keys come from the same derivation the loader's + pairing rule runs, now a public function of the core crate (`derive_m2m_fields`). The persistence + runner runs all 56 scenarios on Postgres, `guarded-update` among them (`meta_store::transition` + takes a transition's `@condition` and ANDs it into the same statement), and its ledger is empty. diff --git a/changelog.d/rust-prompt-tier.md b/changelog.d/rust-prompt-tier.md new file mode 100644 index 0000000000..25783083a8 --- /dev/null +++ b/changelog.d/rust-prompt-tier.md @@ -0,0 +1,9 @@ +- **Rust port's prompt tier: `render-helper`, `output-parser` and `output-prompt`.** Three + generators put the `metaobjects-render` crate (render, the strict JSON parse and the tolerant + `extract`, the output-format fragment) behind typed functions, held to the render, + template-output and extract corpora. They write a crate each beside the model crate: + `_prompts` (a typed render function per prompt), `_parsers` (`parse_` + for a JSON reply, `extract_` for any, and the extract schema) and `_formats` + (the fragment and its descriptor), for every prompt with a `@responseRef` (ADR-0052). `eject` + copies all three, and `gen` checks each body against its payload before it writes a render function. + The generated crates depend on `metaobjects-render` at this release's major and minor. diff --git a/changelog.d/rust-reports-projections-read.md b/changelog.d/rust-reports-projections-read.md new file mode 100644 index 0000000000..a1579f30ae --- /dev/null +++ b/changelog.d/rust-reports-projections-read.md @@ -0,0 +1,10 @@ +- **Rust port: reports and projections are read (FR-044, ADR-0028).** The core crate derives a + report's fields (`metaobjects::report_shape`, FR-044 Table B and C) byte for byte with + `report-shapes.json`. A served read (a concrete projection or report whose read source is a view) + gets a read-only struct in its model crate and a read-only module in its store crate: `list`, + `count`, and `get` for a projection with a key. A view's numbers are read through a cast to their + field's type, since the view's SQL picks the column type. The persistence runner now runs the 24 + report and 3 projection scenarios, and its ledger holds only the three many-to-many ones. A + view-backed projection that an operation returns is now the model crate's type, not a copy in + the contract crate. Clients and commands for read models wait for a Rust transport that serves + them. diff --git a/changelog.d/rust-repository-generator.md b/changelog.d/rust-repository-generator.md new file mode 100644 index 0000000000..b4dede897a --- /dev/null +++ b/changelog.d/rust-repository-generator.md @@ -0,0 +1,12 @@ +- **Rust port's data access: the `repository` generator (ADR-0067 layer 3).** It writes a + `_store` crate per package with a stored entity, on sqlx, for Postgres and SQLite: per + entity the table mapping and typed `list` (the nine filter operators, sort, paging), `count`, + `get`, `create`, `update` and `delete`, and per lifecycle the guarded update + `transition_(id, from, to)`, one conditional `UPDATE` that answers `false` when another + writer moved the row first (ADR-0066 §6). The shared `meta_store` crate holds the statements and + the decode of each column into the model's own types. A single-table subtype writes its + discriminator and reads only its own rows. A Rust runner for the shared persistence corpus runs + it on a throwaway Postgres: every list, get, count, create, update, delete, roundtrip and + single-table scenario passes; the many-to-many, projection and report scenarios are on its + shrink-only ledger, because projections, reports, many-to-many traversal and flattened storage + are not stored yet. diff --git a/changelog.d/rust-rules-names-contract-types.md b/changelog.d/rust-rules-names-contract-types.md new file mode 100644 index 0000000000..708e9802c8 --- /dev/null +++ b/changelog.d/rust-rules-names-contract-types.md @@ -0,0 +1,14 @@ +- **Rust port's rules layers 0 and 1: `rules-names` and `contract-types` (ADR-0067).** Two + generators read the business-rules vocabulary, and each writes nothing for a model without it. + `rules-names` writes a `_rules` crate for a package with a lifecycle or a declared + operation: per entity, each lifecycle's state type (the model's own enum), its states, initial + and terminal states and its transitions, and the commands derived from unclaimed transitions; + then the package's operations (kind, permission, claimed transitions, business errors), every + permission asked about (declared or derived per ADR-0066) and every business error, each as a + closed enum, plus the five codes the enforcing shell answers with. `contract-types` writes a + `_contract` crate for a package with a declared operation: each operation's input and + output types, its business-error enum and its error body (a fixed wire code or one of its own), + the read shape of a projection it returns, and a shared `meta_contract` crate with the wire + error codes, their statuses and the validation and constraint-violation bodies. An entity's + read, create and patch shapes stay in the model crate, which carries no persistence mapping. + Both are listed in the shared generator registry (Rust only for now) and `eject` copies them. diff --git a/changelog.d/rust-service-generator.md b/changelog.d/rust-service-generator.md new file mode 100644 index 0000000000..eaf072bcf1 --- /dev/null +++ b/changelog.d/rust-service-generator.md @@ -0,0 +1,19 @@ +- **Rust port: the `service` generator (ADR-0067 layer 4, ADR-0066 §6).** It writes a + `_service` crate per package with a stored entity: `Service`, generic over the + database pool (Postgres or SQLite) and the actor type, with each derived list (page size 50 unless + `api.pagination` says otherwise, `withCount` for the total), get, many-to-many traversal, create, + update and delete, a command per transition that derives one, and a shell per declared command + and query. Every write runs in one sqlx transaction, or inside a caller's through its `_in` twin, + and runs ADR-0066's checks in order: the row (404), the permission point (403 `forbidden`), the + state (409 `invalid_transition`), the hand-written body, the guarded update (409 + `invalid_transition` or `transition_condition_failed`) and the event hook. The generic update + answers a changed lifecycle field 409 `state_managed`, a create starts in the initial state, and + `@autoSet` timestamps are stamped by the service (ADR-0045 Amendment 1). What an app writes are + traits: `Policy`, `Bodies` (a command answers the move to make or none, and + `BodyError::Business` a declared error), `Hooks` (one `before` and one `after`, told of + the write by the `Before` and `After` enums) and `Events`, the last two with + defaults. The shared `meta_service` crate holds the error codes and statuses. A probe runs the + rules corpus's scenarios through the service on SQLite, with the settings variants checked in + the generated text; the HTTP transport, and the shared API tests over it, come next. The walks + the layer generators share moved into a new engine module, `metaobjects_codegen::layers`, so an + ejected `service` or `repository` calls the same walk the shipped one does. diff --git a/changelog.d/rust-service-routes-transport.md b/changelog.d/rust-service-routes-transport.md new file mode 100644 index 0000000000..66170649a7 --- /dev/null +++ b/changelog.d/rust-service-routes-transport.md @@ -0,0 +1,17 @@ +- **Rust port: the service is served over HTTP (`service-routes`, ADR-0067 layer 5, ADR-0065 + Amendment 7).** A new opt-in generator writes a `_http` crate per package and the shared + `meta_http` crate: `router(service, actor)` returns an axum `Router` over the generated service, + with the derived CRUD, traversal, transition-command and declared-operation routes, the + REST-standard list query (filters with `or`/`and` groups, search, `sort=:asc|desc`, a + default page of 50, `withCount`) and the named 400s. `ActorSource` (or `ActorFn` over the + headers) is the app's authentication, handed to the service untouched. It runs only when + `metaobjects.config.json` lists it: `cargo meta init --transport` adds it, a plain `init` and a + project with no list leave it out, and `gen --list` marks it `[opt-in]`. A credential field (one + with a password view) is never returned. An entity with a read-only view beside its table is + written to the table and read back through the view, so its derived fields are in every answer + (the store's `Table` gains `read`). A field with no `@sortable` is now sortable when it is + filterable, as in TypeScript, so a generated client's sort allowlist can grow: regenerate. + The api-contract corpus runs over HTTP in Rust's generated lane (`core`, `write-through`, + `secret-fields`, `list-query`, `rules` and its settings variants, 77 scenarios; the rest + ledgered), the list-query corpus runs all 95 cases, and `examples/rust-service/` is a whole + tasks service built this way, checked by the `rust` lane. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index b3878015dd..56147b4144 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -24,83 +24,67 @@ Counts are fixture directories (or scenario files, where a corpus is file-shaped regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpora, `find fixtures/ -name "*.yaml" | wc -l` for file-shaped ones. -| Corpus | Fixtures | TS | Java | Kotlin | C# | Python | -|---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 584 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | -| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | -| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | 25 / 26 (1 ledgered: `render-shadowed-dotted-prefix`, Stubble stops a dotted name at the first context holding its first segment) | ✓ | -| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | -| [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | -| [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | -| [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` runs in full in TypeScript and C#, and in no other port until that port's 1.3.0 REST-standard work; `rules/` is TypeScript-only until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | -| [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | -| [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | -| [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 7 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers; `xpkg-value-object-refs` (ruling R52) is run by C# and TypeScript only so far — Java, Kotlin and Python in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ | -| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 30 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/reference-source-conformance/`](../fixtures/reference-source-conformance/) | 6 cases | ✓ (reference implementation) | ✓ | inherits via Java (plus its own codegen exclusion test) | ✓ | ✓ | -| [`fixtures/response-verify-conformance/`](../fixtures/response-verify-conformance/) | 7 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | -| [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | -| [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 6 | ✓ (the emitter is TS-owned) | — | — | — | — | -| [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | -| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | ✓ | planned | -| [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | -| [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | -| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | planned | planned (through Java) | ✓ | planned | -| [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | -| [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | -| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | -| [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases + 23 collection segments (`@collectionName`, `naming.collections`) | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`, `RouteNaming.collectionSegment`) | ✓ | ✓ | -| [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | -| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | -| [`fixtures/check-constraint-conformance/`](../fixtures/check-constraint-conformance/) (the CHECK constraints `meta migrate` derives: name and expression text per dialect) | 1 model, 5 expected files (postgres, sqlite, d1, and both skip-redundant variants) | ✓ (reference, `migrate-ts`) | — (no CHECK in a generated model) | — (same) | ✓ (the EF context declares them; live-Postgres `EnsureCreated` lane) | — (same) | -| [`fixtures/foreign-key-index-conformance/`](../fixtures/foreign-key-index-conformance/) (the indexes `migrate.foreignKeyIndexes` adds: which foreign keys are uncovered, and each index's name per dialect, a name over 63 bytes cut on Postgres; and the name each declared `identity.secondary` / `index.lookup` is created under) | 1 model, 4 expected files (FK and declared, postgres and sqlite) | ✓ (reference, `migrate-ts`; the Drizzle tables declare the declared names) | — (no index in a generated model) | ✓ (the Exposed tables declare them) | ✓ (the EF context declares them) | — (same as Java) | -| [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | -| [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 68 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 12 Python) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | -| [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 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 (ADR-0065) is not a column yet.** The sixth port runs these corpora -today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 584 -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 30 -cases); `reference-source-conformance` (all 6 cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), on both its -`gen` and its `verify` columns, for every case the port can meet (the three it cannot, two -about templates and one about the three-way merge, are named with their reason in its -runner); `validation-conformance`, every case, through the generated `validate()`; -`decimal-wire` and `duration-wire`, every vector, against the code the generated support -crate carries; `render-conformance`, every case but the three ledgered below (`mustache-ng` has its own name lookup, data model and truthiness), `verify-conformance`, all 45 -cases, and `response-verify-conformance`, all 7 (the template gate, `verify --templates`), -`extract-conformance`, all 58 -cases, and `output-prompt-conformance`, all 17 in all three styles with the round trip, in the -`metaobjects-render` crate; 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. 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` (584) is the number of fixtures known to pass, and the -run fails when fewer do. The column joins this table when the port runs the persistence and API-contract corpora. +| Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | +|---|---|---|---|---|---|---|---| +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 584 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (584 / 584, empty ledger) | +| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 18 / 19 (1 ledgered: `yaml-ref-root-escape`, the ADR-0059 root-level `::` rules) | +| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | +| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | 25 / 26 (1 ledgered: `render-shadowed-dotted-prefix`, Stubble stops a dotted name at the first context holding its first segment) | ✓ | 23 / 26 (3 ledgered: `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness`, `mustache-ng`'s lookup, data model and truthiness) | +| [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | +| [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | refuses Jinja | +| [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | ✓ | +| [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | 56 query, `guarded-update` included, through the generated `repository` crates on Postgres (migrations TS-only) | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` runs in full in TypeScript, C# and Rust, and in no other port until that port's 1.3.0 REST-standard work; `rules/` runs in TypeScript and Rust, and in no other port until that port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | generated lane only (generated `service-routes` over SQLite): `core`, `write-through`, `secret-fields`, `list-query` and `rules` with its settings variants, 77 scenarios; the other sub-corpora are on the runner's ledger ([Rust port](ports/rust.md#what-does-not-exist-yet)) | +| [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | ✓ (the generated support crate) | +| [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | ✓ (the `wire` vectors) | +| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | ✓ (the generated `validate()`) | +| [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | — | +| [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 7 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers; `xpkg-value-object-refs` (ruling R52) is run by C# and TypeScript only so far — Java, Kotlin and Python in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | ✓ | ✓ | ✓ | ✓ | ✓ | — | +| [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 | ✓ | ✓ | ✓ | ✓ | ✓ | — | +| [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ (generated `render-helper` crates) | +| [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/provider-composition-conformance/`](../fixtures/provider-composition-conformance/) | 18 (11 error-shape + 4 compose-load + 3 attr-ownership) | ✓ | ✓ | — (JVM registry via Java) | ✓ | ✓ | — | +| [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 30 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | ✓ | +| [`fixtures/reference-source-conformance/`](../fixtures/reference-source-conformance/) | 6 cases | ✓ (reference implementation) | ✓ | inherits via Java (plus its own codegen exclusion test) | ✓ | ✓ | ✓ | +| [`fixtures/response-verify-conformance/`](../fixtures/response-verify-conformance/) | 7 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | ✓ | +| [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | — | +| [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | — | +| [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | — | +| [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 6 | ✓ (the emitter is TS-owned) | — | — | — | — | — | +| [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | ✓ (`list_query_conformance.rs`, the parser `meta_http` ships) | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | ✓ | planned | planned (G-RS-1) | +| [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | — | +| [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — (no `fmt`) | +| [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — | +| [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | planned | planned (through Java) | ✓ | planned | — | +| [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | planned (RS-V2) | +| [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | — | +| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | ✓ | +| [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases + 23 collection segments (`@collectionName`, `naming.collections`) | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`, `RouteNaming.collectionSegment`) | ✓ | ✓ | ✓ | +| [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | the config blocks (`wire_block_corpus`) | +| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | the config blocks (`enums_block_corpus`) | +| [`fixtures/check-constraint-conformance/`](../fixtures/check-constraint-conformance/) (the CHECK constraints `meta migrate` derives: name and expression text per dialect) | 1 model, 5 expected files (postgres, sqlite, d1, and both skip-redundant variants) | ✓ (reference, `migrate-ts`) | — (no CHECK in a generated model) | — (same) | ✓ (the EF context declares them; live-Postgres `EnsureCreated` lane) | — (same) | — (no DDL) | +| [`fixtures/foreign-key-index-conformance/`](../fixtures/foreign-key-index-conformance/) (the indexes `migrate.foreignKeyIndexes` adds: which foreign keys are uncovered, and each index's name per dialect, a name over 63 bytes cut on Postgres; and the name each declared `identity.secondary` / `index.lookup` is created under) | 1 model, 4 expected files (FK and declared, postgres and sqlite) | ✓ (reference, `migrate-ts`; the Drizzle tables declare the declared names) | — (no index in a generated model) | ✓ (the Exposed tables declare them) | ✓ (the EF context declares them) | — (same as Java) | — | +| [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | +| [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | +| [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 76 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 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 (ADR-0065)** joined the table with its service stack. Its ledgers (the metamodel +corpus's `server/rust/metaobjects/tests/conformance-expected-failures.json`, empty; the YAML +and render ledgers; the api-contract runner's list of sub-corpora not built yet) may only +shrink, and 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` (584) is the number of fixtures known to pass, and the run fails when fewer do. +Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a +scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test. +[The Rust port page](ports/rust.md#conformance) has the detail. A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port carries a ledgered divergence. The ledgered YAML fixtures are documented divergences (see the @@ -206,9 +190,10 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). - *Loads strictly in every port.* Each port registers the `metaobjects-ui-web` provider (`view.textarea @rows`, the `view.image` attrs) and `@object` / `@objectAdapter` on `object.*`, loads all three fixtures strictly, and emits `implementedIn` in its manifest, which - byte-matches the canonical in all five ports (`KindOneVocabularyTests` in C#; + byte-matches the canonical in all six ports (`KindOneVocabularyTests` in C#; `registry-conformance.test.ts` in TypeScript; `RegistryManifestConformanceTest` in Java and - Kotlin; `test_registry_conformance.py` in Python). + Kotlin; `test_registry_conformance.py` in Python; `metaobjects/tests/registry_conformance.rs` + in Rust). - *Port-scoped, for comparison* (`ports`, language-specific by nature, never "pending"): `@objectAdapter` (`["java", "kotlin"]`). @@ -255,14 +240,14 @@ port's ORM model carries beside it: Amendment 8). A gate, not a corpus: it has no fixtures of its own, and reads `generator-registry-conformance/registry.json`. -- *Gated in all five ports.* Each port's eject-contract test asserts that every generator it +- *Gated in every port.* Each port's eject-contract test asserts that every generator it ships is in the registry (census), that every registered generator ships eject source unless the shared file exempts it (completeness), and that each generator ejected alone compiles or loads, references nothing in the codegen packages outside the engine surface 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 holds its three generators to + `tests/conformance/test_eject_contract.py`. Rust holds its eleven 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`. @@ -274,18 +259,20 @@ Amendment 8). A gate, not a corpus: it has no fixtures of its own, and reads **Capability requirements** ([features/requirements.md](features/requirements.md)): -- *Vocabulary — gated in all five ports.* The types, their attributes and their closed +- *Vocabulary — gated in all six ports.* The types, their attributes and their closed enums travel in `registry-conformance`'s byte-matched manifest, which every port reproduces exactly, and accept/reject behaviour is pinned by `requirement-*` fixtures in `fixtures/conformance/`. A port that drifts on what it will load fails. -- *Checks — gated in all five ports.* Every port's `verify` runs the requirement gate +- *Checks — gated in five of the six ports.* Every port's `verify` but Rust's runs the + requirement gate ([ADR-0057](../spec/decisions/ADR-0057-requirement-checks-and-tests-in-every-port.md), - which reversed a TypeScript-only split recorded here). `requirement-check-conformance` + which reversed a TypeScript-only split recorded here); Rust's is planned (RS-V2). + `requirement-check-conformance` pins each diagnostic's code, severity, path and message text and the summary counts against the TypeScript reference. Kotlin has no CLI of its own and runs the gate through the Java Maven goal. `verify-conformance` still holds no requirement cases: that corpus is template drift, and the gate has its own. -- *Generated tests — identity gated in all five ports, text in none.* +- *Generated tests — identity gated in those same five ports, text in none.* `requirement-test-identity-conformance` pins which tests a ledger yields, each one's id, witness key, skip state and digest, and what a project's filter is shown. The file a port writes is its reference helper's output and is not a cross-port contract. @@ -333,7 +320,7 @@ manifest contains without moving these boundaries. `schema.postgres.sql` rather than adding a model beside them; only the seed rows are its own (`fixtures/cube-model/canonical/seed.sql`). -**Does the generated code compile** (`codegen-compile-conformance`, all five ports): +**Does the generated code compile** (`codegen-compile-conformance`, all six ports): - *Not a corpus, so it has no row.* It reuses `fixtures/persistence-conformance/canonical/meta.fitness.json` rather than adding a @@ -356,7 +343,9 @@ manifest contains without moving these boundaries. never executes. - *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. + client and commands are driven over HTTP against a local stub in the same test. The + generated prompt, parser and format crates build against the workspace's own + `metaobjects-render`. - *Every port excludes its framework-bound route tier* — TS `routesFile`, C# `RoutesGenerator`, Java `SpringControllerGenerator`, Kotlin `KotlinSpringControllerGenerator`. Those imports are not on an in-memory compile's @@ -408,7 +397,7 @@ fixture that could see it. A split is deliberate when no port makes a claim the have to check; it is a gap when some port already made one. **A hazard for whoever removes an attribute — and it has now fired once.** Contract prose -lives *inside* attr descriptions in `expected-registry.json`, where five ports byte-match it +lives *inside* attr descriptions in `expected-registry.json`, where six ports byte-match it and nothing else gates it. `@trackedBy` still carries "NOT resolved by verify, which does not reach the network". `@verifiedBy` carried "verify checks each name EXISTS and is not skipped; it never runs them" — and that attribute was **retired in `0.24.0` (FR-038)**, which deleted @@ -430,7 +419,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 | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, reference-source, naming, skip, validation, wire-vector, writer, generator-registry, render, verify, response-verify, extract and output-prompt corpora, and the `verify --templates` CLI test; 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, reference-source, naming, skip, validation, wire-vector, writer, generator-registry, render, verify, response-verify, extract, output-prompt, template-output-render, list-query, persistence and api-contract corpora, and the `verify --templates` CLI test; 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. @@ -582,13 +571,15 @@ canonical string, read exactly, filtered exactly and refused past its declared d in a calendar or clock spelling, and filtered and sorted as a span on every engine), `api-settings/` (8, the project's `api` block: `api.pagination`'s default page, `limit_too_large` cap and refused negative `limit`, an empty page for `limit=0`, and -`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, the REST standard's list handling against a real store: search ignores case and `like` does not, `filter[or]`/`filter[and]`, the nesting cap, bare fields, a leading `%`, value formats, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript and C#; the other ports from their 1.3.0 REST-standard work) and `report/` (37, +`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript and Rust; the other ports from their 1.3.0 service work), `list-query/` (21, the REST standard's list handling against a real store: search ignores case and `like` does not, `filter[or]`/`filter[and]`, the nesting cap, bare fields, a leading `%`, value formats, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript, C# and Rust; the other ports from their 1.3.0 REST-standard work) and `report/` (37, FR-044: a view-backed `object.report` is listed, filtered, sorted and paged on its derived fields, answers `POST` with 405 and mounts no `/{id}`; a `@spine` report keeps -a row with no facts, and a measure with `@default` filters and sorts as its default). All 5 ports — TS, Java, -Kotlin, C#, Python — run it in BOTH lanes: a hand-rolled reference server and -the port's own GENERATED API artifact booted over HTTP. `write-through/`, -`secret-fields/`, `enum-default/`, `projection/`, `decimal/`, `duration/` and `report/` run the generated lane only, on all five ports: what +a row with no facts, and a measure with `@default` filters and sorts as its default). The 5 ports with +a reference lane — TS, Java, Kotlin, C#, Python — run it in BOTH lanes: a hand-rolled reference server and +the port's own GENERATED API artifact booted over HTTP. Rust runs the generated lane alone +(see the matrix row above): a hand-rolled server would answer every scenario by construction, and +what is under test is the generator. `write-through/`, +`secret-fields/`, `enum-default/`, `projection/`, `decimal/`, `duration/` and `report/` run the generated lane only, on all five ports (Rust runs two of them, `write-through/` and `secret-fields/`; the rest are on its runner's ledger): what they test is whether a port's generator emits the routes. The `report/` sub-corpus is the one that reads real views, so it runs full stack on Postgres, SQLite and MySQL (`report/schema.sqlite.sql`, `report/schema.mysql.sql`, both TypeScript-produced) in every @@ -611,14 +602,15 @@ case-insensitive extension matching, union-with-de-duplication, and every error condition (an unresolvable path, an unsupported `resource`/`package` kind, and a malformed config — `"expectError": true` pins only that resolution RAISES, since which error code it raises with is deliberately NOT -a cross-port contract; see the corpus README). **All four CLI surfaces run -it** — TypeScript (the reference implementation), C#, Python, and Java (Kotlin +a cross-port contract; see the corpus README). **All five CLI surfaces run +it** — TypeScript (the reference implementation), C#, Python, Java (Kotlin inherits it, since Kotlin has no CLI entry point of its own and runs through -the same Maven plugin as Java): +the same Maven plugin as Java), and Rust (`cargo meta`): `server/typescript/packages/sdk/test/source-resolution-conformance.test.ts`, `server/csharp/MetaObjects.Conformance.Tests/SourceResolutionConformanceTests.cs`, -`server/python/tests/conformance/test_source_resolution_conformance.py`, and -`server/java/metadata/src/test/java/com/metaobjects/config/SourceResolutionConformanceTest.java`. +`server/python/tests/conformance/test_source_resolution_conformance.py`, +`server/java/metadata/src/test/java/com/metaobjects/config/SourceResolutionConformanceTest.java`, +and `server/rust/metaobjects/tests/source_resolution_conformance.rs`. ### `fixtures/reference-source-conformance/` (6 cases) @@ -788,16 +780,17 @@ default-physical-table-name axis has no HTTP-observable surface at all, so it can only be proven at the pluralizer-function level, which is what this corpus does for both axes in one data file. -**All five ports run it** (Kotlin inherits, since `KotlinNaming.collectionSegment` +**All six ports run it** (Kotlin inherits, since `KotlinNaming.collectionSegment` delegates to the same `RouteNaming.pluralize` Java runs): `server/typescript/packages/metadata/test/naming.test.ts`, `server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs`, `server/java/codegen-base/src/test/java/com/metaobjects/generator/util/RouteNamingTest.java` + `server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java` (API-surface and frozen-legacy halves split across the two modules that already -own those two functions), and +own those two functions), `server/python/tests/codegen/test_route_path_naming.py` + -`server/python/tests/unit/test_fr016_source_name_and_kind_aliases.py` (same split). +`server/python/tests/unit/test_fr016_source_name_and_kind_aliases.py` (same split), and +`server/rust/metaobjects/tests/naming_conformance.rs`. ### `fixtures/requirement-check-conformance/` (49 cases) @@ -809,7 +802,7 @@ model with no requirement. The expectations are written from the TypeScript refe a port that disagrees with one is wrong. The case list, and what each pins, is in the [corpus README](../fixtures/requirement-check-conformance/README.md). -**Every port's `verify` is held to it:** +**Every port's `verify` but Rust's is held to it** (Rust's gate is planned, RS-V2): `server/typescript/packages/cli/test/requirement-check-conformance.test.ts`, `server/python/tests/conformance/test_requirement_check_conformance.py`, `server/java/metadata/src/test/java/com/metaobjects/conformance/RequirementCheckConformanceTest.java` @@ -830,8 +823,9 @@ matches in a store is the `list-query/` sub-corpus of `api-contract-conformance/ **Held to it:** `server/typescript/packages/integration-tests/test/list-query-conformance.test.ts` (the source of the expected answers) and `server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs`. **Conformance status:** -TypeScript and C# pass; Java, Kotlin, Python and Rust are pending until their 1.3.0 REST-standard -work lands, and each port's change flips its own entry. The decision is +TypeScript, C# and Rust pass (Rust: `server/rust/metaobjects-codegen/tests/list_query_conformance.rs`, +against the parser its transport ships); Java, Kotlin and Python are pending until their 1.3.0 +REST-standard work lands, and each port's change flips its own entry. The decision is [ADR-0068](../spec/decisions/ADR-0068-list-query-cross-port-contract.md). ### `fixtures/docs-page-conformance/` (4 cases) @@ -861,7 +855,7 @@ It does not pin the text of a generated file, the uncovered warning, or a requir outside ASCII. The case list is in the [corpus README](../fixtures/requirement-test-identity-conformance/README.md). -**All five ports run it:** +**All ports but Rust run it** (Rust's `requirement-tests` generator is planned, RS-V2): `server/typescript/packages/codegen-ts/test/requirement-test-identity-conformance.test.ts`, `server/java/metadata/src/test/java/com/metaobjects/conformance/RequirementTestIdentityConformanceTest.java`, `server/python/tests/conformance/test_requirement_test_identity_conformance.py` and diff --git a/docs/README.md b/docs/README.md index 3b07199217..a12f36dd54 100644 --- a/docs/README.md +++ b/docs/README.md @@ -62,7 +62,7 @@ docs/ ├── kotlin.md ├── csharp.md ├── python.md - └── rust.md # the Rust port: loader, validation, prompt render and reply parser, cargo meta (init/gen/verify/eject) and its three generators + └── rust.md # the Rust port: loader, validation, prompt render and reply parser, cargo meta (init/gen/verify/eject) and its eleven generators, the service stack included ``` If this list and `ls docs/features/` ever disagree, trust the directory listing — diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 05d7ff0bfe..9ec56c5f17 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -14,20 +14,23 @@ > first, see the Java procedure). One route per version, never both. > - **NuGet** → keyless OIDC via the `publish-csharp.yml` workflow: `gh workflow run > publish-csharp.yml` (or push a `csharp-v` tag). +> - **crates.io** → `scripts/release.mjs` publishes the four Rust crates after npm, behind the +> same confirm, with the token `cargo login` stores. See +> [Releasing the Rust crates to crates.io](#releasing-the-rust-crates-to-cratesio). > > Run network commands via the sandbox-disabled shell. **Publish what changed; converge the > number when you do (standing policy since 0.24.5, replacing the version-parity rule of > 0.20.13):** a registry publishes only when it has a changed product file, and when it does it > adopts the **current shared `minor.patch`** — skipping the numbers it sat out. npm / PyPI / -> NuGet on `..

`, Maven on `..

` — only the MAJOR differs, and the offset is +> NuGet / crates.io on `..

`, Maven on `..

` — only the MAJOR differs, and the offset is > permanent (`scripts/maven-coordinate.mjs` is the single derivation; every script imports it). > Concretely: npm `0.25.0` is Maven `7.25.0`, and npm `1.0.0` is Maven **`8.0.0`**. Do not type > a literal `7.` anywhere — at the 1.0 cut it asks Central for a version BELOW the last release. > Two carve-outs: the **13 npm packages still move atomically with each other** (they > cross-depend — that is intra-npm lockstep and it is unchanged), and a change to -> `expected-registry.json` / `metamodelVersion` **forces all four**, because that is the +> `expected-registry.json` / `metamodelVersion` **forces all five**, because that is the > cross-port contract — whatever the release's level, so a vocabulary-adding PATCH publishes -> all four too (ADR-0035 Amendment 5). The rest of this doc is the per-registry procedure. +> all five too (ADR-0035 Amendment 5). The rest of this doc is the per-registry procedure. ## Step 0 (all registries): scan for unmerged work before you cut @@ -86,7 +89,7 @@ step. Each port's eject-contract test fails on a gap that is not listed, so an e deleted before its gap is closed. **Why this is step 0 and not a nicety:** `0.21.1` shipped *without* a `timestampMode` fix that was -already written and sitting on an unmerged branch. Because versions are immutable on all four +already written and sitting on an unmerged branch. Because versions are immutable on all five registries, the only correction was a full coordinated `0.21.2` within the hour — four publishes, an ~11-minute Maven deploy, and a second round of adopter notification, to ship work that already existed. The single shared patch number makes an omission cost four publishes, not one. @@ -253,7 +256,7 @@ Amendment 2). Its last published version is 1.2.3, and it stays on the registry. that run on a `v*` tag and nowhere else. (They were dormant while Actions was off, 2026-09-16 to 09-20, and step 3 above was what gated the cut instead; step 3 still earns its place, because it is the only gate that runs BEFORE the tag.) The ordering - matters because those runs land on the FINAL coordinated tree — all four registries bumped, docs refreshed, payload true — + matters because those runs land on the FINAL coordinated tree — all five registries bumped, docs refreshed, payload true — instead of the npm-only commit, which is a tree that never actually shipped. `publish-npm.yml` triggers on `npm-v*`, not `v*`, so moving the tag does not re-trigger a publish. @@ -296,7 +299,7 @@ what they render is generator output and does not.) | Wire-contract / conformance behavior change of already-valid deployments | FR-036 enforcement | **MINOR**, loud notice (pre-1.0 MINOR *is* the breaking slot) | **`metamodelVersion` MAJOR** (Metamodel 2.0) + package MINOR — see the two-contracts rule below | | Wire behavior fixed to match the documented/conformance contract | 0.19.1 `@min` clamp | PATCH | PATCH | | No changed product file in a port | PyPI/NuGet/Maven at 0.24.4 while npm cuts 0.24.5 | **Do not publish that registry.** It sits the release out and keeps its current version. When it next has a changed file it adopts the shared `minor.patch` then current, skipping the numbers between (publish-what-changed policy, standing since 0.24.5) | same | -| A change to `expected-registry.json` / `metamodelVersion` | any vocabulary move, at any release level — a vocabulary-adding PATCH included | **All four registries publish**, changed file or not — the metamodel is the cross-port contract and every port byte-matches the manifest | same | +| A change to `expected-registry.json` / `metamodelVersion` | any vocabulary move, at any release level — a vocabulary-adding PATCH included | **All five registries publish** (npm, PyPI, NuGet, Maven Central, crates.io), changed file or not — the metamodel is the cross-port contract and every port byte-matches the manifest | same | ### The two-contracts rule (post-1.0; ADR-0035 Amendment 2) @@ -357,7 +360,7 @@ gate. **Answering that question is a human step in every release.** **When you cut a release that moves `metamodelVersion`:** 1. `node scripts/check-metamodel-version.mjs --set ` — it writes the manifest - **and all four port constants** in one go (Kotlin emits through the JVM's). A partial + **and all five port constants** in one go (Kotlin emits through the JVM's). A partial edit is caught by `registry-conformance`, but only in the lane for the port you forgot, so do not hand-edit. Then re-run the corpus in every port. 2. The changelog entry MUST say the metamodel version moved, and to what. Post-1.0 the @@ -415,7 +418,7 @@ did not track what an adopter experiences either, and it pushed additions to shi into a minor or a long-lived release line. **`metamodelVersion` moves by the same decision**, and every move of it, at any release level, -publishes all four registries. See "The two-contracts rule" above for its patch component and +publishes all five registries. See "The two-contracts rule" above for its patch component and what the gate checks until that is implemented. **Do not invert the caret rule.** "Pre-1.0 `^0.22.x` resolves `<0.23.0`, so a consumer adopts @@ -626,10 +629,10 @@ are its check. **Before `bun publish`: run the FULL local CI on the release commit and confirm it is green.** Its `ts-slow` section carries the real-Postgres migrate gate. Publishing is -irreversible on all four registries, and the `v*` tag is pushed *after* `bun publish`, so +irreversible on all five registries, and the `v*` tag is pushed *after* `bun publish`, so even though Actions is on (since 2026-09-20), a tag-triggered `integration-tests` run could never be the pre-publish gate. This is the last gate that can precede the irreversible step, -and it is the only one that runs before it, so the flagless script (all five ports, the +and it is the only one that runs before it, so the flagless script (all six ports, the reactor, the docker matrix) is what you run, not `--quick`. Run it on the commit you will tag, after every fix for this release has merged: the `python-v`, `csharp-v` and `java-v` tags must sit on that same commit, so cut the npm release commit from `main` only once the @@ -941,6 +944,52 @@ Project `metaobjects` → **Settings → Publishing → Add a new GitHub publish dist/*` from `server/python`, and then do not push a `python-v*` tag for that version. 4. **Verify:** `curl -s https://pypi.org/pypi/metaobjects/json | python3 -c "import sys,json;print(json.load(sys.stdin)['info']['version'])"`. +# Releasing the Rust crates to crates.io + +The four Rust crates ([ADR-0065](../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) +Amendment 3) ship to crates.io on the shared `..

` line, from one workspace version +(`[workspace.package]` in [`server/rust/Cargo.toml`](../server/rust/Cargo.toml)): + +| Crate | What it is | +|---|---| +| `metaobjects` | the loader, registry and canonical serializer | +| `metaobjects-render` | prompt render, the reply parser and the output-format fragment | +| `metaobjects-codegen` | the run engine and the shipped generators | +| `metaobjects-cli` | the `cargo-meta` binary (`cargo meta`) | + +**`scripts/release.mjs` publishes them; there is no separate procedure.** The rules it applies +live in [`scripts/lib/rust-release.mjs`](../scripts/lib/rust-release.mjs) and are tested by +`scripts/test-rust-release.mjs` (the `gates` lane runs it): + +1. **Whether they ship.** Publish what changed: the crates publish when a file they ship (a + crate's sources, data, build script or manifest, or the workspace manifest and lockfile, + but not tests, examples, benches or baselines) changed since the newest `rust-v*` tag, and + always when `expected-registry.json` moved. With no `rust-v*` tag they have never shipped, + and the cut publishes them. `--crates=publish` or `--crates=skip` overrides the decision; + the preflight prints the reason either way. +2. **Preflight**, with npm's, before anything is bumped: a crates.io token (from `cargo login` + or `CARGO_REGISTRY_TOKEN`), and the version free on every crate. crates.io versions are + permanent: a yank hides a version from new resolutions and does not free its number. +3. **Bump**: the workspace version and every sibling crate's version requirement move to the + release's, then `cargo update --workspace` updates the lockfile. The commit carries them + with npm's. +4. **Pack-verify**: `cargo publish --dry-run --workspace` packages each crate and builds it + against its siblings' tarballs, so a crate that builds only from a path in the checkout + fails before the confirm. +5. **Publish**, after npm: `cargo publish -p ` in dependency order (`metaobjects`, + `metaobjects-render`, `metaobjects-codegen`, `metaobjects-cli`). cargo waits for each crate + to reach the index before it returns, so the next one resolves it. +6. **Tag** `rust-v` with the other ports' tags, before `finish-release.mjs`. The next + cut compares against it. + +The generated prompt crates name `metaobjects-render` by this release's major and minor +(`metaobjects_render::REQUIREMENT`), so code generated by 1.3.x needs a 1.3 or later render +crate and never resolves to an older one. + +**Nothing is published without the owner's go.** That holds for crates.io as for every +registry. A crate name is reserved only by publishing it, and the CLI's package name is +`metaobjects-cli` because `cargo-meta` is held by an unrelated crate. + # Releasing the Java/Kotlin modules to Maven Central The 14 `com.metaobjects:*` modules (15 artifacts, counting the parent POM) ship to **Maven Central via the Sonatype Central Portal**, diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 24961f8d40..8417876cb5 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -197,8 +197,8 @@ TypeScript's wire names unchanged. Two corpora hold every port to them: The decision is recorded in [ADR-0068](../../spec/decisions/ADR-0068-list-query-cross-port-contract.md). -**Conformance status:** TypeScript and C# pass both corpora; Java, Kotlin, Python and Rust are -pending until their 1.3.0 REST-standard work lands. Each port's change flips its own entry, and its +**Conformance status:** TypeScript, C# and Rust pass both corpora (Rust over its generated axum +transport); Java, Kotlin and Python are pending until their 1.3.0 REST-standard work lands. Each port's change flips its own entry, and its runner holds it to them from then on; [`docs/CONFORMANCE.md`](../CONFORMANCE.md) says which ports run them today. @@ -331,9 +331,11 @@ each handler they register instead; an `HTTPException` is rethrown to your still name a wired routes generator with no page size (never a failure). **Every port reads it:** the TypeScript Fastify and Hono routes, the C# minimal-API routes, the - Java and Kotlin Spring controllers and the Python FastAPI routers, packaged and ejected (an owned + Java and Kotlin Spring controllers, the Python FastAPI routers and the Rust axum routes + (`service-routes`), packaged and ejected (an owned copy picks it up when it is re-ejected). `fixtures/api-contract-conformance/api-settings/` pins - it in the generated lane of every port. Every per-port difference of this kind is collected in + it in the generated lane of every port (Rust's api-settings scenarios are on its runner's + ledger for now). Every per-port difference of this kind is collected in [What differs by language](language-differences.md). - `withCount=1` — opt-in flag that switches the list response from `[...]` to `{ rows: [...], total: }` (needed for grid diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 9d19f278c4..3b67c181cf 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -18,16 +18,19 @@ A requirement can claim an operation or a transition. The flat generators genera the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its generator list as it adds any generator. The first is `rules-names`, which writes the states, transitions, permissions and error codes as constants, in TypeScript (see -[The names layer](#the-names-layer-typescript)) and C#. The second is `contract-types`: in +[The names layer](#the-names-layer-typescript)), C# and Rust. The second is `contract-types`: in TypeScript it writes the shapes and errors an operation takes and returns (see -[The contract types layer](#the-contract-types-layer-typescript)), and in C# so far each -entity's create and update records ([C# port](../ports/csharp.md)). The TypeScript runtime makes the +[The contract types layer](#the-contract-types-layer-typescript)), and in C# and Rust so far each +entity's create and update records ([C# port](../ports/csharp.md), [Rust port](../ports/rust.md)); +the Rust generators write only for a package that declares rules. The TypeScript runtime makes the guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the shared persistence scenario `guarded-update.yaml`. The service layer starts in TypeScript: `service` writes each package's derived list, get, create, update and delete, every write in one transaction with the declared write rules, behind a thin Fastify transport (`service-routes`) or Hono transport (`service-routes-hono`) that answers the shared API tests as the flat routes do (see -[The service layer](#the-service-layer-typescript)). It also writes a command per transition and a +[The service layer](#the-service-layer-typescript)). The Rust `service` generator writes the same +operations and checks over its generated store, behind the opt-in axum transport `service-routes`, +which answers the same shared API tests ([Rust port](../ports/rust.md)). It also writes a command per transition and a shell per declared command and query, and enforces at run time what this page declares: the permission point, the state check, the guarded update, `state_managed` and the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are later 1.3.0 work. A lifecycle in a project that wires no service generator covering it is diff --git a/docs/features/cli.md b/docs/features/cli.md index da70bb0d8a..8b68744d9a 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -43,7 +43,7 @@ command surface splits in two: | Java/Kotlin scaffold | Maven plugin | `mvn metaobjects:init` | writes the port-neutral `.metaobjects/config.json` and an empty `metaobjects/meta.app.json`, each only when missing; it never edits `pom.xml` and wires no generator. Details and the `-Dmeta.init.withDocs=true` opt-in: [docs/ports/java.md](../ports/java.md) | | Java/Kotlin verify | Maven plugin | `mvn metaobjects:verify -Dmeta.verify.mode=codegen\|templates\|deps` (`metaobjects:verify`) | parameter-driven ADR-0021 D2 modes (one goal covers BOTH Java + Kotlin): unset (default — `codegen` and `templates`; the template gate is skipped with a note when `templateRoot` is unset) / `codegen` (regen + fail on drift vs committed output, generator-neutral) / `templates` (`{{field}}`↔payload drift via the render `Verify` engine) / `deps` (opt-in dependency drift, the `path` transport only). `db` rejected ("schema verify is the migrate engine, ADR-0015") | | Python codegen | console-script | `metaobjects gen` / `verify --codegen` / `verify --templates` | `[project.scripts] metaobjects` — **not** `meta` (that's the Node schema CLI); ships the ADR-0021 D2 subverbs (`--db` rejected, exit 2). **The generator list is `metaobjects.config.yaml`** (ADR-0034 Amendment 9, [below](#declarative-config-metaobjectsconfigyaml--python-codegen)): `gen` and `verify --codegen` run each target's `generators` (and its `templateSpec`, the declarative Mustache template-codegen surface shared with C#) into its `outDir`, and with no config they exit 2 and write nothing. `--generators` only narrows the list to declared entries. `metaobjects docs` was removed in 1.1.0: it prints the line that points at [the migration section](migrations/docs-are-generators.md#python) and exits 2 | -| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, unpublished; installed from a checkout) | `cargo meta init` / `gen` / `verify --codegen` / `verify --templates` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Three generators ship, each writing one crate per metadata package: `entity`, `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1). `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` runs the gates (`--codegen`, which renders in memory and exits 1 on drift, `--templates` and the rules gate) (`--full`, or a set `CI`, never answers from the stored key); `--templates` is the template drift gate (`template.*` bodies under `prompts/`, or `--prompts

`, against their payload value objects, plus each prompt's reply), and a bare `verify` runs it too; `--db` and `--deps` are rejected, exit 2. **The generator list is the shipped three until the project owns one**: `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | +| Rust codegen (ADR-0065) | `cargo-meta` (`metaobjects-cli`, published to crates.io with the other Rust crates on the shared release line, [Releasing](../RELEASING.md); also installable from a checkout) | `cargo meta init [--transport]` / `gen` / `verify --codegen` / `verify --templates` / `eject` | A Cargo subcommand, invoked `cargo meta` so it never shadows the Node `meta`. Eleven generators ship, each writing one crate per metadata package: the six ADR-0067 layers (`entity`, `rules-names`, `contract-types`, `repository`, `service`, and the opt-in axum transport `service-routes`, which `init --transport` lists), `client` and `commands` (the last Rust-only by decision, ADR-0065 Amendment 1), and the three prompt-tier generators. The project chooses which run in `metaobjects.config.json`. `gen` skips a run whose key matches (ADR-0064), writes only changed bytes, removes a generated file nothing emits any more, and refuses to overwrite or delete a hand-edited generated file (exit 1). `verify` ships the ADR-0021 D2 subverbs it can: a bare `verify` runs the gates (`--codegen`, which renders in memory and exits 1 on drift, `--templates` and the rules gate) (`--full`, or a set `CI`, never answers from the stored key); `--templates` is the template drift gate (`template.*` bodies under `prompts/`, or `--prompts `, against their payload value objects, plus each prompt's reply), and a bare `verify` runs it too; `--db` and `--deps` are rejected, exit 2. **To own a generator**, `cargo meta eject ` writes a `codegen/` crate (`Cargo.toml`, `main.rs`, `generators/.rs`), and `gen` / `verify` then build and run that crate; `--generators` only narrows the list. No `fmt`, no template generator and no `migrate`. `cargo meta --help` lists the options; [the Rust port page](../ports/rust.md) has the detail | ## `verify` is one verb with explicit subverbs (ADR-0021 D2) diff --git a/docs/features/reporting.md b/docs/features/reporting.md index aeec148153..81b606a873 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -3,14 +3,15 @@ _`dimension` / `measure` / `segment` / `object.report` — declare what a dashboard groups by and counts, as metadata, validated when the model loads._ -**Status:** registered and loader-validated in all five ports (TypeScript, C#, Java, -Python, Kotlin through Java). Arrived with **metamodel 1.1** (FR-044). +**Status:** registered and loader-validated in all six ports (TypeScript, C#, Java, +Python, Kotlin through Java, Rust). Arrived with **metamodel 1.1** (FR-044). **What a report becomes.** A report that declares a read-only `source.rdb` of `@kind: view` is **lowered to a SQL view**: `meta migrate` creates it (Postgres, SQLite and D1; MySQL SQL comes from `buildReportViews`, see [MySQL](#mysql)), every port reads it through its own runtime, and every port's generators **serve it over REST**: one read-only list route, with -the standard filter, sort and paging on the derived fields. +the standard filter, sort and paging on the derived fields. (The Rust transport serves no +report yet; see [the Rust port](../ports/rust.md#what-does-not-exist-yet).) [What a report lowers to](#what-a-report-lowers-to) is the column contract and [How a report is served](#how-a-report-is-served) is the REST one. A report with no `source.*` stays inert: it is a checked statement of intent. No generator, migration or runtime acts on diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 2722832195..ab7198d178 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -1,10 +1,11 @@ # Capability requirements _`requirement.functional` / `requirement.architectural` — record what your system is -supposed to do, as metadata, checked by `verify` in every port._ +supposed to do, as metadata, checked by `verify` in every port that ships the gate._ -**Status:** registered vocabulary in all five ports (TypeScript, Java, C#, Python, Kotlin). -The requirement gate runs in every port's `verify`, and every port ships a +**Status:** registered vocabulary in all six ports (TypeScript, Java, C#, Python, Kotlin, Rust). +The requirement gate runs in every port's `verify` but Rust's, where it is planned (RS-V2), +and every port but Rust ships a `requirement-tests` generator. The authoring lint is TypeScript-only. The vocabulary is a provider pack, composed by default; what leaving it out does is in [Where vocabulary lives](extending-with-providers.md#where-vocabulary-lives). @@ -337,7 +338,8 @@ judgements the ledger exists to record, and no check reaches them. ## The gate in every port -The gate is the same in all five ports. Each port's `verify` runs it on every run, with no +The gate is the same in the five ports that have it (TypeScript, Java, Kotlin, C#, Python; +Rust's is planned, RS-V2). Each port's `verify` runs it on every run, with no subverb to ask for it, from the port's own core library ([ADR-0057](../../spec/decisions/ADR-0057-requirement-checks-and-tests-in-every-port.md)). A shared corpus, @@ -351,6 +353,7 @@ message text of each diagnostic, and the summary counts. | Python | `metaobjects verify` | `metaobjects verify — requirements:` | | Java, Kotlin | `mvn metaobjects:verify` (one goal for both, in either mode) | `metaobjects:verify — requirements:` | | C# | `dotnet meta verify` | `dotnet meta verify — requirements:` | +| Rust | planned (RS-V2) | — | A bare `dotnet meta verify` runs the requirement gate with the other default gates, and needs a `prompts/` or `templates/` directory (else it exits 2 before any gate runs); naming @@ -521,7 +524,7 @@ Pair it with `@trackedBy` to link the ticket it will be built under. **This is a recommended approach, not a contract.** The `requirement-tests` generator, its default renderer and the witness model described here are a reference helper ([ADR-0034 Amendment 3](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md#amendment-3-2026-09-22--generators-are-reference-helpers-the-core-is-what-metaobjects-guarantees)). -Every port ships one and every port can eject it, and an application may change its copy or +Every port but Rust ships one and every port that ships it can eject it, and an application may change its copy or replace it. The checks in `verify` are the part MetaObjects guarantees. They are not ejectable in any port, because they are the contract the ports share. diff --git a/docs/features/source-kinds.md b/docs/features/source-kinds.md index 2d1499d5da..99ffde3331 100644 --- a/docs/features/source-kinds.md +++ b/docs/features/source-kinds.md @@ -64,7 +64,7 @@ there and are excluded from the write codecs); reads route to the view; the `CRE is emitted by `meta migrate` from the **same assembly logic** as a projection view — one emitter, two hosts. -> **Status — shipped in all five ports.** Both halves have landed: the schema/write half +> **Status — shipped in all six ports.** Both halves have landed: the schema/write half > ([#213](https://github.com/metaobjectsdev/metaobjects/issues/213)) keeps derived fields OFF > the write table and emits the replica view (verified by a real-Postgres round-trip), and the > codegen READ half ([#214](https://github.com/metaobjectsdev/metaobjects/issues/214)) routes diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index e14dd56c1a..473edd2839 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -728,7 +728,7 @@ served after codegen that names a variable the payload lacks (`{{nmae}}` for `na it for a Mustache body in TypeScript, C#, Java (and so Kotlin), Python and Rust (the `metaobjects-render` crate), and for a Jinja body in TypeScript and Python. A present `null` still renders empty, and a section over an absent name still renders nothing. The generated render helpers (the `template.output` helper and the -`template.prompt` handle, in all five ports) carry the payload's field tree, so the same miss is +`template.prompt` handle, in all six ports) carry the payload's field tree, so the same miss is caught in text served after codegen. Passing the field tree to the engine (`verify` in TypeScript, Java, Kotlin and C#; `verify=` in Python) also checks names against the declared fields. Pinned by [`fixtures/template-output-render-conformance/runtime-drift/`](../../fixtures/template-output-render-conformance/runtime-drift/), diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 80881619db..9b9eca7b3a 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -3,9 +3,12 @@ The Rust port is a full language of 1.3.0 ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md)). 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`, `verify --templates` and `eject`. Three generators -ship: `entity`, `client` and `commands`, and a project chooses which of them run in -`metaobjects.config.json`. The four crates are **ready to publish but not published**: they package and +codegen loop on a JSON or YAML model: `init`, `gen`, `verify --codegen`, `verify --templates` and `eject`. Eleven +generators ship, from the model crate through the store, the rules, the service and its axum routes +to a typed client and its commands, and a project chooses which of them run in +`metaobjects.config.json`. A generated service passes 77 scenarios of the shared API-contract corpus +over HTTP (see [Conformance](#conformance)); [`examples/rust-service/`](../../examples/rust-service/README.md) +is a whole app built that way. The four 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. @@ -31,7 +34,8 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Reply parser | `metaobjects_render::extract::extract` reads a typed answer out of a model's reply (FR-010, FR-011): fences, prose, comments, trailing commas and cut-off values tolerated, every declared field classified (`EXTRACTED`, `DEFAULTED`, `LOST_OPTIONAL`, `LOST_REQUIRED`, `MALFORMED`) and coerced to its kind, under a `STRICT`, `NORMAL` or `LOOSE` tolerance. `metaobjects_render::prompt::render_output_format` writes the output-format fragment that asks for that answer, in the `guide`, `inline` and `exampleOnly` styles. | | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | -| Code generation (`cargo meta`) | The run engine, three generators (`entity`, `client`, `commands`), the codegen drift gate and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Report shapes | `metaobjects::report_shape::report_shape` derives an `object.report`'s fields (FR-044 Table B, with Table C's `required`): each dimension and measure, its subtype, and the `@of` field it takes its type from. It byte-matches `fixtures/persistence-conformance/report-shapes.json`, as every port does. | +| Code generation (`cargo meta`) | The run engine, eleven generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -51,7 +55,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), 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 init [--project ] [--transport]` | 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)). `--transport` adds the opt-in `service-routes` generator to that list. 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] [--templates] [--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` runs that gate alone. `--templates` is the template drift gate: each `template.*` body (under `prompts/`, or `--prompts `) against its payload value object, and each prompt's `@responseRef` reply; a bare `verify` runs it too, and a Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`). 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` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. An existing copy is refused; `--force` replaces it with the reference, and leaves a copy that already matches untouched. `--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). | @@ -63,19 +67,25 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log 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: +`metaobjects.config.yaml`). `cargo meta init` writes every shipped generator but the opt-in +transport, `service-routes`, which `cargo meta init --transport` adds; delete a line to stop running +one, and no eject is needed: ```json -{ "generators": ["entity", "client", "commands"] } +{ "generators": ["entity", "client", "commands", "render-helper", "output-parser", "output-prompt"] } ``` -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 +The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a +name, or `{"name": "", "options": {...}}` for a generator that takes options; the +generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, +naming the options it takes). The shipped generators take none, so any option given to one fails the +run, also a run `--generators` narrows to other generators. A project with no such file runs every +generator but `service-routes`, which runs only when it is listed: an HTTP server is a choice the +project makes, not a default. 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. +builds on (`client`, `render-helper` and `output-parser` need `entity`; `commands` needs `entity` and `client`; each layer needs the one beneath it, up to `service-routes`, which needs `service`). `cargo meta gen --list` shows each generator +as `[configured]` or `[not configured]`, marks the opt-in one `[opt-in]`, 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. @@ -97,14 +107,29 @@ generated/ shop/ entity the model: structs, enums, create and patch bodies, validate() shop_client/ client a typed HTTP client and list query per served entity shop_cli/ commands clap commands over the client + shop_prompts/ render-helper a typed render function per template (when the package has templates) + shop_parsers/ output-parser a strict parse and a tolerant extract per responding prompt + shop_formats/ output-prompt the output-format fragment per responding prompt + shop_rules/ rules-names lifecycles, commands, operations, permissions, business errors (when the package declares rules) + shop_contract/ contract-types each operation's input, output and errors (when the package declares operations) + shop_store/ repository list, count, get, create, update, delete and the guarded update per stored entity, on sqlx + shop_service/ service each operation in one transaction, with the rules checks, over the store + shop_http/ service-routes the axum routes over the service (when listed) meta_support/ entity exact decimals, durations, patch helpers, the validation checks meta_client/ client the HTTP transport (reqwest), errors, the query builder meta_cli/ commands what a command uses to build a body and a query + meta_store/ repository the table descriptor, filters, and the Postgres and SQLite statements + meta_service/ service the error codes and statuses, the transaction and the guarded move + meta_http/ service-routes the list query parser, the body checks and the error responses ``` The generated crates depend on each other by path and on ordinary crates.io crates (`serde`, -`serde_json`, `reqwest`, `clap`). **They import nothing from MetaObjects**: the shared code is written -into the three `meta_*` crates as source you can read and change. Add the crates you want to your +`serde_json`, `reqwest`, `clap`, `sqlx`, `axum`). **The model, client and command crates import nothing from +MetaObjects**: the shared code is written into the `meta_*` crates as source you can read and +change. The three prompt-tier crates import `metaobjects-render`, an ordinary Apache-2.0 library (the +render engine and the reply parser), as every port's prompt tier imports its render package. It is not +on crates.io yet, so until it is, point a `[patch.crates-io]` entry at a checkout's +`server/rust/metaobjects-render`. Add the crates you want to your workspace as path dependencies: ```toml @@ -122,6 +147,7 @@ under, so `cargo fmt` over the output changes nothing. | In the model | In Rust | |---|---| | a concrete `object.entity` or `object.value` | a `pub struct` with every effective field (inherited ones included), `serde` derives | +| a served read: a concrete `object.projection` or `object.report` whose read source is a view | a read-only `pub struct`, with no create or patch body. A report's members are its dimensions, then its measures, each typed as FR-044 Table B derives it (a dimension and a `min`/`max` as their `@of` field, a `count` as `i64`, a ratio as `Decimal`, a `sum` of an int as `i64`) and an `Option` unless Table C says the column is never null | | an entity | also `Create` (what a caller sends: no generated key, no read-only or derived member) and `Patch` (every member optional; a nullable member tells "set to null" from "leave alone") | | a `field.enum` | a `pub enum` that serializes as the member symbols | | a field that is not `@required` | `Option`; an array is `Vec`; a `field.map` is `BTreeMap` | @@ -186,7 +212,8 @@ The transport is `reqwest` with its default features plus `json` and `query`, wr `meta_client` crate. A project that wants another HTTP stack or TLS backend changes that one crate, which it owns. -Not generated yet: clients for `object.projection` and `object.report` routes. +Not generated yet: clients (and commands) for `object.projection` and `object.report` routes. The +Rust transport serves neither yet (see [What does not exist yet](#what-does-not-exist-yet)), so they wait for it. ### `commands`: command-line commands over the client @@ -224,6 +251,236 @@ refused, not dropped. `commands` with `rust` as their only port, so the difference is stated in the one place every port checks itself against, not left to be discovered. +### `render-helper`: a render function per template + +For each `template.output` and `template.prompt` the generator writes a typed function in a +`_prompts` crate. A document template (the default `@kind`, and every prompt) gets +`render_(&payload, &provider) -> Result`, escaped for its `@format` and held +to its `@maxChars`. An email template gets one returning an `EmailDocument`: the subject and the text +body rendered as text, the HTML body as HTML. The payload is the value object's own struct from the +`entity` crate ([ADR-0056](../../spec/decisions/ADR-0056-value-object-types-are-generated-once.md)). + +```rust +use metaobjects_render::FilesystemProvider; + +let provider = FilesystemProvider::new("prompts"); +let text = shop_prompts::render_order_summary(&summary, &provider)?; +``` + +**The drift gate runs when you generate.** Each body is read from the project's template directory +(`prompts/` when it exists, else `templates/`) and checked against the payload's fields, nested value +objects included. A variable the payload does not have fails `cargo meta gen` with +`ERR_VAR_NOT_ON_PAYLOAD`, naming the template, the reference and the variable. The field tree is also +written into the function, and every render checks the body again, so a body edited after generation, +or served by another provider, fails the render instead of rendering a blank. A body is an input of +the generator: editing one regenerates the crate even when the model did not change. + +### `output-parser` and `output-prompt`: the reply to a prompt + +A `template.prompt` with `@responseRef` names the value object its answer is read into +([ADR-0052](../../spec/decisions/ADR-0052-template-direction-outbound-vs-inbound.md)). `output-parser` writes, in a +`_parsers` crate: + +- `parse_(text) -> Result`, the strict parse: the reply must be exactly + the JSON of a `T`. A prompt whose `@responseFormat` is `xml` has none + ([ADR-0053](../../spec/decisions/ADR-0053-inbound-response-format.md)). +- `extract_(text, &opts) -> Extracted`, the tolerant read of a raw model reply. It never + fails: `value` is the answer when the extracted fields make a complete `T`, and `outcome.report` + classifies every field either way. +- `_schema()`, the extract descriptor both read with, derived from the response object as every + port derives it: nested value objects, numeric ranges and element counts from the field's + validators, `@enumAlias`, `@coerceDefault`, `@default`, `@normalize` and `@xmlText`. + +`output-prompt` writes, in a `_formats` crate, `render__format(&overrides) -> String`: +the part of the prompt that tells the model how to shape its answer, in the reply's syntax and the +prompt's `@promptStyle` (`guide`, `inline` or `exampleOnly`), with each field's `@example`, +`@instruction` and `@enumDoc`. Its root is the response object's name, the root the parser looks for. + +```rust +let fragment = shop_formats::render_judge_format(&PromptOverrides::default()); +let reply = call_the_model(&format!("{prompt}\n\n{fragment}"))?; +let got = shop_parsers::extract_judge(&reply, &ExtractOptions::default()); +match got.value { + Some(verdict) => use_it(verdict), + None => log_the_report(&got.outcome.report), +} +``` + +### `rules-names` and `contract-types`: the rules layers + +The business-rules vocabulary ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) +gets the first two layers of [ADR-0067](../../spec/decisions/ADR-0067-layering-and-the-service-seam.md). +Both write nothing for a package that declares no lifecycle and no operation, so turning them on +changes nothing for a model without rules. + +`rules-names` (layer 0) writes a `_rules` crate of names hand-written code can match on: + +- a module per entity with a lifecycle, and in it a module per lifecycle field: `State` (the model + crate's own enum, so a value read off a record compares directly), `FIELD`, `STATES`, `INITIAL`, + `TERMINAL` and `Transition` (`name()`, `from()`, `to()`), plus `Command`, the commands derived + from the transitions no operation claims, with the permission each asks about; +- `Operation` (`kind()`, `permission()`, `transitions()`, `errors()`), `Permission` (every + permission the package asks about, declared or derived: `.` and + `..`), `BusinessError` and `ShellError` (the five codes the + enforcing shell answers with). Each is a closed enum with `ALL`. + +`contract-types` (layer 1) writes a `_contract` crate. Its `operations` module has, per +operation, `Input` and `Output` (the model's own types, a `Vec` for `@many`), +`BusinessError` (its declared `@errors`, or `NoBusinessError`) and `Error`, the error body +whose code is a fixed one or one of its own. A projection an operation returns gets its read shape +in that crate, unless it is view-backed: then it is the model crate's, and the operation names that. The shared `meta_contract` crate holds the wire error contract: `ErrorCode` with +each code's HTTP status, `ErrorBody`, `ValidationErrorBody` and `ConstraintViolationBody`. An +entity's read, create and patch shapes, with `validate()`, are the model crate's; it carries no +persistence mapping, so it already is the contract. + +```rust +let body: DecideError = serde_json::from_slice(&response)?; +match body.error { + OperationCode::Business(DecideBusinessError::OverBudget) => ask_for_less(), + OperationCode::Fixed(code) => fail(code.status()), + OperationCode::Business(DecideBusinessError::AlreadyDecided) => refresh(), +} +``` + +### `repository`: data access on sqlx + +`repository` ([ADR-0067](../../spec/decisions/ADR-0067-layering-and-the-service-seam.md) layer 3) +writes a `_store` crate with a module per entity that has a source, and per served read +(a view-backed projection or report). Each module has `TABLE`, the physical mapping (table, schema, key, and each field's column and storage +kind, under the project's `naming` strategies and every `@table`/`@column`), and typed functions +over it: + +- `list(c, &Query)` (a `Filter` of the nine operators, sort and paging), `count(c, Option<&Filter>)` + and `get(c, id)`, which a report (it has no key) does not get; +- `create(c, &XCreate)`, `update(c, id, &XPatch)` (`None` when there was no row) and + `delete(c, id)` (`false` when there was none), for an entity whose source is writable. A + projection and a report are read only; +- per lifecycle (ADR-0066), the guarded update `transition_(c, id, from, to)`: one + `UPDATE ... WHERE key = id AND state IN (from)`, `false` when no row matched because it is gone + or another writer moved it first. It decides nothing: which move is legal, and who may make it, + is the service's (layer 4). Underneath it is `meta_store::transition`, which also takes a + transition's `@condition` (a `meta_store::Condition`, the CHECK subset: the six comparisons, the + null tests, and, or, not and coalesce) and ANDs it into the same statement; a literal compared + with a field is written in that field's stored form, so an int-backed enum's member is its integer. + +`c` is a `sqlx::PgConnection` or a `sqlx::SqliteConnection` (a transaction derefs to one), through +`meta_store::Conn`; the shared crate's `postgres` and `sqlite` features pick the engines. Rows come +back as the model crate's own types, which stay free of sqlx. A subtype in a single-table +hierarchy writes its discriminator itself and reads only its own rows. Field names in a filter or +sort are the model's, checked at run time; which fields a caller may filter on is the transport's +choice, not the store's. + +```rust +use meta_store::{Filter, Query}; +use shop_store::order; + +let mut c = sqlx::PgConnection::connect(&url).await?; +let page = order::list(&mut c, &Query { + filter: Some(Filter::from_json(&json!({ "status": { "eq": "NEW" } }))?), + limit: Some(50), + ..Query::default() +}).await?; +// When `status` has transitions, it is a lifecycle and gets its guarded update: +if !order::transition_status(&mut c, id, &[OrderStatus::New], OrderStatus::InFlight).await? { + // someone else moved it first +} +``` + +A view decides its own column types (`AVG` of an integer is `NUMERIC` on Postgres), so a served +read's numbers are read through a cast to their field's type, and a report's column is its derived +field's name under the project's column strategy. + +A many-to-many relationship of a keyed entity gets `_of(c, id)`: the related rows, +read through the junction in one statement, in no order. The junction and its two keys are the +ones the loader's pairing rule derives (`metaobjects::validate::relationships::derive_m2m_fields`), +so a relationship that loads is one the store can follow. A `@symmetric` self-join answers from +both sides of a row, and a row relating a row to itself answers that row. + +Not stored yet: a `@storage: flattened` field is refused at generation (`ERR_UNSUPPORTED`). + +The store is held to the shared persistence corpus (`fixtures/persistence-conformance`): +`tests/persistence_conformance.rs` generates the corpus model, starts a throwaway Postgres +(`docker run --rm` on a tmpfs, removed when the test ends; without docker the test says so and +passes), and runs every scenario through the generated functions, normalized as +`normalization.md` says. All 56 run, `guarded-update` among them; a scenario this port could not run would go on the +ledger in that file, which is empty and only shrinks. `tests/repository.rs` runs the same +rows on SQLite in memory, and the guarded update on the rules model. + +### `service`: the operations, with the rules + +`service` ([ADR-0067](../../spec/decisions/ADR-0067-layering-and-the-service-seam.md) layer 4) +writes a `_service` crate per package with a stored entity. Its `Service` is generic over the pool (`D`, a `sqlx::PgPool` or `SqlitePool`, through `meta_service::Db`) +and the actor type (`A`, whatever the transport resolves a caller to), and is built from what the +app writes: + +- `P: Policy`: `allows(permission, actor, row, input, conn)` answers whether the actor + may run a command, a transition or an operation; the permission is the rules crate's enum; +- `B: Bodies`: a method per declared operation. A command's body answers the move to + make (`Move`, one variant per `@transitions` entry, or `None`) and its output; + `BodyError::Business` answers one of the operation's declared errors; +- `H: Hooks` (default `()`): `before` and `after` each derived create, update and + delete, told which by `Before` and `After` (`Before::CreateOrder(&mut input)`, + `UpdateOrder { patch, current }`, `DeleteOrder(&row)`); a before hook may change the input or patch; +- `E: Events` (default `()`): `on_write`, after every write, inside its transaction. + +Each derived operation and transition command is a method: `list_` (page size 50 unless +`api.pagination` says otherwise, and the total when the query asks `with_count`), `get_`, +`_of_`, `create_`, `update_`, `delete_`, and `_`; a declared +operation is ``. A write opens one transaction, or runs inside a caller's through its +`_in` twin (`create_order_in(&mut tx, ...)`), and a refusal anywhere undoes it. The checks run in +ADR-0066 §6's order: the row (404 `not_found`), validation (400), the permission point (403 +`forbidden`), the state (409 `invalid_transition`), the body, the guarded update (409 +`invalid_transition`, or `transition_condition_failed` when the row is in a legal state and the +`@condition` failed) and the event hook. An update that changes a lifecycle field is 409 +`state_managed`, and so is a create naming a state other than the initial one (unless +`rules.create` allows any). An `@autoSet` timestamp is stamped by the service, whatever the caller +sent ([ADR-0045](../../spec/decisions/ADR-0045-generated-api-surface-owns-write-semantics.md) +Amendment 1). Every error is a `ServiceError`, whose `code()` and `status()` are the wire's. + +`tests/service.rs` runs the rules corpus's scenarios (`fixtures/api-contract-conformance/rules/`) +through the generated service on SQLite, with the README's policy, bodies, hook and audit event, and +checks the settings variants in the generated text. The same scenarios run again over HTTP through +the routes below. + +### `service-routes`: the service over HTTP, on axum + +`service-routes` (ADR-0067 layer 5) writes a `_http` crate per package with a service, and +the shared `meta_http` crate. It is the one transport generator, and it is **opt-in**: it runs only +when `metaobjects.config.json` lists it, which `cargo meta init --transport` does. Its +`router(service, actor)` returns an `axum::Router` to mount under the API root (`apiPrefix`, say +`/api`): + +```rust +let app = axum::Router::new().nest("/api", tasks_http::router( + TasksService::new(pool, Team), // the generated service, with the app's policy + meta_http::ActorFn(|headers: &HeaderMap| user(headers)), +)); +``` + +`actor` is an `ActorSource`: the app's own authentication, a function of the request's headers +(`ActorFn`), or `()`, which reads no one. The routes hand the actor to the service untouched; they +check nothing of the rules themselves. Each entity gets `GET` and `POST` on `/`, `GET`, +`PATCH`, `PUT` and `DELETE` on `//{id}`, `GET //{id}/` for each traversal, +`POST //{id}/` for each transition command, and each declared operation its +`binding.rest` route. An entity that cannot be written answers its write verbs with 405 +`method_not_allowed`. + +The list query is the REST standard every port serves: `filter[][]=` with the nine +operators and `or`/`and` groups, `search=` over the search fields, `sort=:asc|desc`, +`limit` and `offset` (page size 50 unless `api.pagination` says otherwise; a limit over its `maxLimit` +is a 400 `limit_too_large`), and `withCount=true` for the total. The allowlist is the model's: a field is filterable +with `@filterable`, sortable with `@sortable` (or, with no `@sortable`, when it is filterable), and a +field with a password view is neither. Every refusal is a named 400 (`invalid_filter_field`, +`invalid_sort`, `pagination.invalid_value`, and the rest of `fixtures/list-query-conformance/`). A body is +checked before the service sees it: `invalid_json`, `unknown_fields` (unless `api.unknownFields` +is `drop`), `validation` with every issue, and `constraint_violation` for a unique key the store +refused. A credential field (one with a password view) is never written or returned by a route: a body key naming it is ignored, and no response carries it. + +An entity whose source has a read-only view beside its table (`source.rdb @kind: view` in the read +role) is written to the table and read back through the view, so the fields that view derives +(`origin.*`) are in every answer, a write's included. + ### Owning a generator A generator is a reference helper @@ -241,8 +498,9 @@ codegen/ While that crate exists, `cargo meta gen` and `cargo meta verify` build and run it, so there is still one way to generate. A copy is the shipped source byte for byte, and it imports only the engine surface (`metaobjects_codegen::{emitted, generator, names, plan, writer}`); the shared text a generator -writes (the transport, the command helpers) is inside the generator, so an owned `client` owns its -transport too. Every file in `codegen/` is an input of the skip key, whether `eject` wrote it or you +writes (the transport, the command helpers, the store, the service and HTTP mechanics) comes from the +engine's `emitted` module, so an owned copy that wants it different edits the function that writes that +crate (`transport_crate` in an owned `client`) or overrides that piece. Every file in `codegen/` is an input of the skip key, whether `eject` wrote it or you added it (a module beside the generator list, say), so editing any of them regenerates. Only the crate's build directory (`codegen/target`) and its `Cargo.lock` are left out. A crate it depends on by `path` (a linked checkout of a pack's generators, say), in a build table or a `[patch]`, is an input @@ -250,6 +508,15 @@ too, followed through that crate's own path dependencies and the workspace it in `metaobjects` and `metaobjects-codegen` engine crates are left out, because the engine's own hash already covers their source; a path dependency on `metaobjects-render` is hashed like any other. +An owned generator need not be a copy. Each shipped generator has a parts trait (`EntityParts`, +`ClientParts`, `CommandsParts`, `RenderHelperParts`, `OutputParserParts`, `OutputPromptParts`, +`RulesNamesParts`, `ContractTypesParts`, `RepositoryParts`, `ServiceParts` and `ServiceRoutesParts`) +with one default method per piece of its output (a crate's manifest, its `lib.rs`, one entity's file, +one item). A generator of your own implements it, overrides the piece it changes and returns +`self.render(ctx)` from `generate`; every other file is the shipped generator's, byte for byte. An +override can call the shipped piece, a public function of the same module and name. The traits carry +the same no-stability caveat as the rest of the engine API (ADR-0063 item 7). + `cargo meta gen --list` shows each owned copy as `identical`, or as `DIFFERS` with how many shipped lines it lacks and how many are its own. `cargo meta eject --undo` removes copies that are still identical (`--force` discards an edited one) @@ -285,19 +552,20 @@ outright. | `source-resolution-conformance` | all 30 cases | | `reference-source-conformance` | all 6 cases: a `reference: true` source loads so references resolve against it, a node declared only in reference files is a reference node no generator emits, and a `template.*` declared only there is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`) | | `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. | +| `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 one it cannot meet, about the three-way merge, is named with its reason in the runner; the template cases (a body edited, a body added) run. | | `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)) | +| `writer-conformance` | every `core` and `rust` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)); each `rust` case is a rustfmt fixed point | +| `template-output-render-conformance` | the welcome page and email, the nested payload and the cross-package payloads, rendered through generated `render-helper` crates that a probe builds; the drift cases fail `gen`, and a body edited after generation fails the render | +| `verify-conformance` | all 45 cases, through `metaobjects_render::verify`, the check `cargo meta verify --templates` runs, with no ledgered case and no Rust expectation file | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | | `render-conformance` | every case but the three the ledger holds — `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness` (`mustache-ng` has its own name lookup, data model and truthiness); a ledgered case must still differ, the rest render byte-identical through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | -| `verify-conformance` | all 45 cases, through `metaobjects_render::verify`, with no ledgered case | | `response-verify-conformance` | all 7 cases: the reply check the template gate adds — `ERR_RESPONSE_UNRESOLVED`, and, for an xml prompt, `ERR_RESPONSE_TAG_UNDECLARED` | | `extract-conformance` | all 58 cases, through `metaobjects_render::extract::extract` | | `output-prompt-conformance` | all 17 cases in all three `@promptStyle` styles, with the extract round trip, through `metaobjects_render::prompt::render_output_format` | -Two gates have no corpus of their own: +Three gates have no corpus of their own: - **The codegen-compile gate.** The small two-package model and the public fitness model are generated by every shipped generator, each into a scratch Cargo workspace that `cargo check` builds and @@ -307,13 +575,23 @@ Two gates have no corpus of their own: when cargo needed a package that lockfile does not name. - **The scale gate.** Twenty copies of the fitness model, each its own package: the output must be exactly twenty times one copy's files and no more than twenty times its bytes, one copy's output has - a byte budget and a longest-file budget, and all sixty-three crates must build. The times are + a byte budget and a longest-file budget, and all hundred and twenty-three crates must build. The times are printed; their ceilings are set far above a normal run and catch a step that stopped scaling, not a slow machine. +- **The layout ratchet** (ADR-0063 item 6, `metaobjects-codegen/tests/layout_ratchet.rs`). It parses + every source file under `metaobjects-codegen/src/` except the writer, which covers the generators and + the fixed text in `emitted/`, and it fails on a line break or an indentation run typed outside the + writer. `tests/layout_ratchet/allowlist.json` names the files that write something other than + generated code (terminal messages, hash input, JSON), each with a reason. The list only shrinks: the + test compares it with the copy at the branch's merge base. + +The API corpora run too, with no ledger in the list-query one: -Rust is not yet a column in the [per-corpus table](../CONFORMANCE.md#per-corpus-totals); it joins -when the port runs the persistence and API-contract corpora, which need a service tier the port does -not have yet. It runs the render, extract and output-format corpora today. +| Corpus | Rust today | +|---|---| +| `persistence-conformance` | all 56 scenarios, through the generated `repository` crates (see [`repository`](#repository-data-access-on-sqlx)) | +| `list-query-conformance` | all 95 cases, through the list parser `meta_http` ships, with the allowlist derived from the fixture's model as the generator derives it (`tests/list_query_conformance.rs`) | +| `api-contract-conformance` | the generated lane: each sub-corpus's model generated into a project, its routes served on SQLite and every scenario sent over HTTP (`tests/api_contract.rs`). `core` 34 scenarios, `write-through` 2, `secret-fields` 3, `list-query` 21, `rules` 14 and one in each of its three settings variants: 77 scenarios, 151 requests. Its ledger lists the sub-corpora not built yet (see [What does not exist yet](#what-does-not-exist-yet)), and a sub-corpus neither run nor ledgered fails the test. There is no hand-rolled reference-server lane: the generated lane is the one that tests a generator. | ### Load benchmark @@ -328,16 +606,22 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to ## What does not exist yet -- **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`, `verify --templates` and the business-rules gate are the ones it has. - There is no requirement gate and no `fmt`. +- **Other generators.** There is no documentation generator. Projections and reports get no route, + client or commands yet, and a template over a sourceless `object.projection` payload gets no + render function. +- **The rest of the API-contract corpus.** The transport passes `core`, `write-through`, + `secret-fields`, `list-query` and `rules` with its settings variants. These sub-corpora are not + built yet and are on the runner's ledger (`metaobjects-codegen/tests/api_contract.rs`): `tph` and + `secret-fields/tph` (single-table inheritance), `m2m` (many-to-many traversal), `jsonb` (object + fields stored as JSON), `projection`, `report`, `decimal`, `duration`, `api-settings` and + `enum-default`. +- **Other gates.** `verify --codegen`, `verify --templates` and the business-rules gate are the ones + it has. There is 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. -- **Prompt codegen.** The render engine and the reply parser exist as a library; no generator yet - writes a template's payload type or its response parser from the model. (`verify --templates` - does check the bodies and the reply against the model.) +- **A metadata-driven runtime.** No `ObjectManager` and no web adapter over it: data access is the + generated store crates, the generated `service` crates run the rules over them, and the generated + `service-routes` crates serve them. - **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). @@ -404,6 +688,14 @@ assert!(read_errors.is_empty() && result.errors.is_empty()); The API carries no stability promise and may change; read `server/rust/metaobjects/tests/project_load.rs` for a working call. +## A whole service: `examples/rust-service/` + +[`examples/rust-service/`](../../examples/rust-service/README.md) is the port's stand-in estate: a +tasks API with a lifecycle, whose model, store, rules, service and axum routes are generated from one +YAML file, and whose hand-written part is the policy, the caller and the table. The `rust` lane +checks that its committed `generated/` crates are what `gen` writes today (`verify --full`) and runs +its HTTP test. + ## A worked codegen exercise: `examples/tasks-axi-rust/` [`examples/tasks-axi-rust/`](../../examples/tasks-axi-rust/README.md) is an experiment, not a product, diff --git a/examples/rust-service/.gitignore b/examples/rust-service/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/examples/rust-service/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/examples/rust-service/.metaobjects/.gen-state/.hashes/.root.json b/examples/rust-service/.metaobjects/.gen-state/.hashes/.root.json new file mode 100644 index 0000000000..f9506ca091 --- /dev/null +++ b/examples/rust-service/.metaobjects/.gen-state/.hashes/.root.json @@ -0,0 +1,33 @@ +{ + "generated/meta_http/Cargo.toml": "99bbda48959ba0bf4a6e36d56b7754344cb5d320da6bb0baf695abe2e9b7d61a", + "generated/meta_http/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/meta_http/src/lib.rs": "c6a6bcd716fa30ee5f0651ec878956cdcd5b7dbff6c098c5683fdcf63108334c", + "generated/meta_http/src/list_query.rs": "21f40b4590bc3f46708693ece990a04463119d87077e552ef5fb360f8b7da7b6", + "generated/meta_service/Cargo.toml": "a45e561bd69d199599dce7c476dee49f43db5ccc8a3ac206279b7da316a8c3ff", + "generated/meta_service/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/meta_service/src/lib.rs": "e6a790b7be3993e67d71482d49f154700b8d741dfef58b1e95d324c50042dcf6", + "generated/meta_store/Cargo.toml": "a8530854f93e2d00f67514abf9182da0be045cdef708fd253fc5df406c9e66bd", + "generated/meta_store/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/meta_store/src/lib.rs": "d8dcd1dea850c845652113c22179994a1a207634f30afe5b8839e70db7c0d683", + "generated/meta_support/Cargo.toml": "874933bd61149c9c57a09b5227c4d6742ba1ad05dd947e71bd8b01d8b7d2675e", + "generated/meta_support/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/meta_support/src/lib.rs": "2749c3b5fbde6262311270d2d70d7f2c2196f136ea009044d7ae005d8d8bb01d", + "generated/meta_support/src/pattern.rs": "1a259a672d5b403d987a35631f9823f113f46c453ffb5efde8df319c6b31afa7", + "generated/meta_support/src/validation.rs": "cad91306f25e10eac8551cf9aa76b75a9aa95b51c72e75d888cc630b6003f829", + "generated/meta_support/src/wire.rs": "cdafbb73b05f0ae7947ee78ee2c7a434e97b15b9213ad101ca34521c14803439", + "generated/tasks/Cargo.toml": "7bac4befb7829d7f05b8bc6ba732d154cff41646fb3ae24bab42880845cc4d79", + "generated/tasks/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/tasks/src/lib.rs": "c7d1daaba43bae0b38c3ecc862ebc5919cd509c4047bd96b0e9b64472c4df082", + "generated/tasks_http/Cargo.toml": "efa0ddacc80e6a8120a4dc53214c41dba3fee10f435346b98d3b0327c91dd21c", + "generated/tasks_http/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/tasks_http/src/lib.rs": "69687b5e5f716b628ae6e7e228eb746fda24582f4a75f53212a09a3388f8d648", + "generated/tasks_rules/Cargo.toml": "aa58abd07691f7490efa398f8b0d5822a309c053c70a25b0f8bdaa2585407303", + "generated/tasks_rules/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/tasks_rules/src/lib.rs": "eaebf6e19c23e49596175da7a8806258c579cd1567c9c70055415622aac4403b", + "generated/tasks_service/Cargo.toml": "04769ec8e89e50d4cc595bf8c216a880b93354c6574ea57036b52b3b26a136d1", + "generated/tasks_service/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/tasks_service/src/lib.rs": "ed1a2e81a22fc443b50c6e0677286ec60ffc55cecc39af76e8e3937127d6be7a", + "generated/tasks_store/Cargo.toml": "a59263667a8f3a82daa8099f36f488e07e7ce0c827071f451bbb470ab64936ca", + "generated/tasks_store/rustfmt.toml": "a39741a789bf73773b1a51c47541e53f3009d7c100c3f12d3e6bf6249c8e886d", + "generated/tasks_store/src/lib.rs": "648f50d950089053f63bf64579f6b22ed6a2d309d60f738ffb7c18fad1e20fb2" +} diff --git a/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json new file mode 100644 index 0000000000..23a05f894a --- /dev/null +++ b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json @@ -0,0 +1,6 @@ +{ + "generated/tasks/src/task.rs": "c9494e046f1d9ec89cd5441247211303e2b26191bc4eed85f78f415b50a2b2e9", + "generated/tasks_http/src/task.rs": "f2c1bebac5452927c39a0c74c22e67ec2da699d5845d7e9bcccb6316f084b32e", + "generated/tasks_service/src/task.rs": "11fba25fd503ae858bcf6e3395c95b30ebcca1e4444dc4cfba1926c7fc8cfd11", + "generated/tasks_store/src/task.rs": "ae56db0385964c1f68b676bb0e29c3c10c5339cbfd3165e239b10a635fef5bda" +} diff --git a/examples/rust-service/.metaobjects/.gitignore b/examples/rust-service/.metaobjects/.gitignore new file mode 100644 index 0000000000..a8d41496bb --- /dev/null +++ b/examples/rust-service/.metaobjects/.gitignore @@ -0,0 +1,9 @@ +# The generation state. `.hashes/` is committed: it is one hash per generated +# path (one file per model package), and the only thing that lets `gen` tell "this file is exactly what I wrote" from +# "somebody edited this" on a machine that did not generate it. Everything else here (the +# skip key) describes one machine's last run and is not. +# +# The glob form matters: `.gen-state/` (a directory) would stop git descending, and the +# negation below could never take effect. +.gen-state/* +!.gen-state/.hashes/ diff --git a/examples/rust-service/.metaobjects/config.json b/examples/rust-service/.metaobjects/config.json new file mode 100644 index 0000000000..b649a609fc --- /dev/null +++ b/examples/rust-service/.metaobjects/config.json @@ -0,0 +1,16 @@ +{ + "schema_version": 1, + "migrate": { + "foreignKeyIndexes": true + }, + "verify": { + "handEdits": "fail" + }, + "api": { + "pagination": { + "defaultLimit": 50, + "maxLimit": 1000 + }, + "unknownFields": "reject" + } +} diff --git a/examples/rust-service/Cargo.lock b/examples/rust-service/Cargo.lock new file mode 100644 index 0000000000..5277946a57 --- /dev/null +++ b/examples/rust-service/Cargo.lock @@ -0,0 +1,2111 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "meta_http" +version = "0.1.0" +dependencies = [ + "axum", + "meta_service", + "meta_store", + "meta_support", + "serde", + "serde_json", + "serde_path_to_error", + "sqlx", +] + +[[package]] +name = "meta_service" +version = "0.1.0" +dependencies = [ + "chrono", + "meta_store", + "meta_support", + "serde", + "serde_json", + "sqlx", +] + +[[package]] +name = "meta_store" +version = "0.1.0" +dependencies = [ + "chrono", + "meta_support", + "serde", + "serde_json", + "sqlx", +] + +[[package]] +name = "meta_support" +version = "0.1.0" +dependencies = [ + "serde", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tasks" +version = "0.1.0" +dependencies = [ + "meta_support", + "serde", +] + +[[package]] +name = "tasks_app" +version = "0.1.0" +dependencies = [ + "axum", + "meta_http", + "serde_json", + "sqlx", + "tasks_http", + "tasks_rules", + "tasks_service", + "tokio", +] + +[[package]] +name = "tasks_http" +version = "0.1.0" +dependencies = [ + "axum", + "meta_http", + "meta_service", + "meta_store", + "tasks", + "tasks_service", +] + +[[package]] +name = "tasks_rules" +version = "0.1.0" +dependencies = [ + "tasks", +] + +[[package]] +name = "tasks_service" +version = "0.1.0" +dependencies = [ + "meta_service", + "meta_store", + "meta_support", + "serde_json", + "tasks", + "tasks_rules", + "tasks_store", +] + +[[package]] +name = "tasks_store" +version = "0.1.0" +dependencies = [ + "meta_store", + "tasks", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/rust-service/Cargo.toml b/examples/rust-service/Cargo.toml new file mode 100644 index 0000000000..2af5a2a9f2 --- /dev/null +++ b/examples/rust-service/Cargo.toml @@ -0,0 +1,4 @@ +# The example's workspace: the app and every crate `cargo meta gen` wrote. +[workspace] +resolver = "2" +members = ["app", "generated/*"] diff --git a/examples/rust-service/README.md b/examples/rust-service/README.md new file mode 100644 index 0000000000..68183031ba --- /dev/null +++ b/examples/rust-service/README.md @@ -0,0 +1,53 @@ +# A Rust service from one model + +A tasks API whose model, store, lifecycle rules, service and HTTP routes are all generated by +`cargo meta gen` from one file, [`metaobjects/meta.app.yaml`](metaobjects/meta.app.yaml). The +hand-written part is [`app/src/lib.rs`](app/src/lib.rs): who the caller is, what they may do, and +the table. It is the Rust port's stand-in estate: the `rust` lane checks that the committed +`generated/` crates are what `gen` writes today and runs [the app's test](app/tests/api.rs) over +HTTP. + +## What the model says + +One entity, `Task`, stored in `tasks`, with a `status` lifecycle: `todo`, `doing` and `done`, and +three transitions, `start`, `finish` and `reopen` (which is public). `title` and `status` can be +filtered on, and `title` sorted by. That is all the generators need: + +| Crate | Generator | What it holds | +|---|---|---| +| `tasks` | `entity` | `Task`, its create and patch bodies and `validate()` | +| `tasks_rules` | `rules-names` | the lifecycle's states and transitions, and the permissions `tasks.Task.start` and `tasks.Task.finish` | +| `tasks_store` | `repository` | list, count, get, create, update, delete and the guarded update, on sqlx | +| `tasks_service` | `service` | each write in one transaction, with the rules checked in ADR-0066's order | +| `tasks_http` | `service-routes` | the axum routes over the service | +| `meta_*` | the same | the shared code each tier uses, written into the project as source | + +`metaobjects.config.json` lists those six. `service-routes` is opt-in: `cargo meta init --transport` +writes it into the list, and a plain `cargo meta init` leaves it out. + +## Run it + +From a checkout, with `cargo-meta` installed from `server/rust/metaobjects-cli`: + +```bash +cargo meta gen # rewrites nothing: generated/ is already current +cargo test # the HTTP test, on an in-memory SQLite database +cargo run -p tasks_app # serves http://127.0.0.1:3000/api/tasks +``` + +```bash +curl -s -XPOST localhost:3000/api/tasks -H 'x-user: ada' -H 'content-type: application/json' \ + -d '{"title": "Write the docs"}' +curl -s -XPOST localhost:3000/api/tasks/1/start -H 'x-user: ada' +curl -s -XPOST localhost:3000/api/tasks/1/finish -H 'x-user: grace' -H 'x-role: lead' +curl -s 'localhost:3000/api/tasks?filter[status][eq]=done&withCount=true' +``` + +`finish` without `x-role: lead` answers 403 `forbidden`, a second `start` 409 +`invalid_transition`, and a `PATCH` naming `status` 409 `state_managed`: the service makes those +checks, and the routes only carry them to the wire. + +Change the model and run `cargo meta gen` again; `cargo meta verify` fails while `generated/` is +behind it. The table is the app's own (`SCHEMA` in `app/src/lib.rs`): migrations run in the +project's own tool, or the Node `meta migrate` reference helper. See +[the Rust port page](../../docs/ports/rust.md). diff --git a/examples/rust-service/app/Cargo.toml b/examples/rust-service/app/Cargo.toml new file mode 100644 index 0000000000..f0c0069f57 --- /dev/null +++ b/examples/rust-service/app/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tasks_app" +version = "0.1.0" +edition = "2021" +publish = false +description = "A tasks API whose model, store, rules, service and routes are generated by MetaObjects." + +[dependencies] +meta_http = { path = "../generated/meta_http" } +tasks_http = { path = "../generated/tasks_http" } +tasks_rules = { path = "../generated/tasks_rules" } +tasks_service = { path = "../generated/tasks_service" } +axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] } +serde_json = "1" +sqlx = { version = "0.8", default-features = false, features = ["sqlite", "runtime-tokio"] } +tokio = { version = "1", features = ["rt", "macros", "net"] } diff --git a/examples/rust-service/app/src/lib.rs b/examples/rust-service/app/src/lib.rs new file mode 100644 index 0000000000..7360269eb5 --- /dev/null +++ b/examples/rust-service/app/src/lib.rs @@ -0,0 +1,79 @@ +//! The part of the tasks API the model cannot say: who a caller is, what they may do, and the +//! table the rows live in. Everything it calls is generated from `metaobjects/meta.app.yaml` into +//! `generated/` by `cargo meta gen`: the `Task` type and its validation (`tasks`), the store +//! (`tasks_store`), the lifecycle's names (`tasks_rules`), the service that runs every write in a +//! transaction with the rules checked (`tasks_service`) and the axum routes over it (`tasks_http`). + +use axum::http::HeaderMap; +use serde_json::Value; +use sqlx::SqliteConnection; +use sqlx::sqlite::{SqlitePool, SqlitePoolOptions}; +use tasks_rules::Permission; +use tasks_service::{TasksError, TasksPolicy, TasksService}; + +/// The table `Task` is stored in. Migrations are the project's own; the Node `meta migrate` +/// would propose this from the model. +pub const SCHEMA: &str = r#"CREATE TABLE IF NOT EXISTS "tasks" ( + "id" INTEGER PRIMARY KEY NOT NULL, + "title" TEXT NOT NULL, + "notes" TEXT, + "status" TEXT NOT NULL DEFAULT 'todo' +); +"#; + +/// Who a request runs for. +pub struct User { + pub name: String, + /// A team lead, who may finish a task. + pub lead: bool, +} + +/// The caller, from the `x-user` header (absent or empty: nobody) and `x-role: lead`. +pub fn user(headers: &HeaderMap) -> Option { + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or(""); + let name = header("x-user"); + if name.is_empty() { + return None; + } + Some(User { name: name.to_string(), lead: header("x-role") == "lead" }) +} + +/// Anyone signed in may start a task, and only a lead may finish one. Reopening a done task is +/// `public` in the model, so the service never asks. +pub struct Team; + +impl TasksPolicy for Team { + async fn allows<'a>( + &'a self, + permission: Permission, + actor: Option<&'a User>, + _row: Option<&'a Value>, + _input: Option<&'a Value>, + _conn: &'a mut SqliteConnection, + ) -> Result { + Ok(match (permission, actor) { + (_, None) => false, + (Permission::TasksTaskStart, Some(_)) => true, + (Permission::TasksTaskFinish, Some(user)) => user.lead, + }) + } +} + +/// A pool on `url` with the table in place. One connection, kept open, so an in-memory database +/// lives as long as the app. +pub async fn database(url: &str) -> Result { + let pool = SqlitePoolOptions::new() + .max_connections(1) + .min_connections(1) + .idle_timeout(None) + .max_lifetime(None) + .connect(url) + .await?; + sqlx::raw_sql(SCHEMA).execute(&pool).await?; + Ok(pool) +} + +/// The API, to mount under `/api`. +pub fn app(pool: SqlitePool) -> axum::Router { + tasks_http::router(TasksService::new(pool, Team), meta_http::ActorFn(user)) +} diff --git a/examples/rust-service/app/src/main.rs b/examples/rust-service/app/src/main.rs new file mode 100644 index 0000000000..82bc0aba67 --- /dev/null +++ b/examples/rust-service/app/src/main.rs @@ -0,0 +1,14 @@ +//! Serves the tasks API under `/api`: `DATABASE_URL` (default an in-memory SQLite database) and +//! `ADDR` (default `127.0.0.1:3000`). + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + let url = std::env::var("DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".to_string()); + let addr = std::env::var("ADDR").unwrap_or_else(|_| "127.0.0.1:3000".to_string()); + let pool = tasks_app::database(&url).await?; + let app = axum::Router::new().nest("/api", tasks_app::app(pool)); + let listener = tokio::net::TcpListener::bind(&addr).await?; + println!("tasks API on http://{}/api/tasks", listener.local_addr()?); + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/examples/rust-service/app/tests/api.rs b/examples/rust-service/app/tests/api.rs new file mode 100644 index 0000000000..f4c31c3282 --- /dev/null +++ b/examples/rust-service/app/tests/api.rs @@ -0,0 +1,78 @@ +//! The tasks API over HTTP: a create, the list's REST-standard query, a refused body, and the +//! lifecycle with its permission points. + +use serde_json::{Value, json}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// The app on a free port, served for the rest of the test. +async fn serve() -> String { + let pool = tasks_app::database("sqlite::memory:").await.unwrap(); + let app = axum::Router::new().nest("/api", tasks_app::app(pool)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + addr +} + +/// One request: the status and the body read as JSON (`null` for an empty body). +async fn send(addr: &str, method: &str, path: &str, user: &[(&str, &str)], body: Option) -> (u16, Value) { + let mut req = format!("{method} {path} HTTP/1.1\r\nHost: tasks\r\nConnection: close\r\n"); + for (k, v) in user { + req.push_str(&format!("{k}: {v}\r\n")); + } + let body = body.map(|b| b.to_string()).unwrap_or_default(); + req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len())); + let mut stream = TcpStream::connect(addr).await.unwrap(); + stream.write_all(req.as_bytes()).await.unwrap(); + let mut raw = String::new(); + stream.read_to_string(&mut raw).await.unwrap(); + let (head, rest) = raw.split_once("\r\n\r\n").unwrap(); + let status = head.split(' ').nth(1).unwrap().parse().unwrap(); + // axum sends a JSON body with a length, so the body is the rest as it is. + (status, serde_json::from_str(rest).unwrap_or(Value::Null)) +} + +const ADA: &[(&str, &str)] = &[("x-user", "ada")]; +const LEAD: &[(&str, &str)] = &[("x-user", "grace"), ("x-role", "lead")]; + +#[tokio::test(flavor = "current_thread")] +async fn a_task_is_written_listed_and_moved_through_its_lifecycle() { + let addr = serve().await; + + let (status, task) = send(&addr, "POST", "/api/tasks", ADA, Some(json!({ "title": "Write the docs" }))).await; + assert_eq!(status, 201, "{task}"); + assert_eq!(task["status"], "todo", "a create starts the lifecycle in its initial state"); + let id = task["id"].as_i64().unwrap(); + send(&addr, "POST", "/api/tasks", ADA, Some(json!({ "title": "Ship it" }))).await; + + // The list query is the REST standard's: a filter, a sort, a page and the total. + let (status, page) = send(&addr, "GET", "/api/tasks?filter[title][like]=Ship%25&sort=title:desc&withCount=true", &[], None).await; + assert_eq!(status, 200, "{page}"); + assert_eq!((page["total"].clone(), page["rows"][0]["title"].clone()), (json!(1), json!("Ship it"))); + + // What the model refuses, the route refuses with a named body. + let (status, refused) = send(&addr, "POST", "/api/tasks", ADA, Some(json!({ "title": "x", "owner": "ada" }))).await; + assert_eq!((status, refused["error"].clone()), (400, json!("unknown_fields")), "{refused}"); + let (status, refused) = send(&addr, "GET", "/api/tasks?filter[notes][eq]=x", &[], None).await; + assert_eq!((status, refused["error"].clone()), (400, json!("invalid_filter_field")), "{refused}"); + + // Starting needs a caller; finishing needs a lead; the service checks, not the route. + let start = format!("/api/tasks/{id}/start"); + let finish = format!("/api/tasks/{id}/finish"); + assert_eq!(send(&addr, "POST", &start, &[], None).await.0, 403); + let (status, task) = send(&addr, "POST", &start, ADA, None).await; + assert_eq!((status, task["status"].clone()), (200, json!("doing")), "{task}"); + let (status, refused) = send(&addr, "POST", &start, ADA, None).await; + assert_eq!((status, refused["error"].clone()), (409, json!("invalid_transition")), "{refused}"); + assert_eq!(send(&addr, "POST", &finish, ADA, None).await.0, 403); + let (status, task) = send(&addr, "POST", &finish, LEAD, None).await; + assert_eq!((status, task["status"].clone()), (200, json!("done")), "{task}"); + + // A generic update never moves a lifecycle. + let (status, refused) = send(&addr, "PATCH", &format!("/api/tasks/{id}"), ADA, Some(json!({ "status": "todo" }))).await; + assert_eq!((status, refused["error"].clone()), (409, json!("state_managed")), "{refused}"); + // Reopening is public. + let (status, task) = send(&addr, "POST", &format!("/api/tasks/{id}/reopen"), &[], None).await; + assert_eq!((status, task["status"].clone()), (200, json!("todo")), "{task}"); +} diff --git a/examples/rust-service/generated/meta_http/Cargo.toml b/examples/rust-service/generated/meta_http/Cargo.toml new file mode 100644 index 0000000000..80a69d026b --- /dev/null +++ b/examples/rust-service/generated/meta_http/Cargo.toml @@ -0,0 +1,17 @@ +# @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "meta_http" +version = "0.1.0" +edition = "2021" +publish = false +description = "The REST mechanics of the generated MetaObjects transport crates." + +[dependencies] +meta_service = { path = "../meta_service", default-features = false } +meta_store = { path = "../meta_store", default-features = false } +meta_support = { path = "../meta_support" } +axum = { version = "0.8", default-features = false, features = ["json", "query"] } +serde = "1" +serde_json = "1" +serde_path_to_error = "0.1" +sqlx = { version = "0.8", default-features = false } diff --git a/examples/rust-service/generated/meta_http/rustfmt.toml b/examples/rust-service/generated/meta_http/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/meta_http/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/meta_http/src/lib.rs b/examples/rust-service/generated/meta_http/src/lib.rs new file mode 100644 index 0000000000..116068b01e --- /dev/null +++ b/examples/rust-service/generated/meta_http/src/lib.rs @@ -0,0 +1,444 @@ +// @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. + +//! The REST mechanics the `service-routes` generator's crates share (ADR-0067 layer 5): how a +//! request becomes a call on a generated service, and how what the service answered becomes a +//! response. +//! +//! The routes are written into each package's transport crate; this crate holds only what every +//! one of them shares, so each refusal has one spelling in every app: the list query's named 400s +//! ([`list_query`]), `invalid_json`, `invalid_id`, `unknown_fields`, a `validation` 400 listing +//! every issue, `constraint_violation`, `method_not_allowed`, and a 500 that names nothing +//! (`internal`). It holds no rules: those are the service's. + +use axum::Json; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use meta_service::{Page, ServiceError}; +use meta_store::{Filter, Op, StoreError}; +use meta_support::validation::{self, Violation}; +// The list query reads decimals, durations and formats through these. +use meta_support::wire; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value, json}; + +mod list_query; + +pub use list_query::{FilterRule, Kind, ListQuery, ListSpec, Node, Refusal, Search, Sort, SortRule}; + +/// Who a request runs for, read from the request: the app's own authentication. The routes hand +/// the actor to the service untouched, which hands it to the policy, the bodies, the hooks and the +/// event hook. `()` is the source that finds no actor, which a policy may refuse. +pub trait ActorSource: Send + Sync + 'static { + fn actor(&self, headers: &HeaderMap) -> Option; +} + +impl ActorSource for () { + fn actor(&self, _headers: &HeaderMap) -> Option { + None + } +} + +/// An [`ActorSource`] that is a function of the headers. +pub struct ActorFn(pub F); + +impl ActorSource for ActorFn +where + F: Fn(&HeaderMap) -> Option + Send + Sync + 'static, +{ + fn actor(&self, headers: &HeaderMap) -> Option { + (self.0)(headers) + } +} + +/// What a body may carry, for one entity's create or update route. +pub struct BodySpec { + /// Every field the entity declares: any other key is unknown. + pub declared: &'static [&'static str], + /// The keys a create keeps. A declared key the client may not set is dropped, never refused. + pub create: &'static [&'static str], + /// The keys a create must carry, not null. + pub create_required: &'static [&'static str], + /// The keys an update keeps. + pub update: &'static [&'static str], + /// The keys an update may omit but may not set to null. + pub update_not_null: &'static [&'static str], + /// `api.unknownFields: reject` (the default): a body with an undeclared key is refused. + pub reject_unknown: bool, +} + +/// A response with a JSON body. +pub fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +fn refuse(status: StatusCode, code: &str) -> Response { + reply(status, json!({ "error": code })) +} + +/// `405 method_not_allowed`: the write verbs of a read-only route. +pub async fn method_not_allowed() -> Response { + refuse(StatusCode::METHOD_NOT_ALLOWED, "method_not_allowed") +} + +/// `400 invalid_id`: an `{id}` the key cannot hold. +pub fn invalid_id() -> Response { + refuse(StatusCode::BAD_REQUEST, "invalid_id") +} + +/// The whole-number key `text` spells: an optional `-` and ASCII digits with no leading zero, +/// no exponent, hex, plus sign, whitespace or negative zero, and in the key type's range. +pub fn int_key(text: &str) -> Result { + let digits = text.strip_prefix('-').unwrap_or(text); + let canonical = !digits.is_empty() + && digits.bytes().all(|b| b.is_ascii_digit()) + && (digits == "0" || !digits.starts_with('0')) + && text != "-0"; + match canonical.then(|| text.parse::().ok()).flatten() { + Some(key) => Ok(key), + None => Err(invalid_id()), + } +} + +/// A list query and whether its count was asked for, ready for a service's list call. +pub struct Listed { + pub query: meta_store::Query, + pub with_count: bool, +} + +/// Parse a list route's query string against `spec`: the store query, or the named 400. +pub fn list(raw: Option<&str>, spec: &ListSpec) -> Result { + let parsed = list_query::parse(raw.unwrap_or(""), spec) + .map_err(|r| reply(StatusCode::BAD_REQUEST, r.body()))?; + let mut filters: Vec = parsed.filter.map(filter).into_iter().collect(); + if let Some(search) = parsed.search { + let fields = search.fields.iter().map(|f| f.to_string()).collect(); + filters.push(Filter::Search { term: search.term, fields }); + } + let filter = match filters.len() { + 0 => None, + 1 => filters.pop(), + _ => Some(Filter::And(filters)), + }; + let sort = parsed + .sort + .map(|s| meta_store::Sort { field: s.field, descending: s.descending }) + .into_iter() + .collect(); + let query = meta_store::Query { filter, sort, limit: parsed.limit, offset: parsed.offset }; + Ok(Listed { query, with_count: parsed.with_count }) +} + +fn filter(node: Node) -> Filter { + match node { + Node::And(all) => Filter::And(all.into_iter().map(filter).collect()), + Node::Or(any) => Filter::Or(any.into_iter().map(filter).collect()), + Node::Leaf { field, op, value } => { + // The parser admits only the operators the store has. + let op = Op::of(&op).unwrap_or(Op::Eq); + Filter::Field { field, op, value } + } + } +} + +/// What a route answers: its response, either way. A refusal found before the service is +/// called is the `Err`, so a route reads each part of its request with `?`. +pub type Reply = Result; + +/// A list page: the rows, or `{ rows, total }` when the count was asked for. +pub fn page(out: Result, ServiceError>, secret: &[&str]) -> Reply { + Ok(match out { + Ok(Page { rows, total: None }) => answer(StatusCode::OK, &rows, secret), + Ok(Page { rows, total: Some(total) }) => match to_json(&rows, secret) { + Ok(rows) => reply(StatusCode::OK, json!({ "rows": rows, "total": total })), + Err(e) => internal(&e), + }, + Err(e) => error(e), + }) +} + +/// What an operation answered: `200` with it, less the credentials `secret` names. +pub fn ok(out: Result, secret: &[&str]) -> Reply { + send(StatusCode::OK, out, secret) +} + +/// What a create answered: `201` with the row, less the credentials `secret` names. +pub fn created(out: Result, secret: &[&str]) -> Reply { + send(StatusCode::CREATED, out, secret) +} + +fn send(status: StatusCode, out: Result, secret: &[&str]) -> Reply { + Ok(match out { + Ok(v) => answer(status, &v, secret), + Err(e) => error(e), + }) +} + +/// `204` on success, whatever the operation answered. +pub fn no_content(out: Result) -> Reply { + Ok(match out { + Ok(_) => StatusCode::NO_CONTENT.into_response(), + Err(e) => error(e), + }) +} + +/// `value` as JSON, with no credential `secret` names on any row in it. +fn to_json(value: &T, secret: &[&str]) -> Result { + let mut value = serde_json::to_value(value)?; + if !secret.is_empty() { + let strip = |row: &mut Value| { + if let Value::Object(m) = row { + for k in secret { + m.remove(*k); + } + } + }; + match &mut value { + Value::Array(rows) => rows.iter_mut().for_each(strip), + row => strip(row), + } + } + Ok(value) +} + +fn answer(status: StatusCode, value: &T, secret: &[&str]) -> Response { + match to_json(value, secret) { + Ok(body) => reply(status, body), + Err(e) => internal(&e), + } +} + +fn internal(e: &dyn std::fmt::Display) -> Response { + // The full error is the server's: the body names no SQL, table or value. + eprintln!("meta_http: internal error: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "internal") +} + +/// The response for a service error. +pub fn error(e: ServiceError) -> Response { + let status = StatusCode::from_u16(e.status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + match e { + ServiceError::Validation(violations) => validation_failed(issues(&violations)), + ServiceError::LimitTooLarge { max } => { + reply(status, json!({ "error": "limit_too_large", "maxLimit": max })) + } + ServiceError::Refused { code, message } => { + let mut body = json!({ "error": code }); + if let Some(m) = message { + body["message"] = Value::from(m); + } + reply(status, body) + } + ServiceError::Store(StoreError::UnknownField { field, .. }) + | ServiceError::Store(StoreError::BadValue { field, .. }) => { + let message = format!("'{field}' is not a value the store can hold"); + validation_failed(vec![issue("custom", &field, &message)]) + } + ServiceError::Store(StoreError::Database(db)) => match constraint(&db) { + Some((kind, status)) => { + reply(status, json!({ "error": "constraint_violation", "constraint": kind })) + } + None => internal(&db), + }, + ServiceError::Store(other) => internal(&other), + other if status.is_server_error() => internal(&other), + other => refuse(status, other.code()), + } +} + +/// The kind of constraint a database refused a write by, and its status: 409 for a conflict with +/// another row, 400 for the request's own value. +fn constraint(e: &sqlx::Error) -> Option<(&'static str, StatusCode)> { + use sqlx::error::ErrorKind; + let sqlx::Error::Database(db) = e else { return None }; + Some(match db.kind() { + ErrorKind::UniqueViolation => ("unique", StatusCode::CONFLICT), + ErrorKind::ForeignKeyViolation => ("foreign_key", StatusCode::CONFLICT), + ErrorKind::NotNullViolation => ("not_null", StatusCode::BAD_REQUEST), + ErrorKind::CheckViolation => ("check", StatusCode::BAD_REQUEST), + _ => return None, + }) +} + +/// `400 validation`, listing every issue. +fn validation_failed(issues: Vec) -> Response { + reply(StatusCode::BAD_REQUEST, json!({ "error": "validation", "issues": issues })) +} + +/// One issue: its code (Zod's name for the failure), the member's path and a sentence. +fn issue(code: &str, field: &str, message: &str) -> Value { + json!({ "code": code, "path": path(field), "message": message }) +} + +/// `outer[0].inner` as `["outer", 0, "inner"]`. +fn path(field: &str) -> Value { + let mut out = Vec::new(); + for part in field.split('.').filter(|p| !p.is_empty()) { + let mut rest = part; + if let Some(at) = rest.find('[') { + out.push(Value::from(&rest[..at])); + rest = &rest[at..]; + while let Some(close) = rest.find(']') { + match rest[1..close].parse::() { + Ok(n) => out.push(Value::from(n)), + Err(_) => out.push(Value::from(&rest[1..close])), + } + rest = &rest[close + 1..]; + } + } else { + out.push(Value::from(rest)); + } + } + Value::Array(out) +} + +/// The issues of the model's rules a value breaks, each by Zod's name for it. +pub fn issues(violations: &[Violation]) -> Vec { + violations + .iter() + .map(|v| { + let code = match v.rule { + validation::RULE_LENGTH | validation::RULE_ARRAY | validation::RULE_NUMERIC => { + // The checks say which bound was broken: "at least" is the lower one. + if v.message.contains("at least") { + "too_small" + } else { + "too_big" + } + } + validation::RULE_REGEX | validation::RULE_FORMAT => "invalid_format", + _ => "custom", + }; + issue(code, &v.field, &v.message) + }) + .collect() +} + +/// A request body as JSON, or `400 invalid_json`. +fn json_body(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|_| refuse(StatusCode::BAD_REQUEST, "invalid_json")) +} + +/// The members of a body the route keeps: `400 invalid_json`, a `validation` 400 for a body that +/// is not an object, `400 unknown_fields` (sorted) for an undeclared key under `reject`; then +/// only the `keep` keys. +fn members(bytes: &[u8], spec: &BodySpec, keep: &[&str]) -> Result, Response> { + let Value::Object(mut body) = json_body(bytes)? else { + let message = "the body must be a JSON object"; + return Err(validation_failed(vec![json!({ + "code": "invalid_type", + "path": [], + "message": message, + })])); + }; + if spec.reject_unknown { + let mut unknown: Vec<&str> = + body.keys().map(String::as_str).filter(|k| !spec.declared.contains(k)).collect(); + if !unknown.is_empty() { + unknown.sort_unstable(); + let fields = json!({ "error": "unknown_fields", "fields": unknown }); + return Err(reply(StatusCode::BAD_REQUEST, fields)); + } + } + body.retain(|k, _| keep.contains(&k.as_str())); + Ok(body) +} + +fn bind(body: Map) -> Result> { + serde_path_to_error::deserialize(Value::Object(body)).map_err(|e| { + let field = e.path().to_string(); + let field = if field == "." { String::new() } else { field }; + let message = e.inner().to_string(); + let code = if message.starts_with("unknown variant") { + "invalid_value" + } else if message.starts_with("missing field") || message.starts_with("invalid type") { + "invalid_type" + } else { + "custom" + }; + let field = match message.strip_prefix("missing field `") { + Some(rest) => rest.split('`').next().unwrap_or("").to_string(), + None => field, + }; + vec![issue(code, &field, &message)] + }) +} + +fn missing(field: &str) -> Value { + issue("invalid_type", field, &format!("'{field}' is required")) +} + +/// A create body as `C`. A required key that is absent or null is an issue, listed together with +/// every rule a present member breaks (checked through the update body `P` and `check`, since a +/// body missing a required member is no `C` to check). +pub fn create_body( + bytes: &[u8], + spec: &BodySpec, + check: impl Fn(&P) -> Vec, +) -> Result +where + C: DeserializeOwned, + P: DeserializeOwned, +{ + let body = members(bytes, spec, spec.create)?; + let absent: Vec<&str> = spec + .create_required + .iter() + .copied() + .filter(|k| body.get(*k).is_none_or(Value::is_null)) + .collect(); + if absent.is_empty() { + return bind(body).map_err(validation_failed); + } + let mut found: Vec = absent.iter().map(|k| missing(k)).collect(); + let mut present = body; + present.retain(|k, v| !v.is_null() && spec.update.contains(&k.as_str())); + if let Ok(partial) = bind::

(present) { + found.extend(issues(&check(&partial))); + } + Err(validation_failed(found)) +} + +/// An update body as `P`. A null on a member that may not be null is an issue, listed together +/// with every rule a present member breaks. +pub fn update_body

( + bytes: &[u8], + spec: &BodySpec, + check: impl Fn(&P) -> Vec, +) -> Result +where + P: DeserializeOwned, +{ + let mut body = members(bytes, spec, spec.update)?; + let nulls: Vec = body + .iter() + .filter(|(k, v)| v.is_null() && spec.update_not_null.contains(&k.as_str())) + .map(|(k, _)| k.clone()) + .collect(); + if nulls.is_empty() { + return bind(body).map_err(validation_failed); + } + let mut found: Vec = nulls.iter().map(|k| missing(k)).collect(); + body.retain(|k, _| !nulls.contains(k)); + if let Ok(partial) = bind::

(body) { + found.extend(issues(&check(&partial))); + } + Err(validation_failed(found)) +} + +/// An operation's input as `I`, from a JSON body (an empty one is `{}`). +pub fn input_body(bytes: &[u8]) -> Result { + let value = if bytes.iter().all(u8::is_ascii_whitespace) { + Value::Object(Map::new()) + } else { + json_body(bytes)? + }; + let Value::Object(body) = value else { + return Err(validation_failed(vec![issue( + "invalid_type", + "", + "the body must be an object", + )])); + }; + bind(body).map_err(validation_failed) +} diff --git a/examples/rust-service/generated/meta_http/src/list_query.rs b/examples/rust-service/generated/meta_http/src/list_query.rs new file mode 100644 index 0000000000..2fe0161e72 --- /dev/null +++ b/examples/rust-service/generated/meta_http/src/list_query.rs @@ -0,0 +1,762 @@ +// @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. + +//! How a list route reads its query string: the filter tree (and/or groups to a depth cap), +//! the search, the sort and the page, or the named 400 it refuses with. +//! +//! A port of the TypeScript reference parser, held to it by the shared parse cases of +//! `fixtures/list-query-conformance/`. The parse runs before any store sees the query, and the +//! values it hands on are neutral: a number is a JSON number, a decimal its canonical text, an +//! instant timestamp its UTC spelling, and every other value the text as sent. +//! +//! Faults are found, and the first reported, in this order: bare field parameters; `limit`, then +//! `offset`; the filter, depth-first in the order its keys were sent; the sort; the search. +//! +//! This file is written by the `service-routes` generator into the transport crate +//! (`meta_http`). Nothing here depends on MetaObjects. + +// The crates this lands in are edition 2021, which has no `if let` chains to collapse into. +#![allow(clippy::collapsible_if)] + +use std::collections::HashMap; +use std::fmt; + +use serde_json::{Map, Value}; + +use super::validation::{is_date, is_uuid}; +use super::wire::{Decimal, Duration}; + +/// Five levels of `or`/`and` nesting; the sixth is `filter.nesting_too_deep`. +pub const MAX_NESTING: usize = 5; +/// At most 100 `in` elements; more is `filter.in_too_large`. +pub const MAX_IN_LIST: usize = 100; + +const SORT_EXPECTED: &str = "sort=:asc|desc"; +const PAGINATION_EXPECTED: &str = "a non-negative integer (0 or more)"; +const INTEGER_EXPECTED: &str = "integer (a whole number)"; +const PLUS_OFFSET_HINT: &str = + "a \"+\" in a query string decodes to a space: URL-encode the offset's \"+\" as %2B, or use Z for UTC"; +/// The largest page bound the TypeScript routes accept (`Number.isSafeInteger`). +const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; +const RESERVED: [&str; 6] = ["filter", "sort", "limit", "offset", "search", "withCount"]; + +/// How a filter operand is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// Text or an enum member: kept as sent. + Text, + /// int, long, currency: a JSON number with no fraction. + Integer, + /// double, float: a JSON number. + Number, + Boolean, + Date, + Time, + /// A `field.timestamp` instant: a zoneless bound is UTC, a date alone midnight UTC. + Instant, + /// A `@localTime` timestamp: kept as sent unless it carries a zone. + LocalTimestamp, + Uuid, + Decimal, + Duration, +} + +impl Kind { + /// The `expected` text of a malformed value, for the kinds that check a format. + fn expected(self) -> Option<&'static str> { + Some(match self { + Kind::Date => "date (YYYY-MM-DD)", + Kind::Time => "time (HH:MM[:SS[.fff]])", + Kind::Instant | Kind::LocalTimestamp => { + "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])" + } + Kind::Uuid => "uuid (8-4-4-4-12 hex)", + Kind::Decimal => "decimal number (digits, optional fraction, optional exponent)", + Kind::Duration => "duration (ISO 8601, e.g. PT1H30M; no years or months)", + _ => return None, + }) + } +} + +/// One filterable field: its operators, how its operand is read, and its enum members. +#[derive(Debug, Clone, Copy)] +pub struct FilterRule { + pub field: &'static str, + pub ops: &'static [&'static str], + pub kind: Kind, + /// The members of a `field.enum`; a value that is not one is refused. + pub values: Option<&'static [&'static str]>, +} + +/// One sortable field, and the direction a sort that names no order takes. +#[derive(Debug, Clone, Copy)] +pub struct SortRule { + pub field: &'static str, + pub descending: bool, +} + +/// What one entity's list route accepts. +#[derive(Debug, Clone, Copy)] +pub struct ListSpec { + pub filters: &'static [FilterRule], + pub sorts: &'static [SortRule], + /// Every field of the entity a client reads, so a bare `?notes=x` for a field that is not + /// filterable is refused with a reason rather than ignored. + pub fields: &'static [&'static str], +} + +impl ListSpec { + fn filter(&self, field: &str) -> Option<&FilterRule> { + self.filters.iter().find(|r| r.field == field) + } + + fn allowed(&self) -> Value { + names(self.filters.iter().map(|r| r.field)) + } + + /// The fields `?search` matches: text whose band has `like` (plain text and string-backed + /// enums, never a uuid or an int-backed enum). + pub fn search_fields(&self) -> Vec<&'static str> { + self.filters + .iter() + .filter(|r| r.kind == Kind::Text && r.ops.contains(&"like")) + .map(|r| r.field) + .collect() + } +} + +/// A node of a parsed filter. +#[derive(Debug, Clone, PartialEq)] +pub enum Node { + /// One condition. `in` holds a list; `isNull` a boolean. + Leaf { field: String, op: String, value: Value }, + /// Every branch holds. + And(Vec), + /// At least one branch holds. + Or(Vec), +} + +/// A case-insensitive substring search over `fields`. +#[derive(Debug, Clone, PartialEq)] +pub struct Search { + pub term: String, + pub fields: Vec<&'static str>, +} + +/// One sort key. +#[derive(Debug, Clone, PartialEq)] +pub struct Sort { + pub field: String, + pub descending: bool, +} + +/// A parsed list query. Members a query did not send are `None`. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ListQuery { + pub filter: Option, + pub search: Option, + pub sort: Option, + pub limit: Option, + pub offset: Option, + /// `withCount=true`. + pub with_count: bool, +} + +/// A refused list query: the wire code and the members after it in the 400 body. +#[derive(Debug, Clone, PartialEq)] +pub struct Refusal { + pub code: &'static str, + pub details: Vec<(&'static str, Value)>, +} + +impl Refusal { + fn new(code: &'static str, details: Vec<(&'static str, Value)>) -> Self { + Refusal { code, details } + } + + /// The 400 body: `{ "error": code, ...details }`. + pub fn body(&self) -> Value { + let mut body = Map::new(); + body.insert("error".to_string(), Value::from(self.code)); + for (k, v) in &self.details { + body.insert((*k).to_string(), v.clone()); + } + Value::Object(body) + } +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.body()) + } +} + +impl std::error::Error for Refusal {} + +fn names<'a>(items: impl Iterator) -> Value { + Value::Array(items.map(Value::from).collect()) +} + +/// Parse `raw` (the query string as it arrives, with or without its leading `?`) against `spec`. +pub fn parse(raw: &str, spec: &ListSpec) -> Result { + let q = Params::parse(raw); + reject_bare_fields(&q, spec)?; + let mut out = ListQuery { + limit: page_bound(&q, "limit")?, + offset: page_bound(&q, "offset")?, + ..ListQuery::default() + }; + if let Some(Param::Map(f)) = q.get("filter") { + out.filter = node(f, spec, 0)?; + } + if let Some(Param::Scalar(s)) = q.get("sort") { + out.sort = Some(sort(s, spec)?); + } + if let Some(Param::Scalar(t)) = q.get("search") { + let fields = spec.search_fields(); + if !t.is_empty() && !fields.is_empty() { + out.search = Some(Search { term: t.clone(), fields }); + } + } + out.with_count = + matches!(q.get("withCount"), Some(Param::Scalar(s)) if s == "true" || s == "1"); + Ok(out) +} + +fn reject_bare_fields(q: &Params, spec: &ListSpec) -> Result<(), Refusal> { + for (key, value) in q.entries() { + if RESERVED.contains(&key) { + continue; + } + if spec.filter(key).is_some() { + let shown = match value { + Param::Scalar(s) => s.as_str(), + _ => "", + }; + return Err(Refusal::new( + "filter.bare_field", + vec![ + ("field", Value::from(key)), + ("expected", Value::from(format!("filter[{key}][eq]={shown}"))), + ], + )); + } + if spec.fields.contains(&key) { + return Err(Refusal::new( + "filter.bare_field", + vec![ + ("field", Value::from(key)), + ("filterable", Value::Bool(false)), + ( + "expected", + Value::from(format!("a filterable field — \"{key}\" is not @filterable")), + ), + ("allowed", spec.allowed()), + ], + )); + } + } + Ok(()) +} + +fn page_bound(q: &Params, param: &'static str) -> Result, Refusal> { + let Some(raw) = q.get(param) else { return Ok(None) }; + let s = raw.text(); + if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) { + if let Ok(n) = s.parse::() { + if n <= MAX_SAFE_INTEGER { + return Ok(Some(n)); + } + } + } + Err(Refusal::new( + "pagination.invalid_value", + vec![ + ("param", Value::from(param)), + ("value", Value::from(s)), + ("expected", Value::from(PAGINATION_EXPECTED)), + ], + )) +} + +fn node(map: &Params, spec: &ListSpec, depth: usize) -> Result, Refusal> { + if depth > MAX_NESTING { + return Err(Refusal::new( + "filter.nesting_too_deep", + vec![("limit", Value::from(MAX_NESTING))], + )); + } + let mut parts = Vec::new(); + for (key, value) in map.entries() { + if key == "or" || key == "and" { + let group = || Refusal::new("invalid_filter_value", vec![("field", Value::from(key))]); + let Param::Map(branches) = value else { return Err(group()) }; + let mut subs = Vec::new(); + for (_, branch) in branches.entries() { + let Param::Map(branch) = branch else { return Err(group()) }; + if let Some(sub) = node(branch, spec, depth + 1)? { + subs.push(sub); + } + } + match subs.len() { + 0 => {} + 1 => parts.push(subs.remove(0)), + _ if key == "or" => parts.push(Node::Or(subs)), + _ => parts.push(Node::And(subs)), + } + continue; + } + let Some(rule) = spec.filter(key) else { + return Err(Refusal::new( + "invalid_filter_field", + vec![("field", Value::from(key)), ("allowed", spec.allowed())], + )); + }; + match value { + Param::Map(ops) => { + for (op, operand) in ops.entries() { + parts.push(leaf(rule, op, &operand.text())?); + } + } + other => parts.push(leaf(rule, "eq", &other.text())?), + } + } + Ok(match parts.len() { + 0 => None, + 1 => parts.pop(), + _ => Some(Node::And(parts)), + }) +} + +fn leaf(rule: &FilterRule, op: &str, operand: &str) -> Result { + let field = rule.field; + if !rule.ops.contains(&op) { + return Err(Refusal::new( + "invalid_filter_op", + vec![ + ("field", Value::from(field)), + ("op", Value::from(op)), + ("allowed", names(rule.ops.iter().copied())), + ], + )); + } + let value = match op { + "in" => { + let list = operand + .split(',') + .map(|v| scalar(rule, op, v.trim())) + .collect::, _>>()?; + if list.len() > MAX_IN_LIST { + return Err(Refusal::new( + "filter.in_too_large", + vec![("field", Value::from(field)), ("limit", Value::from(MAX_IN_LIST))], + )); + } + Value::Array(list) + } + "like" => { + if operand.starts_with('%') { + return Err(Refusal::new( + "filter.leading_wildcard_disallowed", + vec![("field", Value::from(field))], + )); + } + Value::from(operand) + } + "isNull" => Value::Bool(boolean(operand, field, op)?), + _ => scalar(rule, op, operand)?, + }; + Ok(Node::Leaf { field: field.to_string(), op: op.to_string(), value }) +} + +fn invalid(field: &str, op: &str, expected: &str, extra: Option<(&'static str, Value)>) -> Refusal { + let mut details = vec![ + ("field", Value::from(field)), + ("op", Value::from(op)), + ("expected", Value::from(expected)), + ]; + details.extend(extra); + Refusal::new("invalid_filter_value", details) +} + +fn scalar(rule: &FilterRule, op: &str, s: &str) -> Result { + let field = rule.field; + if let Some(members) = rule.values { + if !members.contains(&s) { + let expected = format!("one of: {}", members.join(", ")); + let allowed = names(members.iter().copied()); + return Err(invalid(field, op, &expected, Some(("allowed", allowed)))); + } + } + let bad = |extra| invalid(field, op, rule.kind.expected().unwrap_or("number"), extra); + Ok(match rule.kind { + Kind::Text => Value::from(s), + Kind::Boolean => Value::Bool(boolean(s, field, op)?), + Kind::Integer | Kind::Number => number(rule, op, s)?, + Kind::Date if is_date(s) => Value::from(s), + Kind::Time if is_filter_time(s) => Value::from(s), + Kind::Uuid if is_uuid(s) => Value::from(s), + Kind::Decimal => match Decimal::parse(s) { + Ok(d) => Value::from(d.as_str()), + Err(_) => return Err(bad(None)), + }, + Kind::Duration if Duration::parse(s).is_ok() => Value::from(s), + Kind::Instant | Kind::LocalTimestamp => match Stamp::parse(s) { + Some(stamp) => Value::from(stamp.utc(s, rule.kind == Kind::Instant)), + None if unencoded_plus_offset(s) => { + return Err(bad(Some(("hint", Value::from(PLUS_OFFSET_HINT))))); + } + None => return Err(bad(None)), + }, + _ => return Err(bad(None)), + }) +} + +fn number(rule: &FilterRule, op: &str, s: &str) -> Result { + let t = s.trim(); + if rule.kind == Kind::Integer { + if let Ok(whole) = t.parse::() { + return Ok(Value::from(whole)); + } + } + let n = match t.parse::() { + Ok(n) if n.is_finite() && !t.is_empty() => n, + _ => return Err(invalid(rule.field, op, "number", None)), + }; + if rule.kind == Kind::Integer { + if n.fract() != 0.0 { + return Err(invalid(rule.field, op, INTEGER_EXPECTED, None)); + } + if n >= i64::MIN as f64 && n <= i64::MAX as f64 { + return Ok(Value::from(n as i64)); + } + } + Ok(Value::from(n)) +} + +fn boolean(s: &str, field: &str, op: &str) -> Result { + match s { + "true" | "1" => Ok(true), + "false" | "0" => Ok(false), + _ => Err(invalid(field, op, "boolean", None)), + } +} + +fn sort(spec_text: &str, spec: &ListSpec) -> Result { + let (field, order) = match spec_text.split_once(':') { + Some((field, order)) => (field, Some(order)), + None => (spec_text, None), + }; + let refuse = || { + Refusal::new( + "invalid_sort", + vec![ + ("field", Value::from(field)), + ("expected", Value::from(SORT_EXPECTED)), + ("allowed", names(spec.sorts.iter().map(|r| r.field))), + ], + ) + }; + let rule = spec.sorts.iter().find(|r| r.field == field).ok_or_else(refuse)?; + let descending = match order.map(str::to_ascii_lowercase).as_deref() { + None => rule.descending, + Some("asc") => false, + Some("desc") => true, + Some(_) => return Err(refuse()), + }; + Ok(Sort { field: field.to_string(), descending }) +} + +// ---- value formats ------------------------------------------------------------------------ + +fn two_digits(s: &str) -> Option { + (s.len() == 2 && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok())? +} + +/// `HH:MM`, `HH:MM:SS` or `HH:MM:SS.f` with one to nine fraction digits. +fn is_filter_time(s: &str) -> bool { + clock(s).is_some() +} + +/// The hour, minute, second and fraction digits of a time of day. +fn clock(s: &str) -> Option<(u32, u32, u32, &str)> { + let (hm, rest) = (s.get(..5)?, &s[5..]); + let (h, m) = hm.split_once(':')?; + let (h, m) = (two_digits(h)?, two_digits(m)?); + if h > 23 || m > 59 { + return None; + } + if rest.is_empty() { + return Some((h, m, 0, "")); + } + let sec = two_digits(rest.strip_prefix(':')?.get(..2)?)?; + let frac = &rest[3..]; + if sec > 59 { + return None; + } + if frac.is_empty() { + return Some((h, m, sec, "")); + } + let digits = frac.strip_prefix('.')?; + (!digits.is_empty() && digits.len() <= 9 && digits.bytes().all(|b| b.is_ascii_digit())) + .then_some((h, m, sec, digits)) +} + +/// A timestamp bound: a date, then optionally a `T`/space time, then optionally `Z` or a +/// `±HH[:]MM` offset. +struct Stamp<'a> { + date: &'a str, + hour: u32, + minute: u32, + second: u32, + fraction: &'a str, + /// The offset in minutes east of UTC, when the bound names a zone. + offset: Option, +} + +impl<'a> Stamp<'a> { + fn parse(s: &'a str) -> Option> { + let date = s.get(..10)?; + if !is_date(date) { + return None; + } + let mut stamp = Stamp { date, hour: 0, minute: 0, second: 0, fraction: "", offset: None }; + let rest = &s[10..]; + if rest.is_empty() { + return Some(stamp); + } + let rest = rest.strip_prefix(['T', 't', ' '])?; + let zone_at = rest.find(['Z', 'z', '+', '-']).unwrap_or(rest.len()); + let (time, zone) = rest.split_at(zone_at); + (stamp.hour, stamp.minute, stamp.second, stamp.fraction) = clock(time)?; + stamp.offset = match zone { + "" => None, + "Z" | "z" => Some(0), + _ => { + let sign = if zone.starts_with('-') { -1 } else { 1 }; + let digits = zone[1..].replacen(':', "", 1); + if digits.len() != 4 || zone[1..].len() > 5 { + return None; + } + let (h, m) = (two_digits(&digits[..2])?, two_digits(&digits[2..])?); + if h > 23 || m > 59 { + return None; + } + Some(sign * i64::from(h * 60 + m)) + } + }; + Some(stamp) + } + + /// The bound in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`), or `s` itself when it names no zone and + /// `zoneless_is_utc` is false (a wall clock), or is already spelled that way. + fn utc(&self, s: &str, zoneless_is_utc: bool) -> String { + if self.offset.is_none() && !zoneless_is_utc { + return s.to_string(); + } + let b = s.as_bytes(); + if b.get(10) == Some(&b'T') && b.get(16) == Some(&b':') && s.ends_with('Z') { + return s.to_string(); + } + let days = days_of(self.date); + let millis: i64 = + format!("{:0<3}", &self.fraction[..self.fraction.len().min(3)]).parse().unwrap_or(0); + let seconds = days * 86_400 + i64::from(self.hour * 3600 + self.minute * 60 + self.second) + - self.offset.unwrap_or(0) * 60; + let (day, second) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400)); + let (y, mo, d) = civil(day); + let mut text = format!( + "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", + second / 3600, + second / 60 % 60, + second % 60 + ); + if millis != 0 { + text.push_str(format!(".{millis:03}").trim_end_matches('0')); + } + text.push('Z'); + text + } +} + +/// A timestamp bound that fails only because its `+` offset arrived as a space. +fn unencoded_plus_offset(s: &str) -> bool { + let Some((head, zone)) = s.rsplit_once(' ') else { return false }; + let digits = |z: &str| z.bytes().all(|b| b.is_ascii_digit()); + let zone_ok = match zone.len() { + 2 | 4 => digits(zone), + 5 => zone.as_bytes()[2] == b':' && digits(&zone[..2]) && digits(&zone[3..]), + _ => false, + }; + zone_ok && head.len() >= 16 && Stamp::parse(head).is_some_and(|t| t.offset.is_none()) +} + +/// Days since 1970-01-01 of a valid `YYYY-MM-DD`. +fn days_of(date: &str) -> i64 { + let y: i64 = date[..4].parse().unwrap_or(1970); + let m: i64 = date[5..7].parse().unwrap_or(1); + let d: i64 = date[8..10].parse().unwrap_or(1); + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y.rem_euclid(400); + let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1; + era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468 +} + +/// The calendar date of a day count since 1970-01-01. +fn civil(days: i64) -> (i64, i64, i64) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (yoe + era * 400 + i64::from(m <= 2), m, d) +} + +// ---- the query string --------------------------------------------------------------------- + +/// One parameter of the bracket grammar: `a[b][c]=v` nests, and a repeated key collects its +/// values. +enum Param { + Scalar(String), + Many(Vec), + Map(Params), +} + +impl Param { + /// The value as text; a repeated value is its parts joined by commas. + fn text(&self) -> String { + match self { + Param::Scalar(s) => s.clone(), + Param::Many(v) => v.join(","), + Param::Map(_) => "[object Object]".to_string(), + } + } +} + +/// A map of parameters. Its entries come back with array-index keys first, in numeric order, +/// and every other key in the order it was sent, the way the TypeScript routes read them. +#[derive(Default)] +struct Params { + order: Vec, + values: HashMap, +} + +impl Params { + fn get(&self, key: &str) -> Option<&Param> { + self.values.get(key) + } + + fn entries(&self) -> Vec<(&str, &Param)> { + let mut index: Vec<(u64, &str)> = + self.order.iter().filter_map(|k| array_index(k).map(|i| (i, k.as_str()))).collect(); + index.sort_by_key(|(i, _)| *i); + index + .into_iter() + .map(|(_, k)| k) + .chain(self.order.iter().map(String::as_str).filter(|k| array_index(k).is_none())) + .map(|k| (k, &self.values[k])) + .collect() + } + + fn set(&mut self, path: &[String], value: String) { + let key = &path[0]; + if path.len() == 1 { + match self.values.get_mut(key) { + None => self.add(key, Param::Scalar(value)), + Some(Param::Scalar(first)) => { + let first = std::mem::take(first); + self.values.insert(key.clone(), Param::Many(vec![first, value])); + } + Some(Param::Many(all)) => all.push(value), + // A scalar sent beside a map under the same key: the map keeps its members. + Some(Param::Map(_)) => {} + } + return; + } + if !matches!(self.values.get(key), Some(Param::Map(_))) { + if self.values.contains_key(key) { + self.values.insert(key.clone(), Param::Map(Params::default())); + } else { + self.add(key, Param::Map(Params::default())); + } + } + if let Some(Param::Map(child)) = self.values.get_mut(key) { + child.set(&path[1..], value); + } + } + + fn add(&mut self, key: &str, value: Param) { + self.order.push(key.to_string()); + self.values.insert(key.to_string(), value); + } + + fn parse(raw: &str) -> Params { + let mut root = Params::default(); + let raw = raw.strip_prefix('?').unwrap_or(raw); + for pair in raw.split('&').filter(|p| !p.is_empty()) { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let path = key_path(&decode(key)); + if path.first().is_some_and(|k| !k.is_empty()) { + root.set(&path, decode(value)); + } + } + root + } +} + +/// A JavaScript array index: a canonical non-negative integer below 2^32 - 1. +fn array_index(k: &str) -> Option { + let canonical = !k.is_empty() + && k.len() <= 10 + && k.bytes().all(|b| b.is_ascii_digit()) + && (k == "0" || !k.starts_with('0')); + canonical.then(|| k.parse().ok()).flatten().filter(|&n: &u64| n < 4_294_967_295) +} + +/// `a[b][c]` is a, b, c. Text after the last balanced bracket pair, or an unclosed `[`, stays +/// part of the last segment. +fn key_path(key: &str) -> Vec { + let Some(open) = key.find('[').filter(|&at| at > 0) else { return vec![key.to_string()] }; + let mut path = vec![key[..open].to_string()]; + let mut i = open; + while key[i..].starts_with('[') { + let Some(close) = key[i + 1..].find(']') else { break }; + path.push(key[i + 1..i + 1 + close].to_string()); + i += close + 2; + } + if i < key.len() { + if let Some(last) = path.last_mut() { + last.push_str(&key[i..]); + } + } + path +} + +/// Percent-decode `s`, with `+` a space. A `%` that does not start a `%XX` escape is kept. +fn decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) { + (Some(hi), Some(lo)) => { + out.push(hi * 16 + lo); + i += 2; + } + _ => out.push(b'%'), + }, + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn hex(b: u8) -> Option { + (b as char).to_digit(16).map(|d| d as u8) +} diff --git a/examples/rust-service/generated/meta_service/Cargo.toml b/examples/rust-service/generated/meta_service/Cargo.toml new file mode 100644 index 0000000000..e06e95e1bb --- /dev/null +++ b/examples/rust-service/generated/meta_service/Cargo.toml @@ -0,0 +1,20 @@ +# @generated by the MetaObjects service generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "meta_service" +version = "0.1.0" +edition = "2021" +publish = false +description = "The service layer mechanics of the generated MetaObjects service crates." + +[features] +default = ["postgres", "sqlite"] +postgres = ["sqlx/postgres", "meta_store/postgres"] +sqlite = ["sqlx/sqlite", "meta_store/sqlite"] + +[dependencies] +meta_store = { path = "../meta_store", default-features = false } +meta_support = { path = "../meta_support" } +chrono = { version = "0.4", default-features = false, features = ["clock"] } +serde = "1" +serde_json = "1" +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio"] } diff --git a/examples/rust-service/generated/meta_service/rustfmt.toml b/examples/rust-service/generated/meta_service/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/meta_service/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/meta_service/src/lib.rs b/examples/rust-service/generated/meta_service/src/lib.rs new file mode 100644 index 0000000000..e77d99f306 --- /dev/null +++ b/examples/rust-service/generated/meta_service/src/lib.rs @@ -0,0 +1,412 @@ +// @generated by the MetaObjects service generator. Do not edit: change the model and run `cargo meta gen`. + +//! The service layer's mechanics for the `service` generator's crates (ADR-0067 layer 4): the +//! errors an operation answers with, the store it opens a transaction on, the event a write +//! reports, and the list page. +//! +//! What runs, in which order and against which table is written into each package's service +//! crate; this crate holds only what every one of them shares. It knows the wire codes of +//! ADR-0066 §6 and nothing of HTTP: the status of each is here so a transport maps an error the +//! same way in every app. + +use std::fmt; +use std::future::Future; +use std::ops::DerefMut; + +use meta_store::{Conn, StoreError}; +use meta_support::validation::Violation; +use serde::Serialize; +use serde_json::Value; + +/// The page size a list answers with when the query names no limit, the same in every port. +pub const DEFAULT_LIMIT: u64 = 50; + +/// Why an operation did not complete. Each answers one wire code (ADR-0066 §6). +#[derive(Debug)] +pub enum ServiceError { + /// 404 `not_found`: no row has the key. + NotFound, + /// 403 `forbidden`: the policy refused the permission point. + Forbidden, + /// 409 `invalid_transition`: the row is in no state the move leaves. + InvalidTransition, + /// 409 `transition_condition_failed`: the move's `@condition` does not hold for the row. + TransitionConditionFailed, + /// 409 `state_managed`: a write that is not a transition named another state of a lifecycle. + StateManaged, + /// 400 `validation`: the body breaks the model's rules. Every one is listed. + Validation(Vec), + /// 400 `limit_too_large`: a list asked for more rows than the page allows. + LimitTooLarge { max: u64 }, + /// 409 with the code: a hook, the event hook or a body refused (a declared `@errors` code + /// is answered this way too). + Refused { code: String, message: Option }, + /// The data access failed. + Store(StoreError), +} + +impl ServiceError { + /// A refusal by `code`, as a hook or the event hook returns one. + pub fn refused(code: impl Into) -> Self { + ServiceError::Refused { code: code.into(), message: None } + } + + /// Its wire code. + pub fn code(&self) -> &str { + match self { + ServiceError::NotFound => "not_found", + ServiceError::Forbidden => "forbidden", + ServiceError::InvalidTransition => "invalid_transition", + ServiceError::TransitionConditionFailed => "transition_condition_failed", + ServiceError::StateManaged => "state_managed", + ServiceError::Validation(_) => "validation", + ServiceError::LimitTooLarge { .. } => "limit_too_large", + ServiceError::Refused { code, .. } => code, + ServiceError::Store(StoreError::UnknownField { .. } | StoreError::BadValue { .. }) => { + "validation" + } + ServiceError::Store(_) => "internal", + } + } + + /// Its HTTP status. + pub fn status(&self) -> u16 { + match self { + ServiceError::NotFound => 404, + ServiceError::Forbidden => 403, + ServiceError::InvalidTransition + | ServiceError::TransitionConditionFailed + | ServiceError::StateManaged + | ServiceError::Refused { .. } => 409, + ServiceError::Validation(_) | ServiceError::LimitTooLarge { .. } => 400, + ServiceError::Store(StoreError::UnknownField { .. } | StoreError::BadValue { .. }) => { + 400 + } + ServiceError::Store(_) => 500, + } + } +} + +impl fmt::Display for ServiceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ServiceError::Validation(v) => write!(f, "validation: {} problem(s)", v.len()), + ServiceError::LimitTooLarge { max } => write!(f, "limit_too_large: at most {max}"), + ServiceError::Refused { code, message: Some(m) } => write!(f, "{code}: {m}"), + ServiceError::Store(e) => write!(f, "{e}"), + other => f.write_str(other.code()), + } + } +} + +impl std::error::Error for ServiceError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + ServiceError::Store(e) => Some(e), + _ => None, + } + } +} + +impl From for ServiceError { + fn from(e: StoreError) -> Self { + ServiceError::Store(e) + } +} + +/// What a declared operation's body may fail with: one of the operation's own `@errors` +/// (`B`, its contract's business error type), or any service error. +#[derive(Debug)] +pub enum BodyError { + Business(B), + Service(ServiceError), +} + +impl From for BodyError { + fn from(e: ServiceError) -> Self { + BodyError::Service(e) + } +} + +impl From for BodyError { + fn from(e: StoreError) -> Self { + BodyError::Service(ServiceError::Store(e)) + } +} + +impl BodyError { + /// The service error it answers with: a business error is a refusal by its code. + pub fn into_service(self) -> ServiceError { + match self { + BodyError::Service(e) => e, + BodyError::Business(b) => match serde_json::to_value(&b) { + Ok(Value::String(code)) => ServiceError::refused(code), + _ => ServiceError::refused("internal"), + }, + } + } +} + +/// Refuses a body that breaks a rule of the model. +pub fn validated(violations: Vec) -> Result<(), ServiceError> { + if violations.is_empty() { + Ok(()) + } else { + Err(ServiceError::Validation(violations)) + } +} + +// ---- the store --------------------------------------------------------------------------- + +/// A store a service runs on: a pool it reads from and opens transactions on. Implemented for +/// `sqlx::PgPool` and `sqlx::SqlitePool`. +pub trait Db: Send + Sync { + /// The connection the generated store functions run on. + type Conn: Conn; + /// A transaction: dropped without [`Db::commit`], it is rolled back. + type Tx: DerefMut + Send; + /// A pooled connection for a read. + type Read: DerefMut + Send; + + fn begin(&self) -> impl Future> + Send; + fn commit(tx: Self::Tx) -> impl Future> + Send; + fn rollback(tx: Self::Tx) -> impl Future> + Send; + fn read(&self) -> impl Future> + Send; +} + +#[cfg(feature = "postgres")] +impl Db for sqlx::PgPool { + type Conn = sqlx::PgConnection; + type Tx = sqlx::Transaction<'static, sqlx::Postgres>; + type Read = sqlx::pool::PoolConnection; + + async fn begin(&self) -> Result { + Ok(sqlx::Pool::begin(self).await?) + } + async fn commit(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.commit().await?) + } + async fn rollback(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.rollback().await?) + } + async fn read(&self) -> Result { + Ok(self.acquire().await?) + } +} + +#[cfg(feature = "sqlite")] +impl Db for sqlx::SqlitePool { + type Conn = sqlx::SqliteConnection; + type Tx = sqlx::Transaction<'static, sqlx::Sqlite>; + type Read = sqlx::pool::PoolConnection; + + async fn begin(&self) -> Result { + Ok(sqlx::Pool::begin(self).await?) + } + async fn commit(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.commit().await?) + } + async fn rollback(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.rollback().await?) + } + async fn read(&self) -> Result { + Ok(self.acquire().await?) + } +} + +/// Ends the transaction `tx` an operation ran in: committed when `out` is a success, rolled +/// back when it is a refusal, so a refusal anywhere undoes every write before it. +pub async fn finish(tx: D::Tx, out: Result) -> Result { + match out { + Ok(v) => { + D::commit(tx).await?; + Ok(v) + } + Err(e) => { + // The refusal is the answer; a failed rollback is the connection's to report. + let _ = D::rollback(tx).await; + Err(e) + } + } +} + +// ---- what hand-written code is handed ---------------------------------------------------- + +/// What a body or a hook runs with: the operation's connection (inside its transaction for a +/// write) and the actor it runs for. +pub struct Cx<'a, A, C: ?Sized> { + pub conn: &'a mut C, + pub actor: Option<&'a A>, +} + +/// What kind of write an event reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WriteKind { + Create, + Update, + Delete, + /// A lifecycle moved: a transition's derived command, or a declared command that moved it. + Transition, + /// A declared command that made no move. + Command, +} + +impl WriteKind { + /// Its name, as the other ports' events spell it. + pub const fn as_str(self) -> &'static str { + match self { + WriteKind::Create => "create", + WriteKind::Update => "update", + WriteKind::Delete => "delete", + WriteKind::Transition => "transition", + WriteKind::Command => "command", + } + } +} + +/// A write, as the event hook is told of it: last, inside the write's transaction, so a +/// refusal undoes the write. +#[derive(Debug)] +pub struct WriteEvent<'a, A> { + pub kind: WriteKind, + /// The entity written; `None` for a declared command with no target. + pub entity: Option<&'static str>, + /// The key of the row written. + pub key: Option, + /// The operation that wrote: a declared command, or a transition's derived command. + pub operation: Option<&'static str>, + /// For a transition: the lifecycle's field, the transition, and the states. + pub lifecycle: Option<&'static str>, + pub transition: Option<&'static str>, + pub from: Option, + pub to: Option, + /// The row as written (a create or an update), or as it was (a delete). + pub row: Option, + /// The row before an update. + pub previous: Option, + pub actor: Option<&'a A>, +} + +impl<'a, A> WriteEvent<'a, A> { + /// An event of `kind` with nothing else said. + pub fn new(kind: WriteKind, actor: Option<&'a A>) -> Self { + WriteEvent { + kind, + entity: None, + key: None, + operation: None, + lifecycle: None, + transition: None, + from: None, + to: None, + row: None, + previous: None, + actor, + } + } +} + +/// `value` as JSON, for a policy, an event or a key. +pub fn json(value: &T) -> Value { + serde_json::to_value(value).unwrap_or(Value::Null) +} + +/// The instant a write stamps an `@autoSet` timestamp with (ADR-0045): ISO 8601 in UTC, to the +/// millisecond, with its zone, or with none for a `@localTime` field. +pub fn now(local_time: bool) -> String { + let now = chrono::Utc::now(); + if local_time { + now.naive_utc().format("%Y-%m-%dT%H:%M:%S%.3f").to_string() + } else { + now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true) + } +} + +/// The wire spelling of a state. +pub fn state_name(state: &S) -> String { + match json(state) { + Value::String(s) => s, + other => other.to_string(), + } +} + +// ---- lists ------------------------------------------------------------------------------- + +/// A page of a list. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Page { + pub rows: Vec, + /// The number of rows the filter selects, when the list asked for it. + #[serde(skip_serializing_if = "Option::is_none")] + pub total: Option, +} + +/// The page size of a list: the query's limit, else `default`; refused above `max`. +pub fn page_limit(limit: Option, default: u64, max: Option) -> Result { + match (limit, max) { + (Some(l), Some(m)) if l > m => Err(ServiceError::LimitTooLarge { max: m }), + (Some(l), _) => Ok(l), + (None, _) => Ok(default), + } +} + +// ---- lifecycles -------------------------------------------------------------------------- + +/// Whether `state` (a row's lifecycle field, an `Option` of the state or the state) is one of +/// `from`. +pub fn in_state(state: &S, from: &[F]) -> bool { + let state = json(state); + from.iter().any(|f| json(f) == state) +} + +/// One move of a lifecycle, as [`make_move`] makes it: `field` from one of `from` to `to`, under +/// `condition` (the move's `@condition` as JSON) when it has one. +#[derive(Debug, Clone, Copy)] +pub struct Move<'a, S> { + pub field: &'a str, + pub from: &'a [S], + pub to: S, + pub condition: Option<&'a str>, +} + +/// Makes the move `m` on the row `key` names: the guarded update of ADR-0066 §6 step 5. A row +/// another write moved first is `invalid_transition`, and one still in `from` whose condition +/// does not hold is `transition_condition_failed`. +pub async fn make_move( + conn: &mut C, + table: &meta_store::Table, + key: &(impl Serialize + Sync + ?Sized), + m: &Move<'_, S>, +) -> Result<(), ServiceError> +where + S: Serialize + Sync, + C: Conn + ?Sized, +{ + let condition = match m.condition { + Some(text) => { + let value: Value = serde_json::from_str(text).map_err(|e| { + ServiceError::Store(StoreError::BadValue { + field: m.field.to_string(), + message: e.to_string(), + }) + })?; + Some(meta_store::Condition::from_json(&value)?) + } + None => None, + }; + let (from, to) = (m.from, &m.to); + let condition_ref = condition.as_ref(); + if meta_store::transition(&mut *conn, table, key, m.field, from, to, condition_ref).await? { + return Ok(()); + } + let now: Option = meta_store::get(&mut *conn, table, key).await?; + let Some(now) = now else { + return Err(ServiceError::NotFound); + }; + let still = in_state(now.get(m.field).unwrap_or(&Value::Null), from); + Err(if still && condition.is_some() { + ServiceError::TransitionConditionFailed + } else { + ServiceError::InvalidTransition + }) +} diff --git a/examples/rust-service/generated/meta_store/Cargo.toml b/examples/rust-service/generated/meta_store/Cargo.toml new file mode 100644 index 0000000000..5531add64c --- /dev/null +++ b/examples/rust-service/generated/meta_store/Cargo.toml @@ -0,0 +1,19 @@ +# @generated by the MetaObjects repository generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "meta_store" +version = "0.1.0" +edition = "2021" +publish = false +description = "Data access over sqlx for the generated MetaObjects store crates." + +[features] +default = ["postgres", "sqlite"] +postgres = ["sqlx/postgres"] +sqlite = ["sqlx/sqlite"] + +[dependencies] +meta_support = { path = "../meta_support" } +chrono = { version = "0.4", default-features = false, features = ["std"] } +serde = "1" +serde_json = "1" +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "chrono", "json"] } diff --git a/examples/rust-service/generated/meta_store/rustfmt.toml b/examples/rust-service/generated/meta_store/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/meta_store/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/meta_store/src/lib.rs b/examples/rust-service/generated/meta_store/src/lib.rs new file mode 100644 index 0000000000..d301fedee7 --- /dev/null +++ b/examples/rust-service/generated/meta_store/src/lib.rs @@ -0,0 +1,1656 @@ +// @generated by the MetaObjects repository generator. Do not edit: change the model and run `cargo meta gen`. + +//! Data access over sqlx for the `repository` generator's crates: a table described as data, +//! the list query (the nine filter operators, sort and paging), and the reads and writes on +//! Postgres and SQLite. +//! +//! A row is read into the JSON a model type deserializes from, and a body a caller sends is +//! serialized to JSON and bound column by column, so the model types stay free of sqlx and a +//! store crate is a table descriptor and a few typed functions over this one. +//! +//! The wire forms are the ones every port's runtime reads and writes +//! (`fixtures/persistence-conformance/normalization.md`): on SQLite a boolean is `0`/`1`, a +//! duration is its length in microseconds, a JSON value and an array are JSON text, and a +//! timestamp is the text the caller sent. A null sorts after every value (ascending) and +//! before every value (descending) on both engines. + +use std::fmt; +use std::future::Future; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; + +/// How a column holds its value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Text, + Int, + Long, + Double, + Float, + Bool, + Decimal, + Date, + Time, + /// A wall-clock timestamp (`@localTime`): no zone. + Timestamp, + /// An instant, read back in UTC. + TimestampTz, + Uuid, + Inet, + Duration, + /// A value object or a map, stored as one JSON column. + Json, + /// An enum stored as an integer (`@intValueMap`): each member and its stored value. + IntEnum(&'static [(&'static str, i64)]), + /// An enum stored as other text (`@stringValueMap`): each member and its stored text. + StringEnum(&'static [(&'static str, &'static str)]), +} + +/// One column of a table: the model field it holds and how. +#[derive(Debug, Clone, Copy)] +pub struct Column { + /// The field's name in the model, which is its name on the wire. + pub field: &'static str, + /// The column's name in the database. + pub column: &'static str, + pub kind: Kind, + /// An array of `kind`: a native array on Postgres, JSON text on SQLite. An array of + /// value objects is one `Json` column instead. + pub array: bool, + /// The column's own SQL type when the model names one (`@dbColumnType`), as a string held + /// in a `uuid` or `jsonb` column: Postgres casts to it on a write and back on a read. + pub stored_as: Option<&'static str>, +} + +impl Column { + /// A column holding one value of `kind`. + pub const fn new(field: &'static str, column: &'static str, kind: Kind) -> Column { + Column { field, column, kind, array: false, stored_as: None } + } + + /// A column holding a list of `kind`. + pub const fn list(field: &'static str, column: &'static str, kind: Kind) -> Column { + Column { field, column, kind, array: true, stored_as: None } + } + + /// A column holding one value of `kind` in its own SQL type `ty`. + pub const fn typed( + field: &'static str, + column: &'static str, + kind: Kind, + ty: &'static str, + ) -> Column { + Column { field, column, kind, array: false, stored_as: Some(ty) } + } + + /// A column holding a list of `kind` in its own SQL type `ty` (of each element). + pub const fn typed_list( + field: &'static str, + column: &'static str, + kind: Kind, + ty: &'static str, + ) -> Column { + Column { field, column, kind, array: true, stored_as: Some(ty) } + } +} + +/// A table or view a store reads, and writes when it is writable. +#[derive(Debug, Clone, Copy)] +pub struct Table { + /// The object's name in the model, for messages. + pub object: &'static str, + pub schema: Option<&'static str>, + pub name: &'static str, + /// The field of the primary key; `None` for a keyless view. + pub key: Option<&'static str>, + pub columns: &'static [Column], + pub writable: bool, + /// For a subtype of a single-table hierarchy: the discriminator field and this subtype's + /// stored value. Every read and write is scoped to it, and a create sets it. + pub discriminator: Option<(&'static str, &'static str)>, + /// The view the rows are read from, when it is not this table (an entity that writes a + /// table and reads a view, carrying the derived fields the table does not store). Every + /// read goes to it, and a write reads its row back from it. + pub read: Option<&'static Table>, +} + +impl Table { + /// What the rows are read from: the read view, else the table itself. + pub fn reader(&self) -> &Table { + self.read.unwrap_or(self) + } + + /// The column of a model field. + pub fn column(&self, field: &str) -> Result<&Column, StoreError> { + self.columns.iter().find(|c| c.field == field).ok_or_else(|| StoreError::UnknownField { + object: self.object, + field: field.to_string(), + }) + } + + fn key_column(&self) -> Result<&Column, StoreError> { + match self.key { + Some(k) => self.column(k), + None => Err(StoreError::Unsupported(format!("{} has no primary key", self.object))), + } + } + + fn require_writable(&self) -> Result<(), StoreError> { + if self.writable { + Ok(()) + } else { + Err(StoreError::Unsupported(format!("{} is read-only", self.object))) + } + } +} + +/// The junction of a many-to-many relationship: the table and the two columns that hold the +/// keys of the rows it relates. +#[derive(Debug, Clone, Copy)] +pub struct Through { + pub schema: Option<&'static str>, + pub name: &'static str, + /// The column that holds the key of the row the relationship is navigated from. + pub source: Column, + /// The column that holds the key of a related row. + pub target: Column, + /// An undirected self-join: a row relates each of its two sides to the other, so a row + /// `(a, b)` answers from `a` and from `b`. + pub symmetric: bool, +} + +/// A data-access failure. +#[derive(Debug)] +pub enum StoreError { + /// A query or a body names a field the object does not have. + UnknownField { + object: &'static str, + field: String, + }, + /// A value does not fit its column, or a filter does not fit its field. + BadValue { + field: String, + message: String, + }, + /// A stored value the model does not describe. + Decode { + field: String, + message: String, + }, + Unsupported(String), + Database(sqlx::Error), +} + +impl fmt::Display for StoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + StoreError::UnknownField { object, field } => { + write!(f, "{object} has no field `{field}`") + } + StoreError::BadValue { field, message } => write!(f, "`{field}`: {message}"), + StoreError::Decode { field, message } => write!(f, "reading `{field}`: {message}"), + StoreError::Unsupported(m) => f.write_str(m), + StoreError::Database(e) => write!(f, "{e}"), + } + } +} + +impl std::error::Error for StoreError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + StoreError::Database(e) => Some(e), + _ => None, + } + } +} + +impl From for StoreError { + fn from(e: sqlx::Error) -> Self { + StoreError::Database(e) + } +} + +fn bad(field: &str, message: impl Into) -> StoreError { + StoreError::BadValue { field: field.to_string(), message: message.into() } +} + +fn decode_err(field: &str, message: impl fmt::Display) -> StoreError { + StoreError::Decode { field: field.to_string(), message: message.to_string() } +} + +// ---- the list query ------------------------------------------------------------------ + +/// A filter operator. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Op { + Eq, + Ne, + Gt, + Gte, + Lt, + Lte, + In, + Like, + IsNull, +} + +impl Op { + /// The operator of its wire name. + pub fn of(name: &str) -> Option { + Some(match name { + "eq" => Op::Eq, + "ne" => Op::Ne, + "gt" => Op::Gt, + "gte" => Op::Gte, + "lt" => Op::Lt, + "lte" => Op::Lte, + "in" => Op::In, + "like" => Op::Like, + "isNull" => Op::IsNull, + _ => return None, + }) + } + + fn sql(self) -> &'static str { + match self { + Op::Eq => "=", + Op::Ne => "<>", + Op::Gt => ">", + Op::Gte => ">=", + Op::Lt => "<", + Op::Lte => "<=", + Op::Like => "LIKE", + Op::In | Op::IsNull => "", + } + } +} + +/// A condition on a model's fields. +#[derive(Debug, Clone, PartialEq)] +pub enum Filter { + Field { + field: String, + op: Op, + value: Value, + }, + /// Every one holds; none is always true. + And(Vec), + /// At least one holds; none is always false. + Or(Vec), + /// A case-insensitive substring match of `term` on any of `fields` (text), the list + /// route's `?search`. `%` and `_` in the term keep their `LIKE` meaning. + Search { + term: String, + fields: Vec, + }, +} + +impl Filter { + pub fn field(field: impl Into, op: Op, value: impl Into) -> Filter { + Filter::Field { field: field.into(), op, value: value.into() } + } + + /// The filter of its JSON form: `{ "": { "": value }, "and": [ ... ], "or": [ ... ] }`, + /// each key one more condition ANDed with the rest. + pub fn from_json(value: &Value) -> Result { + let Value::Object(map) = value else { + return Err(bad("filter", "a filter is an object")); + }; + let mut all = Vec::new(); + for (key, v) in map { + if key == "and" || key == "or" { + let Value::Array(items) = v else { + return Err(bad(key, format!("`{key}` is a list of filters"))); + }; + let items = items.iter().map(Filter::from_json).collect::, _>>()?; + match key.as_str() { + "and" => all.extend(items), + _ => all.push(Filter::Or(items)), + } + continue; + } + let Value::Object(ops) = v else { + return Err(bad(key, "a field's condition is an object of operators")); + }; + for (op, operand) in ops { + let op = Op::of(op).ok_or_else(|| bad(key, format!("unknown operator `{op}`")))?; + all.push(Filter::field(key.clone(), op, operand.clone())); + } + } + Ok(if all.len() == 1 { all.remove(0) } else { Filter::And(all) }) + } +} + +/// A transition's `@condition` (ADR-0066 §1): attr.expression's CHECK subset, the six +/// comparisons, the null tests, and, or, not and coalesce, over a model's FIELD names. The +/// guarded update ANDs it into the one statement that makes the move. +#[derive(Debug, Clone, PartialEq)] +pub enum Condition { + /// One of `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + Compare { + op: Op, + left: Operand, + right: Operand, + }, + /// `isNull`, or `isNotNull` when `not`. + IsNull { + operand: Operand, + not: bool, + }, + Not(Box), + And(Vec), + Or(Vec), +} + +/// One side of a comparison in a [`Condition`]. +#[derive(Debug, Clone, PartialEq)] +pub enum Operand { + Field(String), + /// A literal: compared with a field, it is written in the form that field's column stores + /// (an int-backed enum's member is its integer), as a filter value is. + Value(Value), + Coalesce(Vec), +} + +impl Condition { + /// The condition of its JSON form, a node of the `@condition` grammar. A node outside the + /// grammar is refused rather than dropped: a guard that loses its condition makes a move the + /// model forbids. + pub fn from_json(node: &Value) -> Result { + let op = node.get("op").and_then(Value::as_str).unwrap_or(""); + let arg = |key: &str| { + node.get(key).ok_or_else(|| bad("condition", format!("`{op}` takes `{key}`"))) + }; + let args = || match node.get("args") { + Some(Value::Array(items)) => items.iter().map(Condition::from_json).collect(), + _ => Err(bad("condition", format!("`{op}` takes a list `args`"))), + }; + Ok(match op { + "and" => Condition::And(args()?), + "or" => Condition::Or(args()?), + "not" => Condition::Not(Box::new(Condition::from_json(arg("arg")?)?)), + "isNull" | "isNotNull" => Condition::IsNull { + operand: Operand::from_json(arg("arg")?)?, + not: op == "isNotNull", + }, + _ => match Op::of(op) { + Some(o @ (Op::Eq | Op::Ne | Op::Gt | Op::Gte | Op::Lt | Op::Lte)) => { + Condition::Compare { + op: o, + left: Operand::from_json(arg("left")?)?, + right: Operand::from_json(arg("right")?)?, + } + } + _ => { + return Err(bad( + "condition", + format!("{node} is not a condition the guarded update can apply"), + )) + } + }, + }) + } +} + +impl Operand { + /// The operand of its JSON form: `{ "field": name }`, `{ "value": literal }` or + /// `{ "fn": "coalesce", "args": [ ... ] }`. + pub fn from_json(node: &Value) -> Result { + if let Some(field) = node.get("field").and_then(Value::as_str) { + return Ok(Operand::Field(field.to_string())); + } + if let Some(v) = node.get("value") { + return Ok(Operand::Value(v.clone())); + } + if let (Some("coalesce"), Some(Value::Array(items))) = + (node.get("fn").and_then(Value::as_str), node.get("args")) + { + return Ok(Operand::Coalesce( + items.iter().map(Operand::from_json).collect::>()?, + )); + } + Err(bad("condition", format!("{node} is not an operand the guarded update can apply"))) + } + + /// The field whose stored form a literal compared with this operand takes: the field + /// itself, or a coalesce's first field. + fn stored_field(&self) -> Option<&str> { + match self { + Operand::Field(f) => Some(f), + Operand::Value(_) => None, + Operand::Coalesce(items) => items.iter().find_map(Operand::stored_field), + } + } +} + +/// An order on one field. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sort { + pub field: String, + pub descending: bool, +} + +/// What a list reads: a filter, an order, and a page. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Query { + pub filter: Option, + pub sort: Vec, + pub limit: Option, + pub offset: Option, +} + +// ---- connections --------------------------------------------------------------------- + +/// The engine a connection talks to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Engine { + Postgres, + Sqlite, +} + +/// A value bound to a placeholder. +#[derive(Debug, Clone, PartialEq)] +pub enum Bind { + Null, + Bool(bool), + Int(i64), + Real(f64), + Text(String), + Ints(Vec), + Texts(Vec), +} + +/// A database connection a store runs on: a Postgres or a SQLite connection, or a +/// transaction on one (`&mut *tx`). +pub trait Conn: Send { + fn engine(&self) -> Engine; + + /// Runs `sql` and reads every row, each column decoded as `columns` says, in order. + fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> impl Future>, StoreError>> + Send + 'a; + + /// Runs `sql` and reads the one integer its one row holds. + fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> impl Future> + Send + 'a; + + /// Runs `sql` and answers the number of rows it changed. + fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> impl Future> + Send + 'a; +} + +/// A statement as it is built: its text and its binds, numbered for the engine. +struct Sql { + engine: Engine, + text: String, + binds: Vec, +} + +impl Sql { + fn new(engine: Engine) -> Self { + Sql { engine, text: String::new(), binds: Vec::new() } + } + + fn push(&mut self, s: &str) { + self.text.push_str(s); + } + + /// A placeholder for `bind`, cast to the column's type on Postgres. + fn param(&mut self, bind: Bind, column: &Column) { + self.binds.push(bind); + match self.engine { + Engine::Postgres => { + let n = self.binds.len(); + let ty = pg_type(column); + self.text.push_str(&format!("CAST(${n} AS {ty})")); + } + Engine::Sqlite => self.text.push('?'), + } + } + + /// A placeholder for a literal with no column to take its type from. + fn raw_param(&mut self, bind: Bind) { + self.binds.push(bind); + match self.engine { + Engine::Postgres => self.text.push_str(&format!("${}", self.binds.len())), + Engine::Sqlite => self.text.push('?'), + } + } +} + +fn quote(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn table_ref(table: &Table) -> String { + match table.schema { + Some(s) => format!("{}.{}", quote(s), quote(table.name)), + None => quote(table.name), + } +} + +fn pg_type(c: &Column) -> String { + if let Some(ty) = c.stored_as { + return if c.array { format!("{ty}[]") } else { ty.to_string() }; + } + logical_pg_type(c) +} + +/// The Postgres type the model's `kind` reads as. +fn logical_pg_type(c: &Column) -> String { + let base = match c.kind { + Kind::Text | Kind::StringEnum(_) => "text", + Kind::Int | Kind::IntEnum(_) => "integer", + Kind::Long => "bigint", + Kind::Double => "double precision", + Kind::Float => "real", + Kind::Bool => "boolean", + Kind::Decimal => "numeric", + Kind::Date => "date", + Kind::Time => "time", + Kind::Timestamp => "timestamp", + Kind::TimestampTz => "timestamptz", + Kind::Uuid => "uuid", + Kind::Inet => "inet", + Kind::Duration => "interval", + Kind::Json => return "jsonb".to_string(), + }; + if c.array { + format!("{base}[]") + } else { + base.to_string() + } +} + +/// What a SELECT reads for a column: on Postgres an exact decimal and a uuid as text, an +/// address without its netmask, and a column of its own SQL type as the type of its kind. A +/// view's number is read as the type of its kind too, because the view's SQL decides its +/// column's type (`AVG` of an integer is `NUMERIC` on Postgres). +fn read_expr(engine: Engine, table: &Table, c: &Column) -> String { + let col = quote(c.column); + let view_number = !table.writable + && !c.array + && matches!(c.kind, Kind::Int | Kind::Long | Kind::Double | Kind::Float); + if engine == Engine::Postgres && (c.stored_as.is_some() || view_number) { + return format!("CAST({col} AS {})", logical_pg_type(c)); + } + match (engine, c.kind, c.array) { + (Engine::Postgres, Kind::Decimal | Kind::Uuid, false) => format!("{col}::text"), + (Engine::Postgres, Kind::Decimal | Kind::Uuid, true) => format!("{col}::text[]"), + (Engine::Postgres, Kind::Inet, false) => format!("host({col})"), + _ => col, + } +} + +fn select_list(engine: Engine, table: &Table) -> String { + table.columns.iter().map(|c| read_expr(engine, table, c)).collect::>().join(", ") +} + +// ---- binding a JSON value ---------------------------------------------------------------- + +fn text_of<'v>(field: &str, v: &'v Value, what: &str) -> Result<&'v str, StoreError> { + v.as_str().ok_or_else(|| bad(field, format!("{what} is a string"))) +} + +fn int_of(field: &str, v: &Value) -> Result { + if let Some(i) = v.as_i64() { + return Ok(i); + } + // A 64-bit value may arrive as its base-10 text, so it survives a JSON number. + if let Some(i) = v.as_str().and_then(|s| s.parse::().ok()) { + return Ok(i); + } + Err(bad(field, "an integer is a number or its base-10 text")) +} + +/// The bind of one value of a column of `kind`. +fn scalar_bind(engine: Engine, field: &str, kind: Kind, v: &Value) -> Result { + if v.is_null() { + return Ok(Bind::Null); + } + Ok(match kind { + Kind::Text | Kind::Date | Kind::Time | Kind::Timestamp | Kind::TimestampTz | Kind::Inet => { + Bind::Text(text_of(field, v, "the value")?.to_string()) + } + // A UUID's canonical text is lower case, which is what Postgres reads back too. + Kind::Uuid => Bind::Text(text_of(field, v, "a UUID")?.to_ascii_lowercase()), + Kind::Int | Kind::Long => Bind::Int(int_of(field, v)?), + Kind::Double | Kind::Float => { + Bind::Real(v.as_f64().ok_or_else(|| bad(field, "a number is a JSON number"))?) + } + Kind::Bool => { + let b = v.as_bool().ok_or_else(|| bad(field, "a boolean is true or false"))?; + match engine { + Engine::Postgres => Bind::Bool(b), + Engine::Sqlite => Bind::Int(i64::from(b)), + } + } + Kind::Decimal => match v { + Value::String(s) => { + let d = + meta_support::wire::Decimal::parse(s).map_err(|e| bad(field, e.to_string()))?; + Bind::Text(d.as_str().to_string()) + } + Value::Number(n) => Bind::Text(n.to_string()), + _ => return Err(bad(field, "a decimal is a string or a number")), + }, + Kind::Duration => { + let text = text_of(field, v, "a duration")?; + let d = + meta_support::wire::Duration::parse(text).map_err(|e| bad(field, e.to_string()))?; + match engine { + // In microseconds, the interval's own resolution: Postgres reads no sign on an + // ISO duration. + Engine::Postgres => Bind::Text(format!("{} microseconds", d.nanos() / 1000)), + Engine::Sqlite => Bind::Int( + i64::try_from(d.nanos() / 1000) + .map_err(|_| bad(field, "the duration is too long"))?, + ), + } + } + Kind::Json => Bind::Text(v.to_string()), + Kind::StringEnum(map) => { + let symbol = text_of(field, v, "an enum member")?; + let stored = map + .iter() + .find(|(m, _)| *m == symbol) + .map(|(_, t)| *t) + .ok_or_else(|| bad(field, format!("`{symbol}` is not a member")))?; + Bind::Text(stored.to_string()) + } + Kind::IntEnum(map) => { + let symbol = text_of(field, v, "an enum member")?; + let stored = map + .iter() + .find(|(m, _)| *m == symbol) + .map(|(_, i)| *i) + .ok_or_else(|| bad(field, format!("`{symbol}` is not a member")))?; + Bind::Int(stored) + } + }) +} + +/// The bind of a column's value: an array is bound whole. +fn bind_of(engine: Engine, c: &Column, v: &Value) -> Result { + if !c.array || v.is_null() { + return scalar_bind(engine, c.field, c.kind, v); + } + let Value::Array(items) = v else { + return Err(bad(c.field, "the value is a list")); + }; + let binds = items + .iter() + .map(|item| scalar_bind(engine, c.field, c.kind, item)) + .collect::, _>>()?; + match engine { + Engine::Sqlite => { + let stored: Vec = binds + .into_iter() + .map(|b| match b { + Bind::Null => Value::Null, + Bind::Bool(b) => Value::Bool(b), + Bind::Int(i) => Value::from(i), + Bind::Real(r) => Value::from(r), + Bind::Text(t) => Value::String(t), + Bind::Ints(_) | Bind::Texts(_) => Value::Null, + }) + .collect(); + Ok(Bind::Text(Value::Array(stored).to_string())) + } + Engine::Postgres => { + if binds.iter().all(|b| matches!(b, Bind::Int(_))) { + Ok(Bind::Ints( + binds.into_iter().map(|b| if let Bind::Int(i) = b { i } else { 0 }).collect(), + )) + } else if binds.iter().all(|b| matches!(b, Bind::Text(_))) { + Ok(Bind::Texts( + binds + .into_iter() + .map(|b| if let Bind::Text(t) = b { t } else { String::new() }) + .collect(), + )) + } else { + Err(StoreError::Unsupported(format!("`{}`: an array of this type", c.field))) + } + } + } +} + +// ---- decoding a stored value --------------------------------------------------------------- + +fn int_enum_member(field: &str, map: &[(&str, i64)], stored: i64) -> Result { + map.iter() + .find(|(_, i)| *i == stored) + .map(|(m, _)| Value::String((*m).to_string())) + .ok_or_else(|| decode_err(field, format!("the stored value {stored} is no member"))) +} + +fn string_enum_member( + field: &str, + map: &[(&str, &str)], + stored: &str, +) -> Result { + map.iter() + .find(|(_, t)| *t == stored) + .map(|(m, _)| Value::String((*m).to_string())) + .ok_or_else(|| decode_err(field, format!("the stored value `{stored}` is no member"))) +} + +fn decimal_text(field: &str, text: &str) -> Result { + meta_support::wire::Decimal::parse(text) + .map(|d| Value::String(d.as_str().to_string())) + .map_err(|e| decode_err(field, e)) +} + +fn decimal_real(field: &str, r: f64) -> Result { + meta_support::wire::Decimal::from_f64(r) + .map(|d| Value::String(d.as_str().to_string())) + .ok_or_else(|| decode_err(field, "a decimal must be finite")) +} + +fn duration_nanos(nanos: i128) -> Value { + Value::String(meta_support::wire::Duration::from_nanos(nanos).to_string()) +} + +fn number(field: &str, r: f64) -> Result { + serde_json::Number::from_f64(r) + .map(Value::Number) + .ok_or_else(|| decode_err(field, "a number must be finite")) +} + +#[cfg(feature = "postgres")] +mod pg { + use super::*; + use chrono::Timelike; + use sqlx::postgres::types::PgInterval; + use sqlx::postgres::{PgArguments, PgRow}; + use sqlx::{Arguments, Row}; + + fn args(binds: Vec) -> Result { + let mut a = PgArguments::default(); + for b in binds { + let r = match b { + Bind::Null => a.add(Option::::None), + Bind::Bool(v) => a.add(v), + Bind::Int(v) => a.add(v), + Bind::Real(v) => a.add(v), + Bind::Text(v) => a.add(v), + Bind::Ints(v) => a.add(v), + Bind::Texts(v) => a.add(v), + }; + r.map_err(|e| StoreError::Database(sqlx::Error::Encode(e)))?; + } + Ok(a) + } + + /// The fractional seconds of a time: `.` and the digits without trailing zeros, or nothing + /// for a whole second. + /// The fraction of a second on the wire: milliseconds, truncated, with no trailing zeros + /// and no dot when there are none (normalization.md). + fn fraction(nanos: u32) -> String { + let millis = nanos / 1_000_000; + if millis == 0 { + return String::new(); + } + let digits = format!("{millis:03}"); + format!(".{}", digits.trim_end_matches('0')) + } + + fn get<'r, T: sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type>( + row: &'r PgRow, + i: usize, + field: &str, + ) -> Result, StoreError> { + row.try_get::, _>(i).map_err(|e| decode_err(field, e)) + } + + fn scalar(row: &PgRow, i: usize, c: &Column) -> Result { + let f = c.field; + let v = match c.kind { + Kind::Text | Kind::Decimal | Kind::Uuid | Kind::Inet | Kind::StringEnum(_) => { + match (get::(row, i, f)?, c.kind) { + (None, _) => Value::Null, + (Some(s), Kind::Decimal) => decimal_text(f, &s)?, + (Some(s), Kind::StringEnum(map)) => string_enum_member(f, map, &s)?, + (Some(s), _) => Value::String(s), + } + } + Kind::Int => get::(row, i, f)?.map_or(Value::Null, Value::from), + Kind::IntEnum(map) => match get::(row, i, f)? { + None => Value::Null, + Some(s) => int_enum_member(f, map, i64::from(s))?, + }, + Kind::Long => get::(row, i, f)?.map_or(Value::Null, Value::from), + Kind::Double => match get::(row, i, f)? { + None => Value::Null, + Some(r) => number(f, r)?, + }, + Kind::Float => match get::(row, i, f)? { + None => Value::Null, + // The shortest text of the f32, so 0.1 reads back as 0.1 and not its f64 widening. + Some(r) => number(f, r.to_string().parse::().unwrap_or(f64::from(r)))?, + }, + Kind::Bool => get::(row, i, f)?.map_or(Value::Null, Value::Bool), + Kind::Date => get::(row, i, f)? + .map_or(Value::Null, |d| Value::String(d.format("%Y-%m-%d").to_string())), + Kind::Time => get::(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!("{}{}", t.format("%H:%M:%S"), fraction(t.nanosecond()))) + }), + Kind::Timestamp => get::(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!( + "{}{}", + t.format("%Y-%m-%dT%H:%M:%S"), + fraction(t.nanosecond()) + )) + }), + Kind::TimestampTz => { + get::>(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!( + "{}{}Z", + t.format("%Y-%m-%dT%H:%M:%S"), + fraction(t.nanosecond()) + )) + }) + } + Kind::Duration => match get::(row, i, f)? { + None => Value::Null, + Some(iv) if iv.months != 0 => { + return Err(decode_err(f, "an interval with months has no fixed length")); + } + Some(iv) => duration_nanos( + i128::from(iv.days) * 86_400_000_000_000 + i128::from(iv.microseconds) * 1000, + ), + }, + Kind::Json => get::(row, i, f)?.unwrap_or(Value::Null), + }; + Ok(v) + } + + fn array(row: &PgRow, i: usize, c: &Column) -> Result { + let f = c.field; + let items: Option> = match c.kind { + Kind::Int => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::from).collect()) + } + Kind::IntEnum(map) => match get::>(row, i, f)? { + None => None, + Some(v) => Some( + v.into_iter() + .map(|s| int_enum_member(f, map, i64::from(s))) + .collect::>()?, + ), + }, + Kind::Long => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::from).collect()) + } + Kind::Text | Kind::Uuid => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::String).collect()) + } + Kind::Decimal => match get::>(row, i, f)? { + None => None, + Some(v) => Some(v.iter().map(|s| decimal_text(f, s)).collect::>()?), + }, + Kind::StringEnum(map) => match get::>(row, i, f)? { + None => None, + Some(v) => Some( + v.iter().map(|s| string_enum_member(f, map, s)).collect::>()?, + ), + }, + Kind::Bool => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::Bool).collect()) + } + _ => return Err(StoreError::Unsupported(format!("`{f}`: an array of this type"))), + }; + Ok(items.map_or(Value::Null, Value::Array)) + } + + fn decode(row: &PgRow, columns: &[Column]) -> Result, StoreError> { + let mut out = Map::new(); + for (i, c) in columns.iter().enumerate() { + let v = if c.array { array(row, i, c)? } else { scalar(row, i, c)? }; + out.insert(c.field.to_string(), v); + } + Ok(out) + } + + impl Conn for sqlx::PgConnection { + fn engine(&self) -> Engine { + Engine::Postgres + } + + async fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> Result>, StoreError> { + let rows = sqlx::query_with(sql, args(binds)?).fetch_all(&mut *self).await?; + rows.iter().map(|r| decode(r, columns)).collect() + } + + async fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let row = sqlx::query_with(sql, args(binds)?).fetch_one(&mut *self).await?; + Ok(row.try_get::(0)?) + } + + async fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let done = sqlx::query_with(sql, args(binds)?).execute(&mut *self).await?; + Ok(done.rows_affected()) + } + } +} + +#[cfg(feature = "sqlite")] +mod sqlite { + use super::*; + use sqlx::sqlite::{SqliteArguments, SqliteRow}; + use sqlx::{Arguments, Row, TypeInfo, ValueRef}; + + fn args(binds: Vec) -> Result, StoreError> { + let mut a = SqliteArguments::default(); + for b in binds { + let r = match b { + Bind::Null => a.add(Option::::None), + Bind::Bool(v) => a.add(i64::from(v)), + Bind::Int(v) => a.add(v), + Bind::Real(v) => a.add(v), + Bind::Text(v) => a.add(v), + Bind::Ints(v) => a.add(Value::from(v).to_string()), + Bind::Texts(v) => a.add(Value::from(v).to_string()), + }; + r.map_err(|e| StoreError::Database(sqlx::Error::Encode(e)))?; + } + Ok(a) + } + + /// One stored value, by the storage class SQLite gave it. + enum Stored { + Null, + Int(i64), + Real(f64), + Text(String), + } + + fn stored(row: &SqliteRow, i: usize, field: &str) -> Result { + let raw = row.try_get_raw(i).map_err(|e| decode_err(field, e))?; + if raw.is_null() { + return Ok(Stored::Null); + } + let class = raw.type_info().name().to_string(); + Ok(match class.as_str() { + "INTEGER" | "BOOLEAN" => { + Stored::Int(row.try_get::(i).map_err(|e| decode_err(field, e))?) + } + "REAL" => Stored::Real(row.try_get::(i).map_err(|e| decode_err(field, e))?), + _ => Stored::Text(row.try_get::(i).map_err(|e| decode_err(field, e))?), + }) + } + + fn from_stored(field: &str, kind: Kind, s: Stored) -> Result { + Ok(match (kind, s) { + (_, Stored::Null) => Value::Null, + (Kind::Bool, Stored::Int(i)) => Value::Bool(i != 0), + (Kind::IntEnum(map), Stored::Int(i)) => int_enum_member(field, map, i)?, + (Kind::StringEnum(map), Stored::Text(t)) => string_enum_member(field, map, &t)?, + (Kind::Decimal, Stored::Int(i)) => Value::String(i.to_string()), + (Kind::Decimal, Stored::Real(r)) => decimal_real(field, r)?, + (Kind::Decimal, Stored::Text(t)) => decimal_text(field, &t)?, + (Kind::Duration, Stored::Int(micros)) => duration_nanos(i128::from(micros) * 1000), + (Kind::Json, Stored::Text(t)) => { + serde_json::from_str(&t).map_err(|e| decode_err(field, e))? + } + (Kind::Int | Kind::Long, Stored::Int(i)) => Value::from(i), + (Kind::Double | Kind::Float, Stored::Int(i)) => Value::from(i as f64), + (Kind::Double | Kind::Float, Stored::Real(r)) => number(field, r)?, + (_, Stored::Text(t)) => Value::String(t), + (_, Stored::Int(i)) => Value::from(i), + (_, Stored::Real(r)) => number(field, r)?, + }) + } + + /// An element of an array column, which is JSON text. + fn element(field: &str, kind: Kind, v: Value) -> Result { + let s = match v { + Value::Null => Stored::Null, + Value::Bool(b) => Stored::Int(i64::from(b)), + Value::Number(n) => match n.as_i64() { + Some(i) => Stored::Int(i), + None => Stored::Real(n.as_f64().unwrap_or(f64::NAN)), + }, + Value::String(t) => Stored::Text(t), + other => return Ok(other), + }; + from_stored(field, kind, s) + } + + fn decode(row: &SqliteRow, columns: &[Column]) -> Result, StoreError> { + let mut out = Map::new(); + for (i, c) in columns.iter().enumerate() { + let s = stored(row, i, c.field)?; + let v = if c.array { + match s { + Stored::Null => Value::Null, + Stored::Text(t) => match serde_json::from_str::(&t) + .map_err(|e| decode_err(c.field, e))? + { + Value::Array(items) => Value::Array( + items + .into_iter() + .map(|v| element(c.field, c.kind, v)) + .collect::>()?, + ), + _ => return Err(decode_err(c.field, "an array column holds a JSON list")), + }, + _ => return Err(decode_err(c.field, "an array column holds JSON text")), + } + } else { + from_stored(c.field, c.kind, s)? + }; + out.insert(c.field.to_string(), v); + } + Ok(out) + } + + impl Conn for sqlx::SqliteConnection { + fn engine(&self) -> Engine { + Engine::Sqlite + } + + async fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> Result>, StoreError> { + let rows = sqlx::query_with(sql, args(binds)?).fetch_all(&mut *self).await?; + rows.iter().map(|r| decode(r, columns)).collect() + } + + async fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let row = sqlx::query_with(sql, args(binds)?).fetch_one(&mut *self).await?; + Ok(row.try_get::(0)?) + } + + async fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let done = sqlx::query_with(sql, args(binds)?).execute(&mut *self).await?; + Ok(done.rows_affected()) + } + } +} + +// ---- statements ---------------------------------------------------------------------------- + +fn where_filter(sql: &mut Sql, table: &Table, f: &Filter) -> Result<(), StoreError> { + match f { + Filter::And(all) if all.is_empty() => sql.push("1 = 1"), + Filter::Or(any) if any.is_empty() => sql.push("1 = 0"), + Filter::And(all) | Filter::Or(all) => { + let joiner = if matches!(f, Filter::And(_)) { " AND " } else { " OR " }; + sql.push("("); + for (i, f) in all.iter().enumerate() { + if i > 0 { + sql.push(joiner); + } + where_filter(sql, table, f)?; + } + sql.push(")"); + } + Filter::Search { fields, .. } if fields.is_empty() => sql.push("1 = 0"), + Filter::Search { term, fields } => { + // Postgres' ILIKE ignores case; SQLite's LIKE already does, for ASCII. + let like = match sql.engine { + Engine::Postgres => "ILIKE", + Engine::Sqlite => "LIKE", + }; + sql.push("("); + for (i, field) in fields.iter().enumerate() { + let c = *table.column(field)?; + if c.kind != Kind::Text || c.array { + return Err(bad(field, "a search matches text")); + } + if i > 0 { + sql.push(" OR "); + } + sql.push(&format!("{} {like} ", quote(c.column))); + sql.param(Bind::Text(format!("%{term}%")), &c); + } + sql.push(")"); + } + Filter::Field { field, op, value } => { + let c = *table.column(field)?; + if (c.array || c.kind == Kind::Json) && *op != Op::IsNull { + return Err(bad(field, "a list or a JSON value takes only `isNull`")); + } + let col = quote(c.column); + match op { + Op::IsNull => { + let yes = value + .as_bool() + .ok_or_else(|| bad(field, "`isNull` takes true or false"))?; + sql.push(&format!("{col} IS {}NULL", if yes { "" } else { "NOT " })); + } + Op::Eq | Op::Ne if value.is_null() => { + sql.push(&format!("{col} IS {}NULL", if *op == Op::Ne { "NOT " } else { "" })); + } + Op::In => { + let Value::Array(items) = value else { + return Err(bad(field, "`in` takes a list")); + }; + if items.is_empty() { + sql.push("1 = 0"); + return Ok(()); + } + sql.push(&format!("{col} IN (")); + for (i, item) in items.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + let b = scalar_bind(sql.engine, field, c.kind, item)?; + sql.param(b, &c); + } + sql.push(")"); + } + Op::Like => { + if c.kind != Kind::Text { + return Err(bad(field, "`like` applies to text")); + } + // `like` is case-sensitive (ADR-0049). SQLite's LIKE ignores ASCII case, + // so there the pattern runs as the GLOB it means. + match (sql.engine, scalar_bind(sql.engine, field, c.kind, value)?) { + (Engine::Sqlite, Bind::Text(pattern)) => { + sql.push(&format!("{col} GLOB ")); + sql.param(Bind::Text(like_to_glob(&pattern)), &c); + } + (_, b) => { + sql.push(&format!("{col} LIKE ")); + sql.param(b, &c); + } + } + } + _ => { + let b = scalar_bind(sql.engine, field, c.kind, value)?; + sql.push(&format!("{col} {} ", op.sql())); + sql.param(b, &c); + } + } + } + } + Ok(()) +} + +/// A `LIKE` pattern as the GLOB that matches the same text, case-sensitively. +fn like_to_glob(pattern: &str) -> String { + let mut out = String::with_capacity(pattern.len()); + for ch in pattern.chars() { + match ch { + '%' => out.push('*'), + '_' => out.push('?'), + '*' => out.push_str("[*]"), + '?' => out.push_str("[?]"), + '[' => out.push_str("[[]"), + c => out.push(c), + } + } + out +} + +fn where_condition(sql: &mut Sql, table: &Table, cond: &Condition) -> Result<(), StoreError> { + match cond { + Condition::Compare { op, left, right } => { + sql.push("("); + operand_sql(sql, table, left, right.stored_field())?; + sql.push(&format!(" {} ", op.sql())); + operand_sql(sql, table, right, left.stored_field())?; + sql.push(")"); + } + Condition::IsNull { operand, not } => { + sql.push("("); + operand_sql(sql, table, operand, None)?; + sql.push(&format!(" IS {}NULL)", if *not { "NOT " } else { "" })); + } + Condition::Not(inner) => { + sql.push("(NOT "); + where_condition(sql, table, inner)?; + sql.push(")"); + } + Condition::And(all) | Condition::Or(all) => { + let (join, empty) = if matches!(cond, Condition::And(_)) { + (" AND ", "1 = 1") + } else { + (" OR ", "1 = 0") + }; + if all.is_empty() { + sql.push(empty); + return Ok(()); + } + sql.push("("); + for (i, c) in all.iter().enumerate() { + if i > 0 { + sql.push(join); + } + where_condition(sql, table, c)?; + } + sql.push(")"); + } + } + Ok(()) +} + +/// One operand; a literal takes the stored form of `partner`, the field it is compared with. +fn operand_sql( + sql: &mut Sql, + table: &Table, + operand: &Operand, + partner: Option<&str>, +) -> Result<(), StoreError> { + match operand { + Operand::Field(f) => { + let c = *table.column(f)?; + if c.array || c.kind == Kind::Json { + return Err(bad(f, "a condition compares no list or JSON value")); + } + sql.push("e(c.column)); + } + Operand::Value(v) => match partner { + Some(f) => { + let c = *table.column(f)?; + let b = scalar_bind(sql.engine, f, c.kind, v)?; + sql.param(b, &c); + } + None => { + let b = match v { + Value::Null => Bind::Null, + Value::Bool(b) => Bind::Bool(*b), + Value::String(s) => Bind::Text(s.clone()), + Value::Number(n) => match n.as_i64() { + Some(i) => Bind::Int(i), + None => Bind::Real(n.as_f64().unwrap_or_default()), + }, + _ => return Err(bad("condition", "a literal is a scalar")), + }; + sql.raw_param(b); + } + }, + Operand::Coalesce(items) => { + // The arguments of a coalesce share its type, so a literal among them takes the + // first field's form. + let own = operand.stored_field().or(partner); + sql.push("COALESCE("); + for (i, item) in items.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + operand_sql(sql, table, item, own)?; + } + sql.push(")"); + } + } + Ok(()) +} + +/// ` AND "" = ` (or ` WHERE ...` when `first`), for a subtype. +fn scope(sql: &mut Sql, table: &Table, first: bool) -> Result<(), StoreError> { + if let Some((field, value)) = table.discriminator { + let c = *table.column(field)?; + sql.push(&format!(" {} {} = ", if first { "WHERE" } else { "AND" }, quote(c.column))); + sql.param(Bind::Text(value.to_string()), &c); + } + Ok(()) +} + +fn select(engine: Engine, table: &Table) -> Sql { + let mut sql = Sql::new(engine); + sql.push(&format!("SELECT {} FROM {}", select_list(engine, table), table_ref(table))); + sql +} + +fn key_where(sql: &mut Sql, table: &Table, key: &Value) -> Result<(), StoreError> { + let c = *table.key_column()?; + let b = scalar_bind(sql.engine, c.field, c.kind, key)?; + sql.push(&format!(" WHERE {} = ", quote(c.column))); + sql.param(b, &c); + scope(sql, table, false) +} + +fn rows_into( + table: &Table, + rows: Vec>, +) -> Result, StoreError> { + rows.into_iter() + .map(|r| serde_json::from_value(Value::Object(r)).map_err(|e| decode_err(table.object, e))) + .collect() +} + +fn body_of(table: &Table, body: &B) -> Result, StoreError> { + match serde_json::to_value(body) { + Ok(Value::Object(m)) => Ok(m), + Ok(_) => Err(bad(table.object, "a body is an object")), + Err(e) => Err(bad(table.object, e.to_string())), + } +} + +/// The row with key `key`, or `None`. +pub async fn get( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + get_value(c, table.reader(), &key).await +} + +async fn get_value( + c: &mut C, + table: &Table, + key: &Value, +) -> Result, StoreError> { + let mut sql = select(c.engine(), table); + key_where(&mut sql, table, key)?; + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + Ok(rows_into(table, rows)?.into_iter().next()) +} + +/// The row with key `key`, or `None`, read to be written in the same transaction: on Postgres +/// under a row lock (`FOR UPDATE`), held until the transaction ends, so a second writer waits +/// for the first. SQLite locks the whole database for a writer, so it reads the row as `get` +/// does. +pub async fn get_for_update( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let mut sql = select(c.engine(), table); + key_where(&mut sql, table, &key)?; + if sql.engine == Engine::Postgres { + sql.push(" FOR UPDATE"); + } + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + let row = rows_into(table, rows)?.into_iter().next(); + match table.read { + // Locked through the table; read, with what it derives, through the view. + Some(read) if row.is_some() => get_value(c, read, &key).await, + _ => Ok(row), + } +} + +/// The `target` rows related through `through` to the row whose key is `key`, in no order (a +/// relationship is a set). A subtype target answers only its own rows. +pub async fn related( + c: &mut C, + target: &Table, + through: &Through, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(target.object, e.to_string()))?; + let target = target.reader(); + let engine = c.engine(); + let (s, t) = (&through.source, &through.target); + let junction = match through.schema { + Some(schema) => format!("{}.{}", quote(schema), quote(through.name)), + None => quote(through.name), + }; + let mut sql = select(engine, target); + sql.push(&format!(" WHERE {} IN (SELECT ", quote(target.key_column()?.column))); + let param = |sql: &mut Sql| -> Result<(), StoreError> { + let b = scalar_bind(engine, s.field, s.kind, &key)?; + sql.param(b, s); + Ok(()) + }; + if through.symmetric { + // The side of each row that is not the source; a row relating a row to itself is + // that row. + sql.push(&format!("CASE WHEN {} = ", quote(s.column))); + param(&mut sql)?; + sql.push(&format!( + " THEN {} ELSE {} END FROM {junction} WHERE {} = ", + quote(t.column), + quote(s.column), + quote(s.column) + )); + param(&mut sql)?; + sql.push(&format!(" OR {} = ", quote(t.column))); + param(&mut sql)?; + } else { + sql.push(&format!("{} FROM {junction} WHERE {} = ", quote(t.column), quote(s.column))); + param(&mut sql)?; + } + sql.push(")"); + scope(&mut sql, target, false)?; + let rows = c.rows(&sql.text, sql.binds, target.columns).await?; + rows_into(target, rows) +} + +/// The rows a query selects, in its order and page. +pub async fn list( + c: &mut C, + table: &Table, + query: &Query, +) -> Result, StoreError> { + let table = table.reader(); + let mut sql = select(c.engine(), table); + scope(&mut sql, table, true)?; + if let Some(f) = &query.filter { + sql.push(if table.discriminator.is_some() { " AND " } else { " WHERE " }); + where_filter(&mut sql, table, f)?; + } + if !query.sort.is_empty() { + let mut order = Vec::new(); + for s in &query.sort { + let col = table.column(&s.field)?; + // A null sorts as larger than any value. + order.push(if s.descending { + format!("{} DESC NULLS FIRST", quote(col.column)) + } else { + format!("{} ASC NULLS LAST", quote(col.column)) + }); + } + sql.push(&format!(" ORDER BY {}", order.join(", "))); + } + match (query.limit, query.offset) { + (Some(l), Some(o)) => sql.push(&format!(" LIMIT {l} OFFSET {o}")), + (Some(l), None) => sql.push(&format!(" LIMIT {l}")), + (None, Some(o)) => sql.push(&match sql.engine { + Engine::Postgres => format!(" OFFSET {o}"), + Engine::Sqlite => format!(" LIMIT -1 OFFSET {o}"), + }), + (None, None) => {} + } + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + rows_into(table, rows) +} + +/// The number of rows a filter selects. +pub async fn count( + c: &mut C, + table: &Table, + filter: Option<&Filter>, +) -> Result { + let table = table.reader(); + let mut sql = Sql::new(c.engine()); + sql.push(&format!("SELECT COUNT(*) FROM {}", table_ref(table))); + scope(&mut sql, table, true)?; + if let Some(f) = filter { + sql.push(if table.discriminator.is_some() { " AND " } else { " WHERE " }); + where_filter(&mut sql, table, f)?; + } + let n = c.scalar(&sql.text, sql.binds).await?; + Ok(u64::try_from(n).unwrap_or(0)) +} + +/// Inserts the members `body` carries and reads the row back. +pub async fn create( + c: &mut C, + table: &Table, + body: &B, +) -> Result { + table.require_writable()?; + let mut body = body_of(table, body)?; + if let Some((field, value)) = table.discriminator { + match body.get(field) { + None | Some(Value::Null) => { + body.insert(field.to_string(), Value::String(value.to_string())); + } + Some(Value::String(v)) if v == value => {} + Some(_) => return Err(bad(field, format!("a {} is always `{value}`", table.object))), + } + } + let engine = c.engine(); + let mut sql = Sql::new(engine); + let mut names = Vec::new(); + let mut values = Sql::new(engine); + for (field, v) in &body { + let col = *table.column(field)?; + names.push(quote(col.column)); + if !values.text.is_empty() { + values.push(", "); + } + let b = bind_of(engine, &col, v)?; + values.param(b, &col); + } + if names.is_empty() { + sql.push(&format!("INSERT INTO {} DEFAULT VALUES", table_ref(table))); + } else { + // The values were numbered from 1, as they are the statement's only binds. + sql.push(&format!( + "INSERT INTO {} ({}) VALUES ({})", + table_ref(table), + names.join(", "), + values.text + )); + sql.binds = values.binds; + } + sql.push(&format!(" RETURNING {}", select_list(engine, table))); + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + let none = || StoreError::Unsupported(format!("{}: the insert returned no row", table.object)); + let row = rows.into_iter().next().ok_or_else(none)?; + match table.read { + Some(read) => { + let key = row.get(table.key_column()?.field).cloned().unwrap_or(Value::Null); + get_value(c, read, &key).await?.ok_or_else(none) + } + None => rows_into(table, vec![row])?.into_iter().next().ok_or_else(none), + } +} + +/// Sets the members `patch` carries on the row with key `key` and reads it back; `None` when +/// there is no such row. +pub async fn update( + c: &mut C, + table: &Table, + key: impl Serialize, + patch: &B, +) -> Result, StoreError> { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let body = body_of(table, patch)?; + if let Some((field, value)) = table.discriminator { + if body.get(field).is_some_and(|v| v.as_str() != Some(value)) { + return Err(bad(field, "the discriminator never changes")); + } + } + if body.is_empty() { + return get_value(c, table.reader(), &key).await; + } + let engine = c.engine(); + let mut sql = Sql::new(engine); + sql.push(&format!("UPDATE {} SET ", table_ref(table))); + for (i, (field, v)) in body.iter().enumerate() { + let col = *table.column(field)?; + if i > 0 { + sql.push(", "); + } + sql.push(&format!("{} = ", quote(col.column))); + let b = bind_of(engine, &col, v)?; + sql.param(b, &col); + } + key_where(&mut sql, table, &key)?; + sql.push(&format!(" RETURNING {}", select_list(engine, table))); + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + match table.read { + Some(read) if !rows.is_empty() => get_value(c, read, &key).await, + _ => Ok(rows_into(table, rows)?.into_iter().next()), + } +} + +/// Deletes the row with key `key`; `false` when there was none. +pub async fn delete( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let mut sql = Sql::new(c.engine()); + sql.push(&format!("DELETE FROM {}", table_ref(table))); + key_where(&mut sql, table, &key)?; + Ok(c.execute(&sql.text, sql.binds).await? > 0) +} + +/// The guarded update of a lifecycle (ADR-0066 §6 step 5): sets `state` to `to` on the row +/// with key `key` only while its state is one of `from` and `condition` (a transition's +/// `@condition`, when it has one) holds, in one statement. `false` when no row matched: the +/// row is gone, its condition fails, or another writer moved it first. The caller re-reads to +/// tell which. +pub async fn transition( + c: &mut C, + table: &Table, + key: impl Serialize, + state: &str, + from: &[S], + to: &S, + condition: Option<&Condition>, +) -> Result { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let value = |s: &S| serde_json::to_value(s).map_err(|e| bad(state, e.to_string())); + let col = *table.column(state)?; + let engine = c.engine(); + let mut sql = Sql::new(engine); + sql.push(&format!("UPDATE {} SET {} = ", table_ref(table), quote(col.column))); + sql.param(scalar_bind(engine, state, col.kind, &value(to)?)?, &col); + key_where(&mut sql, table, &key)?; + if from.is_empty() { + return Ok(false); + } + sql.push(&format!(" AND {} IN (", quote(col.column))); + for (i, f) in from.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + sql.param(scalar_bind(engine, state, col.kind, &value(f)?)?, &col); + } + sql.push(")"); + if let Some(cond) = condition { + sql.push(" AND "); + where_condition(&mut sql, table, cond)?; + } + Ok(c.execute(&sql.text, sql.binds).await? == 1) +} diff --git a/examples/rust-service/generated/meta_support/Cargo.toml b/examples/rust-service/generated/meta_support/Cargo.toml new file mode 100644 index 0000000000..adbdc5b3d0 --- /dev/null +++ b/examples/rust-service/generated/meta_support/Cargo.toml @@ -0,0 +1,10 @@ +# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "meta_support" +version = "0.1.0" +edition = "2021" +publish = false +description = "Wire types and validation checks for the generated MetaObjects model crates." + +[dependencies] +serde = "1" diff --git a/examples/rust-service/generated/meta_support/rustfmt.toml b/examples/rust-service/generated/meta_support/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/meta_support/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/meta_support/src/lib.rs b/examples/rust-service/generated/meta_support/src/lib.rs new file mode 100644 index 0000000000..3d3a66864b --- /dev/null +++ b/examples/rust-service/generated/meta_support/src/lib.rs @@ -0,0 +1,8 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! What every generated model crate uses: the exact `Decimal` and the ISO-8601 +//! `Duration` of the wire form, and the checks `validate()` is written in. + +pub mod pattern; +pub mod validation; +pub mod wire; diff --git a/examples/rust-service/generated/meta_support/src/pattern.rs b/examples/rust-service/generated/meta_support/src/pattern.rs new file mode 100644 index 0000000000..b9690d8922 --- /dev/null +++ b/examples/rust-service/generated/meta_support/src/pattern.rs @@ -0,0 +1,613 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! A small, dependency-free, full-match regular-expression matcher for `validator.regex`. +//! +//! It implements the subset of regular-expression syntax every MetaObjects port agrees on, so a +//! pattern means the same thing in every language. A pattern is parsed once into a tree and +//! matched by backtracking. Matching is over `char`s, case-sensitive, and the class escapes are +//! ASCII only. Nothing is captured. +//! +//! Supported: literals; the escapes `\d \D \w \W \s \S \t \n \r \f \v \0 \xHH \uHHHH` and an +//! escaped punctuation character; `.` (any character but `\n`); classes `[...]` and `[^...]` +//! with ranges; groups `( ... )` and `(?: ... )`; alternation `|`; the quantifiers `* + ? {n} +//! {n,} {n,m}` and their lazy forms; and the anchors `^` and `$`. Everything else is refused +//! with a [`PatternError`]: lookaround, named groups, inline flags, backreferences, `\b`, `\p{..}` +//! and possessive quantifiers. +//! +//! Matching keeps its choice points on the heap, so the call stack does not grow with the text: +//! a text of any length matches `(a)*` or `(\w+\s?)*` without overflowing it. A match is given a +//! step budget that grows with the length of the text, and when a pathological pattern spends it +//! the answer is [`Outcome::GaveUp`], which is neither a match nor a mismatch. A caller must +//! report it as its own result, so a value is never refused or accepted on a guess. +//! +//! This file is written by the `entity` generator into the support crate (`meta_support`) +//! every generated model crate depends on. + +use std::fmt; +use std::rc::Rc; + +/// The steps one match may take before it gives up, whatever the length of the text. +const STEP_BUDGET: u64 = 1_000_000; +/// The steps a match may take in addition for each character of the text. +const STEP_ALLOWANCE_PER_CHAR: u64 = 32; +/// The deepest nesting of groups a pattern may have. +const NESTING_LIMIT: u32 = 100; + +/// Why a pattern was refused. `at` is the byte offset in the pattern source. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PatternError { + pub at: usize, + pub message: String, +} + +impl fmt::Display for PatternError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} at offset {}", self.message, self.at) + } +} + +impl std::error::Error for PatternError {} + +/// One member of a character class. +#[derive(Debug, Clone, PartialEq, Eq)] +enum ClassItem { + Range(char, char), + Digit, + NotDigit, + Word, + NotWord, + Space, + NotSpace, +} + +/// Whether `count` is still under the optional upper bound. +fn below(max: Option, count: T) -> bool { + match max { + Some(m) => count < m, + None => true, + } +} + +fn is_word(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' +} + +fn is_space(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C') +} + +impl ClassItem { + fn matches(&self, c: char) -> bool { + match *self { + ClassItem::Range(lo, hi) => (lo..=hi).contains(&c), + ClassItem::Digit => c.is_ascii_digit(), + ClassItem::NotDigit => !c.is_ascii_digit(), + ClassItem::Word => is_word(c), + ClassItem::NotWord => !is_word(c), + ClassItem::Space => is_space(c), + ClassItem::NotSpace => !is_space(c), + } + } +} + +/// A repeated node with its bounds. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Rep { + node: Box, + min: u32, + max: Option, + lazy: bool, +} + +/// A parsed pattern node. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Node { + Char(char), + Any, + Class { negated: bool, items: Vec }, + Start, + End, + Group(Vec>), + Repeat(Rep), +} + +/// What an escape stands for. +enum Escape { + Char(char), + Class(ClassItem), +} + +/// A parsed pattern, ready to match whole texts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pattern { + alts: Vec>, +} + +impl Pattern { + /// Parses `source`, or says why it is refused. + pub fn parse(source: &str) -> Result { + let mut parser = Parser { + chars: source.char_indices().collect(), + pos: 0, + nesting: 0, + end: source.len(), + }; + let alts = parser.parse_alts()?; + if parser.peek().is_some() { + return parser.fail(parser.offset(), "unmatched ')'"); + } + Ok(Pattern { alts }) + } + + /// Whether the whole text matches, as if the pattern were wrapped in `^(?: ... )$`. + pub fn outcome(&self, text: &str) -> Outcome { + let chars: Vec = text.chars().collect(); + Matcher::run(&chars, &self.alts) + } + + /// True only when the whole text matches. False for a mismatch and for a give-up alike; use + /// [`Pattern::outcome`] to tell them apart. + pub fn is_full_match(&self, text: &str) -> bool { + self.outcome(text) == Outcome::Match + } +} + +/// Parses and matches in one call; a pattern that does not parse matches nothing. +pub fn outcome(source: &str, text: &str) -> Outcome { + Pattern::parse(source).map_or(Outcome::NoMatch, |p| p.outcome(text)) +} + +/// True only when the whole text matches `source`. False for a mismatch, a give-up and a +/// pattern that does not parse; use [`outcome`] to tell the first two apart. +pub fn full_match(source: &str, text: &str) -> bool { + outcome(source, text) == Outcome::Match +} + +/// What matching a text against a pattern came to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Outcome { + /// The whole text matches. + Match, + /// The whole text does not match. + NoMatch, + /// The match spent its step budget before it could tell. + GaveUp, +} + +struct Parser { + chars: Vec<(usize, char)>, + pos: usize, + nesting: u32, + end: usize, +} + +impl Parser { + fn char_at(&self, index: usize) -> Option { + self.chars.get(index).map(|&(_, c)| c) + } + + fn peek(&self) -> Option { + self.char_at(self.pos) + } + + fn next(&mut self) -> Option { + let c = self.peek(); + if c.is_some() { + self.pos += 1; + } + c + } + + fn eat(&mut self, c: char) -> bool { + let found = self.peek() == Some(c); + if found { + self.pos += 1; + } + found + } + + fn offset_at(&self, index: usize) -> usize { + self.chars.get(index).map_or(self.end, |&(o, _)| o) + } + + fn offset(&self) -> usize { + self.offset_at(self.pos) + } + + fn fail(&self, at: usize, message: &str) -> Result { + Err(PatternError { at, message: message.to_string() }) + } + + fn parse_alts(&mut self) -> Result>, PatternError> { + let mut alts = Vec::new(); + loop { + alts.push(self.parse_seq()?); + if !self.eat('|') { + return Ok(alts); + } + } + } + + fn parse_seq(&mut self) -> Result, PatternError> { + let mut seq = Vec::new(); + while let Some(c) = self.peek() { + if c == '|' || c == ')' { + break; + } + let atom = self.parse_atom()?; + seq.push(self.parse_quantifier(atom)?); + } + Ok(seq) + } + + fn parse_atom(&mut self) -> Result { + let at = self.offset(); + let Some(c) = self.next() else { + return self.fail(at, "unexpected end of pattern"); + }; + Ok(match c { + '(' => { + if self.eat('?') && !self.eat(':') { + return self.fail(at, "unsupported group syntax"); + } + if self.nesting >= NESTING_LIMIT { + return self.fail(at, "groups are nested too deeply"); + } + self.nesting += 1; + let alts = self.parse_alts()?; + self.nesting -= 1; + if !self.eat(')') { + return self.fail(at, "unclosed group"); + } + Node::Group(alts) + } + '[' => self.parse_class(at)?, + '.' => Node::Any, + '^' => Node::Start, + '$' => Node::End, + '\\' => match self.parse_escape(at)? { + Escape::Char(c) => Node::Char(c), + Escape::Class(item) => Node::Class { negated: false, items: vec![item] }, + }, + '*' | '+' | '?' => return self.fail(at, "nothing to repeat"), + '{' => { + if self.braces_at(self.pos)?.is_some() { + return self.fail(at, "nothing to repeat"); + } + Node::Char('{') + } + other => Node::Char(other), + }) + } + + fn parse_quantifier(&mut self, atom: Node) -> Result { + let at = self.offset(); + let (min, max) = match self.peek() { + Some('*') => (0, None), + Some('+') => (1, None), + Some('?') => (0, Some(1)), + Some('{') => match self.braces_at(self.pos + 1)? { + Some((min, max, next)) => { + if max.is_some_and(|m| m < min) { + return self.fail(at, "repeat range is reversed"); + } + self.pos = next - 1; + (min, max) + } + None => return Ok(atom), + }, + _ => return Ok(atom), + }; + self.pos += 1; + let lazy = self.eat('?'); + if !lazy && self.peek() == Some('+') { + return self.fail(self.offset(), "possessive quantifiers are not supported"); + } + Ok(Node::Repeat(Rep { node: Box::new(atom), min, max, lazy })) + } + + /// Reads `n}`, `n,}` or `n,m}` starting at `start`, just after a `{`. Gives the bounds and + /// the index after the `}`, or `None` when the text is not a quantifier. + fn braces_at(&self, start: usize) -> Result, usize)>, PatternError> { + let Some((min, mut i)) = self.number(start)? else { + return Ok(None); + }; + let max = if self.char_at(i) == Some(',') { + i += 1; + match self.number(i)? { + Some((m, next)) => { + i = next; + Some(m) + } + None => None, + } + } else { + Some(min) + }; + if self.char_at(i) != Some('}') { + return Ok(None); + } + Ok(Some((min, max, i + 1))) + } + + fn number(&self, start: usize) -> Result, PatternError> { + let mut i = start; + let mut value: u32 = 0; + while let Some(digit) = self.char_at(i).and_then(|c| c.to_digit(10)) { + let Some(next) = value.checked_mul(10).and_then(|v| v.checked_add(digit)) else { + return self.fail(self.offset_at(start), "repeat count is too large"); + }; + value = next; + i += 1; + } + Ok(if i == start { None } else { Some((value, i)) }) + } + + /// Reads an escape; `at` is the offset of its backslash. + fn parse_escape(&mut self, at: usize) -> Result { + let Some(c) = self.next() else { + return self.fail(at, "trailing backslash"); + }; + Ok(match c { + 'd' => Escape::Class(ClassItem::Digit), + 'D' => Escape::Class(ClassItem::NotDigit), + 'w' => Escape::Class(ClassItem::Word), + 'W' => Escape::Class(ClassItem::NotWord), + 's' => Escape::Class(ClassItem::Space), + 'S' => Escape::Class(ClassItem::NotSpace), + 't' => Escape::Char('\t'), + 'n' => Escape::Char('\n'), + 'r' => Escape::Char('\r'), + 'f' => Escape::Char('\x0C'), + 'v' => Escape::Char('\x0B'), + '0' => Escape::Char('\0'), + 'x' => Escape::Char(self.parse_hex(2, at)?), + 'u' => Escape::Char(self.parse_hex(4, at)?), + c if c.is_ascii_alphanumeric() => return self.fail(at, "unsupported escape"), + c => Escape::Char(c), + }) + } + + fn parse_hex(&mut self, digits: usize, at: usize) -> Result { + let mut value: u32 = 0; + for _ in 0..digits { + let Some(d) = self.peek().and_then(|c| c.to_digit(16)) else { + return self.fail(at, "invalid hex escape"); + }; + value = value * 16 + d; + self.pos += 1; + } + match char::from_u32(value) { + Some(c) => Ok(c), + None => self.fail(at, "invalid code point"), + } + } + + /// Reads a class after its `[`; `at` is the offset of that bracket. + fn parse_class(&mut self, at: usize) -> Result { + let negated = self.eat('^'); + let mut items = Vec::new(); + loop { + let item_at = self.offset(); + let Some(c) = self.next() else { + return self.fail(at, "unclosed character class"); + }; + if c == ']' { + break; + } + let lo = if c == '\\' { + match self.parse_escape(item_at)? { + Escape::Class(item) => { + items.push(item); + continue; + } + Escape::Char(ch) => ch, + } + } else { + c + }; + let is_range = + self.peek() == Some('-') && !matches!(self.char_at(self.pos + 1), None | Some(']')); + if !is_range { + items.push(ClassItem::Range(lo, lo)); + continue; + } + self.pos += 1; + let hi_at = self.offset(); + let Some(hi_char) = self.next() else { + return self.fail(at, "unclosed character class"); + }; + let hi = if hi_char == '\\' { + match self.parse_escape(hi_at)? { + Escape::Char(ch) => ch, + Escape::Class(_) => return self.fail(item_at, "invalid range"), + } + } else { + hi_char + }; + if hi < lo { + return self.fail(item_at, "reversed range"); + } + items.push(ClassItem::Range(lo, hi)); + } + if items.is_empty() { + return self.fail(at, "empty character class"); + } + Ok(Node::Class { negated, items }) + } +} + +/// What follows the node being matched: the rest of a sequence, or the next iteration of a +/// repeat. Frames are shared, and a chain of them is as long as the pattern is nested, never as +/// long as the text is. +enum Cont<'a> { + Accept, + Seq { nodes: &'a [Node], next: Rc> }, + Iter { rep: &'a Rep, count: u32, start: usize, next: Rc> }, +} + +/// One unit of matching work, started at a text position. +enum Work<'a> { + /// Match `nodes` in order, then follow the continuation. + Nodes(&'a [Node], Rc>), + /// A repeat of a multi-character node has done `count` iterations. + Rep { rep: &'a Rep, count: u32, next: Rc> }, + /// A repeat of a one-character node may take any count from `lo` to `hi`; the position is + /// where the repeat began. + Counts { rest: &'a [Node], next: Rc>, lo: usize, hi: usize, lazy: bool }, + /// Follow the continuation. + Resume(Rc>), +} + +enum Step<'a> { + To(Work<'a>, usize), + Fail, + GaveUp, + Accept, +} + +/// A backtracking matcher whose choice points live on the heap, so the depth of the call stack +/// does not depend on the text. +struct Matcher<'a> { + text: &'a [char], + steps: u64, + budget: u64, + stack: Vec<(Work<'a>, usize)>, +} + +impl<'a> Matcher<'a> { + fn run(text: &'a [char], alts: &'a [Vec]) -> Outcome { + let mut m = Matcher { + text, + steps: 0, + budget: STEP_BUDGET + STEP_ALLOWANCE_PER_CHAR * text.len() as u64, + stack: Vec::new(), + }; + let accept = Rc::new(Cont::Accept); + for alt in alts.iter().rev() { + m.stack.push((Work::Nodes(alt, accept.clone()), 0)); + } + while let Some((mut work, mut pos)) = m.stack.pop() { + loop { + if !m.spend(1) { + return Outcome::GaveUp; + } + match m.step(work, pos) { + Step::To(w, p) => (work, pos) = (w, p), + Step::Fail => break, + Step::GaveUp => return Outcome::GaveUp, + Step::Accept => return Outcome::Match, + } + } + } + Outcome::NoMatch + } + + /// Charges `n` steps; false once the budget is spent. + fn spend(&mut self, n: usize) -> bool { + self.steps = self.steps.saturating_add(n as u64); + self.steps <= self.budget + } + + fn is_single(node: &Node) -> bool { + matches!(node, Node::Char(_) | Node::Any | Node::Class { .. }) + } + + /// Whether a one-character node accepts the character at `pos`. + fn single(&self, node: &Node, pos: usize) -> bool { + let Some(&c) = self.text.get(pos) else { + return false; + }; + match node { + Node::Char(want) => c == *want, + Node::Any => c != '\n', + Node::Class { negated, items } => items.iter().any(|i| i.matches(c)) != *negated, + _ => false, + } + } + + fn step(&mut self, work: Work<'a>, pos: usize) -> Step<'a> { + match work { + Work::Nodes(nodes, next) => match nodes.split_first() { + None => Step::To(Work::Resume(next), pos), + Some((first, rest)) => self.node(first, rest, next, pos), + }, + Work::Rep { rep, count, next } => { + let more = below(rep.max, count).then(|| { + let iter = Cont::Iter { rep, count, start: pos, next: next.clone() }; + Work::Nodes(std::slice::from_ref(&*rep.node), Rc::new(iter)) + }); + let done = (count >= rep.min).then_some(Work::Resume(next)); + let (first, second) = if rep.lazy { (done, more) } else { (more, done) }; + if let Some(work) = second { + self.stack.push((work, pos)); + } + first.map_or(Step::Fail, |work| Step::To(work, pos)) + } + Work::Counts { rest, next, lo, hi, lazy } => { + let take = if lazy { lo } else { hi }; + if lo < hi { + let (lo, hi) = if lazy { (lo + 1, hi) } else { (lo, hi - 1) }; + self.stack.push((Work::Counts { rest, next: next.clone(), lo, hi, lazy }, pos)); + } + Step::To(Work::Nodes(rest, next), pos + take) + } + Work::Resume(next) => match &*next { + Cont::Accept if pos == self.text.len() => Step::Accept, + Cont::Accept => Step::Fail, + Cont::Seq { nodes, next } => Step::To(Work::Nodes(nodes, next.clone()), pos), + Cont::Iter { rep, count, start, next } => { + // An iteration that consumed nothing and is past the minimum adds nothing. + if pos == *start && *count >= rep.min { + Step::Fail + } else { + Step::To(Work::Rep { rep, count: count + 1, next: next.clone() }, pos) + } + } + }, + } + } + + fn node( + &mut self, + node: &'a Node, + rest: &'a [Node], + next: Rc>, + pos: usize, + ) -> Step<'a> { + match node { + Node::Start if pos == 0 => Step::To(Work::Nodes(rest, next), pos), + Node::End if pos == self.text.len() => Step::To(Work::Nodes(rest, next), pos), + Node::Start | Node::End => Step::Fail, + Node::Group(alts) => { + let after = Rc::new(Cont::Seq { nodes: rest, next }); + for alt in alts.iter().skip(1).rev() { + self.stack.push((Work::Nodes(alt, after.clone()), pos)); + } + alts.first().map_or(Step::Fail, |alt| Step::To(Work::Nodes(alt, after), pos)) + } + Node::Repeat(rep) if Self::is_single(&rep.node) => { + let mut avail = 0; + while below(rep.max.map(|m| m as usize), avail) + && self.single(&rep.node, pos + avail) + { + avail += 1; + } + let lo = rep.min as usize; + if !self.spend(avail) { + return Step::GaveUp; + } + if avail < lo { + return Step::Fail; + } + Step::To(Work::Counts { rest, next, lo, hi: avail, lazy: rep.lazy }, pos) + } + Node::Repeat(rep) => { + let next = Rc::new(Cont::Seq { nodes: rest, next }); + Step::To(Work::Rep { rep, count: 0, next }, pos) + } + _ if self.single(node, pos) => Step::To(Work::Nodes(rest, next), pos + 1), + _ => Step::Fail, + } + } +} diff --git a/examples/rust-service/generated/meta_support/src/validation.rs b/examples/rust-service/generated/meta_support/src/validation.rs new file mode 100644 index 0000000000..7ec652150f --- /dev/null +++ b/examples/rust-service/generated/meta_support/src/validation.rs @@ -0,0 +1,462 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! What `validate()` reports, and the checks it is built from. +//! +//! A generated `validate()` is a list of calls into this module, one per rule the model +//! declares, so the rule a call enforces can be read off the call. A check that is handed +//! `None` passes: an absent value breaks no rule, and whether a member may be absent is a +//! property of its type. Nothing here depends on MetaObjects. +//! +//! This file is written by the `entity` generator into the support crate (`meta_support`) +//! every generated model crate depends on. + +use std::cmp::Ordering; +use std::fmt; + +use super::wire::Decimal; + +/// A value longer or shorter than the model allows. +pub const RULE_LENGTH: &str = "length"; +/// A value that does not match the model's `validator.regex`. +pub const RULE_REGEX: &str = "regex"; +/// A number outside the model's `validator.numeric` bounds. +pub const RULE_NUMERIC: &str = "numeric"; +/// A list with more or fewer items than the model's `validator.array` allows. +pub const RULE_ARRAY: &str = "array"; +/// Text that is not in the form its field type requires. +pub const RULE_FORMAT: &str = "format"; +/// Two members that break the model's `validator.comparison`. +pub const RULE_COMPARISON: &str = "comparison"; +/// A member the model's `validator.requiredWhen` requires and the value lacks. +pub const RULE_REQUIRED_WHEN: &str = "requiredWhen"; +/// A member present when the model's `validator.presentIff` forbids it, or the reverse. +pub const RULE_PRESENT_IFF: &str = "presentIff"; +/// None of the members the model's `validator.atLeastOne` names is present. +pub const RULE_AT_LEAST_ONE: &str = "atLeastOne"; +/// Not exactly one of the members the model's `validator.exactlyOne` names is present. +pub const RULE_EXACTLY_ONE: &str = "exactlyOne"; + +/// One rule a value breaks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Violation { + /// The member that broke the rule, by its wire name; a member of a nested object is + /// `outer.inner`, and an element of a list is `outer[0].inner`. + pub field: String, + /// The rule: `length`, `regex`, `numeric`, `array` or `format`, or the kind of a rule + /// across members (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, + /// `exactlyOne`). + pub rule: &'static str, + pub message: String, +} + +impl Violation { + /// The three parts, for carrying a violation into another crate's `Violation`. + pub fn into_parts(self) -> (String, &'static str, String) { + (self.field, self.rule, self.message) + } +} + +impl fmt::Display for Violation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for Violation {} + +/// Report that `field` breaks `rule`. +pub fn fail(out: &mut Vec, field: &str, rule: &'static str, message: &str) { + out.push(Violation { field: field.to_string(), rule, message: message.to_string() }); +} + +/// The violations of a nested value, with `prefix` put before each member name. +pub fn nested(out: &mut Vec, prefix: &str, found: Vec) { + for Violation { field, rule, message } in found { + out.push(Violation { field: format!("{prefix}.{field}"), rule, message }); + } +} + +/// A string's length in characters is within the bounds. +pub fn length( + out: &mut Vec, + field: &str, + value: Option<&str>, + min: Option, + max: Option, +) { + let Some(value) = value else { return }; + let got = value.chars().count(); + if let Some(min) = min.filter(|&min| got < min) { + fail( + out, + field, + RULE_LENGTH, + &format!("'{field}' must be at least {min} chars (got {got})"), + ); + } + if let Some(max) = max.filter(|&max| got > max) { + fail( + out, + field, + RULE_LENGTH, + &format!("'{field}' must be at most {max} chars (got {got})"), + ); + } +} + +/// A list's item count is within the bounds. +pub fn items( + out: &mut Vec, + field: &str, + count: Option, + min: Option, + max: Option, +) { + let Some(got) = count else { return }; + if let Some(min) = min.filter(|&min| got < min) { + fail( + out, + field, + RULE_ARRAY, + &format!("'{field}' must have at least {min} items (got {got})"), + ); + } + if let Some(max) = max.filter(|&max| got > max) { + fail( + out, + field, + RULE_ARRAY, + &format!("'{field}' must have at most {max} items (got {got})"), + ); + } +} + +/// A number is within the bounds, both inclusive. +pub fn range( + out: &mut Vec, + field: &str, + value: Option, + min: Option, + max: Option, +) where + T: PartialOrd + fmt::Display, +{ + let Some(got) = value else { return }; + if let Some(min) = min.filter(|min| got < *min) { + fail(out, field, RULE_NUMERIC, &format!("'{field}' must be at least {min} (got {got})")); + } + if let Some(max) = max.filter(|max| got > *max) { + fail(out, field, RULE_NUMERIC, &format!("'{field}' must be at most {max} (got {got})")); + } +} + +/// A string matches the model's pattern from its first character to its last. A match that +/// spends its step budget is reported as its own violation, never as a mismatch. +pub fn pattern(out: &mut Vec, field: &str, value: Option<&str>, pattern: &str) { + let Some(value) = value else { return }; + match super::pattern::outcome(pattern, value) { + super::pattern::Outcome::Match => {} + super::pattern::Outcome::NoMatch => { + fail(out, field, RULE_REGEX, &format!("'{field}' does not match required pattern")); + } + super::pattern::Outcome::GaveUp => fail( + out, + field, + RULE_REGEX, + &format!("'{field}' pattern could not be evaluated within limits"), + ), + } +} + +/// A string is in the form `accepts` tests; `must` finishes the sentence "'field' must ...". +pub fn format( + out: &mut Vec, + field: &str, + value: Option<&str>, + accepts: fn(&str) -> bool, + must: &str, +) { + if value.is_some_and(|value| !accepts(value)) { + fail(out, field, RULE_FORMAT, &format!("'{field}' must {must}")); + } +} + +/// A decimal fits `precision` digits with `scale` of them after the point. Nothing is +/// rounded to make it fit. +pub fn decimal( + out: &mut Vec, + field: &str, + value: Option<&Decimal>, + precision: usize, + scale: usize, +) { + if value.is_some_and(|value| !value.fits(precision, scale)) { + let message = format!("'{field}' must fit {precision} digits with {scale} after the point"); + fail(out, field, RULE_FORMAT, &message); + } +} + +/// An absolute URI: a scheme, a non-empty remainder and, when the remainder opens an +/// authority with `//`, a non-empty authority. Surrounding spaces are ignored. +pub fn is_absolute_uri(value: &str) -> bool { + let value = value.trim_matches(|c: char| c <= ' '); + let Some((scheme, rest)) = value.split_once(':') else { return false }; + let mut chars = scheme.chars(); + let scheme_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')); + if !scheme_ok || rest.is_empty() { + return false; + } + match rest.strip_prefix("//") { + None => true, + Some(after) => !after.split(['/', '?', '#']).next().unwrap_or("").is_empty(), + } +} + +/// A DNS host name: at most 253 characters, in dot-separated labels of 1 to 63 letters, +/// digits and hyphens that neither start nor end with a hyphen. +pub fn is_hostname(value: &str) -> bool { + let label = |label: &str| { + let bytes = label.as_bytes(); + (1..=63).contains(&bytes.len()) + && bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-') + && bytes[0] != b'-' + && bytes[bytes.len() - 1] != b'-' + }; + (1..=253).contains(&value.len()) && value.split('.').all(label) +} + +/// An email address in the loose sense: one `@` with text on both sides and no spaces. +pub fn is_email(value: &str) -> bool { + match value.split_once('@') { + Some((local, domain)) => { + !local.is_empty() + && !domain.is_empty() + && !domain.contains('@') + && !value.chars().any(|c| c.is_whitespace() || c.is_control()) + } + None => false, + } +} + +/// A UUID in the 8-4-4-4-12 hexadecimal form. +pub fn is_uuid(value: &str) -> bool { + let bytes = value.as_bytes(); + bytes.len() == 36 + && bytes.iter().enumerate().all(|(at, b)| match at { + 8 | 13 | 18 | 23 => *b == b'-', + _ => b.is_ascii_hexdigit(), + }) +} + +fn two_digits(text: &str) -> Option { + let bytes = text.as_bytes(); + (bytes.len() == 2 && bytes.iter().all(u8::is_ascii_digit)).then(|| text.parse().ok())? +} + +/// Days since 1970-01-01 of a `YYYY-MM-DD` calendar date. +fn date_days(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return None; + } + if !bytes[..4].iter().all(u8::is_ascii_digit) { + return None; + } + let year: i64 = text[..4].parse().ok()?; + let month = two_digits(&text[5..7])?; + let day = two_digits(&text[8..10])?; + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let month_days = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap => 29, + 2 => 28, + _ => return None, + }; + if !(1..=month_days).contains(&day) { + return None; + } + // The days-from-civil algorithm, with March as the first month of the year. + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y.rem_euclid(400); + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + Some(era * 146_097 + day_of_era - 719_468) +} + +/// Nanoseconds since midnight of `HH:MM`, `HH:MM:SS` or `HH:MM:SS.fff`. +fn time_nanos(text: &str) -> Option { + let (clock, fraction) = match text.split_once('.') { + Some((clock, fraction)) => (clock, fraction), + None => (text, ""), + }; + let mut parts = clock.split(':'); + let hour = two_digits(parts.next()?)?; + let minute = two_digits(parts.next()?)?; + let second = match parts.next() { + Some(second) => two_digits(second)?, + None => 0, + }; + if parts.next().is_some() || hour > 23 || minute > 59 || second > 59 { + return None; + } + let has_fraction = text.contains('.'); + if has_fraction && (fraction.is_empty() || clock.len() != 8) { + return None; + } + if !fraction.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let kept = &fraction[..fraction.len().min(9)]; + let nanos: i128 = format!("{kept:0<9}").parse().ok()?; + Some(i128::from((hour * 60 + minute) * 60 + second) * 1_000_000_000 + nanos) +} + +/// A calendar date, `YYYY-MM-DD`. +pub fn is_date(value: &str) -> bool { + date_days(value).is_some() +} + +/// A time of day: `HH:MM:SS`, with an optional fraction of a second. +pub fn is_time(value: &str) -> bool { + time_nanos(value).is_some() +} + +/// A timestamp: a date, `T`, a time of day and an optional zone (`Z` or `+HH:MM`). +pub fn is_timestamp(value: &str) -> bool { + instant_key(Some(value)).is_some() +} + +/// A time of day as a number that orders the way the times do. +pub fn time_key(value: Option<&str>) -> Option { + time_nanos(value?) +} + +/// A timestamp as nanoseconds since 1970-01-01T00:00:00Z, so two timestamps order by the +/// moment they name whatever zone each was written in. One with no zone is read as UTC. +pub fn instant_key(value: Option<&str>) -> Option { + let value = value?; + let (date, rest) = value.split_once(['T', ' '])?; + let (clock, offset_seconds) = if let Some(clock) = rest.strip_suffix(['Z', 'z']) { + (clock, 0) + } else if let Some(at) = rest.rfind(['+', '-']) { + let (clock, zone) = rest.split_at(at); + let (hours, minutes) = zone[1..].split_once(':')?; + let seconds = (two_digits(hours)? * 60 + two_digits(minutes)?) * 60; + (clock, if zone.starts_with('-') { -seconds } else { seconds }) + } else { + (rest, 0) + }; + let seconds = i128::from(date_days(date)? * 86_400 - offset_seconds); + Some(seconds * 1_000_000_000 + time_nanos(clock)?) +} + +/// How two values of a rule across members are compared. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Op { + Eq, + Ne, + Gt, + Gte, + Lt, + Lte, +} + +/// How two values order, or `None` when either is absent: an absent value is SQL `NULL`, +/// and a comparison with it is neither true nor false. +pub fn ord(left: Option, right: Option) -> Option { + left?.partial_cmp(&right?) +} + +/// Whether two values are equal, or `None` when either is absent. +pub fn same(left: Option, right: Option) -> Option { + Some(left? == right?) +} + +/// Whether an ordering satisfies `op`, or `None` when there is no ordering. +pub fn test(ordering: Option, op: Op) -> Option { + let ordering = ordering?; + Some(match op { + Op::Eq => ordering == Ordering::Equal, + Op::Ne => ordering != Ordering::Equal, + Op::Gt => ordering == Ordering::Greater, + Op::Gte => ordering != Ordering::Less, + Op::Lt => ordering == Ordering::Less, + Op::Lte => ordering != Ordering::Greater, + }) +} + +/// Three-valued AND: false when any part is false, unknown when any part is unknown. +pub fn all(parts: &[Option]) -> Option { + if parts.contains(&Some(false)) { + Some(false) + } else if parts.contains(&None) { + None + } else { + Some(true) + } +} + +/// Three-valued OR: true when any part is true, unknown when any part is unknown. +pub fn any(parts: &[Option]) -> Option { + if parts.contains(&Some(true)) { + Some(true) + } else if parts.contains(&None) { + None + } else { + Some(false) + } +} + +/// Three-valued NOT: unknown stays unknown. +pub fn not(value: Option) -> Option { + value.map(|value| !value) +} + +/// `left` against `right` under `op`; unknown when either is absent. +pub fn compare(left: Option, right: Option, op: Op) -> Option { + test(ord(left, right), op) +} + +/// Whether two values differ; unknown when either is absent. +pub fn differ(left: Option, right: Option) -> Option { + not(same(left, right)) +} + +/// Report the rule `name` across members, against `field`, when it applies and does not +/// hold. A rule whose condition is unknown does not apply, and one whose verdict is unknown +/// (a member it compares is absent) holds. +pub fn rule( + out: &mut Vec, + field: &str, + rule: &'static str, + name: &str, + applies: Option, + holds: Option, +) { + if applies == Some(true) && holds == Some(false) { + fail(out, field, rule, &format!("'{field}' breaks the rule '{name}'")); + } +} + +/// A member that must be present when the gate is open. +pub fn required_when(gate: Option, present: bool) -> Option { + Some(present || gate != Some(true)) +} + +/// A member that is present exactly when the gate is open. +pub fn present_iff(gate: Option, present: bool) -> Option { + Some(present == (gate == Some(true))) +} + +/// At least one of the members is present. +pub fn at_least_one(present: &[bool]) -> Option { + Some(present.contains(&true)) +} + +/// Exactly one of the members is present. +pub fn exactly_one(present: &[bool]) -> Option { + Some(present.iter().filter(|present| **present).count() == 1) +} diff --git a/examples/rust-service/generated/meta_support/src/wire.rs b/examples/rust-service/generated/meta_support/src/wire.rs new file mode 100644 index 0000000000..94d67a1f83 --- /dev/null +++ b/examples/rust-service/generated/meta_support/src/wire.rs @@ -0,0 +1,436 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! Wire types of the generated model: exact decimals, signed ISO-8601 durations and the +//! helpers a patch body needs. +//! +//! The Rust standard library has no exact decimal and no signed duration, so the generated +//! support crate carries these two small types. Both hold a value in ONE form (its canonical wire +//! text, or its length in nanoseconds), so two equal values compare equal and serialize to +//! the same bytes. Nothing here depends on MetaObjects. +//! +//! This file is written by the `entity` generator into the support crate (`meta_support`) +//! every generated model crate depends on. + +use std::cmp::Ordering; +use std::fmt; +use std::str::FromStr; + +/// Text that is not in the wire grammar of the type it was parsed as. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WireError { + /// What was being parsed: `decimal` or `duration`. + pub kind: &'static str, + /// The text that was refused. + pub text: String, +} + +impl fmt::Display for WireError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "not a {}: {:?}", self.kind, self.text) + } +} + +impl std::error::Error for WireError {} + +/// The largest exponent a decimal may carry on input. A larger one is refused instead of +/// being expanded into that many digits. +const MAX_DECIMAL_EXPONENT: i64 = 4096; + +/// An exact decimal number, held as its canonical wire text: no exponent, no plus sign, no +/// leading zeros, no trailing fraction zeros, and zero as `0`. It never passes through a +/// float, and it serializes as a JSON string. +/// +/// On input it accepts a JSON string in plain or exponent form (`"12.50"`, `"1e-7"`) and a +/// JSON number, which is exact to 15 significant digits. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Decimal(String); + +impl Decimal { + /// Parse decimal text: an optional `-`, digits with no leading zero, an optional + /// fraction and an optional exponent. Anything else is refused: whitespace, a plus + /// sign, a comma, `NaN`, `Infinity`, hex, `1.` and `.5`. + pub fn parse(text: &str) -> Result { + canonical_decimal(text) + .map(Decimal) + .ok_or_else(|| WireError { kind: "decimal", text: text.to_string() }) + } + + /// The decimal a float prints as at 15 significant digits, the most a float carries + /// exactly. `None` for a value that is not finite. + pub fn from_f64(value: f64) -> Option { + if !value.is_finite() { + return None; + } + canonical_decimal(&format!("{value:.14e}")).map(Decimal) + } + + /// The canonical text. + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn is_negative(&self) -> bool { + self.0.starts_with('-') + } + + fn magnitude(&self) -> (&str, &str) { + let digits = self.0.strip_prefix('-').unwrap_or(&self.0); + digits.split_once('.').unwrap_or((digits, "")) + } + + /// How many digits stand before the decimal point. A value below one has none. + pub fn integer_digits(&self) -> usize { + let (int, _) = self.magnitude(); + if int == "0" { + 0 + } else { + int.len() + } + } + + /// How many digits stand after the decimal point. + pub fn fraction_digits(&self) -> usize { + self.magnitude().1.len() + } + + /// Whether the value fits a column of `precision` digits with `scale` of them after + /// the point, without rounding. + pub fn fits(&self, precision: usize, scale: usize) -> bool { + self.fraction_digits() <= scale && self.integer_digits() <= precision.saturating_sub(scale) + } +} + +fn canonical_decimal(text: &str) -> Option { + let (negative, rest) = match text.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, text), + }; + let (mantissa, exponent) = match rest.find(['e', 'E']) { + Some(at) => (&rest[..at], Some(&rest[at + 1..])), + None => (rest, None), + }; + let (int, frac) = match mantissa.split_once('.') { + Some((int, frac)) => (int, Some(frac)), + None => (mantissa, None), + }; + let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + if !all_digits(int) || (int.len() > 1 && int.starts_with('0')) { + return None; + } + if frac.is_some_and(|f| !all_digits(f)) { + return None; + } + let exponent = match exponent { + None => 0, + Some(e) => { + let digits = e.strip_prefix(['+', '-']).unwrap_or(e); + if !all_digits(digits) { + return None; + } + let magnitude = digits.parse::().unwrap_or(i64::MAX); + if e.starts_with('-') { + -magnitude + } else { + magnitude + } + } + }; + let frac = frac.unwrap_or(""); + let all = format!("{int}{frac}"); + let digits = all.trim_start_matches('0'); + if digits.is_empty() { + return Some("0".to_string()); + } + if exponent.abs() > MAX_DECIMAL_EXPONENT { + return None; + } + // The decimal point sits `point` digits into `digits`. + let dropped = i64::try_from(all.len() - digits.len()).ok()?; + let point = i64::try_from(int.len()).ok()? + exponent - dropped; + let len = i64::try_from(digits.len()).ok()?; + let (int_part, frac_part) = if point <= 0 { + let zeros = "0".repeat(usize::try_from(-point).ok()?); + ("0".to_string(), format!("{zeros}{digits}")) + } else if point >= len { + let zeros = "0".repeat(usize::try_from(point - len).ok()?); + (format!("{digits}{zeros}"), String::new()) + } else { + let (a, b) = digits.split_at(usize::try_from(point).ok()?); + (a.to_string(), b.to_string()) + }; + let frac_part = frac_part.trim_end_matches('0'); + let mut out = String::new(); + if negative { + out.push('-'); + } + out.push_str(&int_part); + if !frac_part.is_empty() { + out.push('.'); + out.push_str(frac_part); + } + Some(out) +} + +impl Ord for Decimal { + fn cmp(&self, other: &Self) -> Ordering { + match (self.is_negative(), other.is_negative()) { + (false, true) => return Ordering::Greater, + (true, false) => return Ordering::Less, + _ => {} + } + let (a_int, a_frac) = self.magnitude(); + let (b_int, b_frac) = other.magnitude(); + let magnitude = a_int + .len() + .cmp(&b_int.len()) + .then_with(|| a_int.cmp(b_int)) + .then_with(|| a_frac.cmp(b_frac)); + if self.is_negative() { + magnitude.reverse() + } else { + magnitude + } + } +} + +impl PartialOrd for Decimal { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl fmt::Display for Decimal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl FromStr for Decimal { + type Err = WireError; + + fn from_str(text: &str) -> Result { + Decimal::parse(text) + } +} + +impl From for Decimal { + fn from(value: i64) -> Self { + Decimal(value.to_string()) + } +} + +impl serde::Serialize for Decimal { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +struct DecimalVisitor; + +impl serde::de::Visitor<'_> for DecimalVisitor { + type Value = Decimal; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a decimal as a string or a number") + } + + fn visit_str(self, text: &str) -> Result { + Decimal::parse(text).map_err(E::custom) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(Decimal(value.to_string())) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(Decimal(value.to_string())) + } + + fn visit_f64(self, value: f64) -> Result { + Decimal::from_f64(value).ok_or_else(|| E::custom("a decimal must be finite")) + } +} + +impl<'de> serde::Deserialize<'de> for Decimal { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(DecimalVisitor) + } +} + +const NANOS_PER_SECOND: i128 = 1_000_000_000; +const NANOS_PER_MINUTE: i128 = 60 * NANOS_PER_SECOND; +const NANOS_PER_HOUR: i128 = 60 * NANOS_PER_MINUTE; + +/// A signed span of time, held in nanoseconds and written as an ISO-8601 duration. +/// +/// On input it accepts weeks, days, hours, minutes and seconds (`P1DT2H`, `-PT30S`, +/// `PT0.5S`); a day is 24 hours and a week is 7 days. Years and months are refused, +/// because their length depends on a calendar. Only the seconds may carry a fraction, and +/// digits past the ninth are dropped. On output hours are never folded into days: 26 hours +/// is `PT26H`, and zero is `PT0S`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Duration { + nanos: i128, +} + +impl Duration { + pub const ZERO: Duration = Duration { nanos: 0 }; + + pub const fn from_nanos(nanos: i128) -> Self { + Duration { nanos } + } + + /// The length in nanoseconds; negative for a negative duration. + pub const fn nanos(self) -> i128 { + self.nanos + } + + pub fn parse(text: &str) -> Result { + duration_nanos(text) + .map(Duration::from_nanos) + .ok_or_else(|| WireError { kind: "duration", text: text.to_string() }) + } +} + +/// The digits at the start of `text` and what follows them. +fn leading_digits(text: &str) -> (&str, &str) { + let end = text.bytes().position(|b| !b.is_ascii_digit()).unwrap_or(text.len()); + text.split_at(end) +} + +fn duration_nanos(text: &str) -> Option { + let (negative, rest) = match text.strip_prefix(['-', '+']) { + Some(rest) => (text.starts_with('-'), rest), + None => (false, text), + }; + let mut rest = rest.strip_prefix('P')?; + if rest.is_empty() { + return None; + } + let mut total: i128 = 0; + // The date part: weeks, then days, each at most once. + for (unit, hours) in [('W', 7 * 24), ('D', 24)] { + let (digits, after) = leading_digits(rest); + if !digits.is_empty() && after.starts_with(unit) { + let count = digits.parse::().ok()?; + total = total.checked_add(count.checked_mul(hours * NANOS_PER_HOUR)?)?; + rest = &after[1..]; + } + } + if let Some(time) = rest.strip_prefix('T') { + if !time.starts_with(|c: char| c.is_ascii_digit()) { + return None; + } + rest = time; + for (unit, nanos) in [('H', NANOS_PER_HOUR), ('M', NANOS_PER_MINUTE)] { + let (digits, after) = leading_digits(rest); + if !digits.is_empty() && after.starts_with(unit) { + let count = digits.parse::().ok()?; + total = total.checked_add(count.checked_mul(nanos)?)?; + rest = &after[1..]; + } + } + let (digits, after) = leading_digits(rest); + if !digits.is_empty() { + let (fraction, after) = match after.strip_prefix('.') { + Some(tail) => { + let (fraction, after) = leading_digits(tail); + if fraction.is_empty() { + return None; + } + (fraction, after) + } + None => ("", after), + }; + let seconds = digits.parse::().ok()?; + total = total.checked_add(seconds.checked_mul(NANOS_PER_SECOND)?)?; + // Nine fraction digits are kept; the rest are dropped, toward zero. + let kept = &fraction[..fraction.len().min(9)]; + total = total.checked_add(format!("{kept:0<9}").parse::().ok()?)?; + rest = after.strip_prefix('S')?; + } + } + if !rest.is_empty() { + return None; + } + Some(if negative { -total } else { total }) +} + +impl fmt::Display for Duration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.nanos == 0 { + return f.write_str("PT0S"); + } + let magnitude = self.nanos.unsigned_abs(); + let hours = magnitude / NANOS_PER_HOUR.unsigned_abs(); + let minutes = magnitude / NANOS_PER_MINUTE.unsigned_abs() % 60; + let seconds = magnitude / NANOS_PER_SECOND.unsigned_abs() % 60; + let fraction = magnitude % NANOS_PER_SECOND.unsigned_abs(); + if self.nanos < 0 { + f.write_str("-")?; + } + f.write_str("PT")?; + if hours > 0 { + write!(f, "{hours}H")?; + } + if minutes > 0 { + write!(f, "{minutes}M")?; + } + if fraction > 0 { + let digits = format!("{fraction:09}"); + write!(f, "{seconds}.{}S", digits.trim_end_matches('0'))?; + } else if seconds > 0 { + write!(f, "{seconds}S")?; + } + Ok(()) + } +} + +impl FromStr for Duration { + type Err = WireError; + + fn from_str(text: &str) -> Result { + Duration::parse(text) + } +} + +impl serde::Serialize for Duration { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +struct DurationVisitor; + +impl serde::de::Visitor<'_> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an ISO-8601 duration such as PT1H30M (no years or months)") + } + + fn visit_str(self, text: &str) -> Result { + Duration::parse(text).map_err(E::custom) + } +} + +impl<'de> serde::Deserialize<'de> for Duration { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_str(DurationVisitor) + } +} + +/// Deserializes a member of a patch body: a member that is present, `null` included, +/// becomes `Some`, so a patch can tell "set this to null" from "leave this alone". +pub fn present<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::Deserialize<'de>, +{ + T::deserialize(deserializer).map(Some) +} + +/// The value a patch sets for a nullable member, when it sets one that is not null. +pub fn set(member: &Option>) -> Option<&T> { + member.as_ref().and_then(Option::as_ref) +} diff --git a/examples/rust-service/generated/tasks/Cargo.toml b/examples/rust-service/generated/tasks/Cargo.toml new file mode 100644 index 0000000000..a63f31adc3 --- /dev/null +++ b/examples/rust-service/generated/tasks/Cargo.toml @@ -0,0 +1,11 @@ +# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "tasks" +version = "0.1.0" +edition = "2021" +publish = false +description = "Generated from the MetaObjects package tasks." + +[dependencies] +serde = { version = "1", features = ["derive"] } +meta_support = { path = "../meta_support" } diff --git a/examples/rust-service/generated/tasks/rustfmt.toml b/examples/rust-service/generated/tasks/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/tasks/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/tasks/src/lib.rs b/examples/rust-service/generated/tasks/src/lib.rs new file mode 100644 index 0000000000..8c756ae86f --- /dev/null +++ b/examples/rust-service/generated/tasks/src/lib.rs @@ -0,0 +1,10 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! Generated from the MetaObjects package `tasks`. + +mod task; + +pub use task::Task; +pub use task::TaskCreate; +pub use task::TaskPatch; +pub use task::TaskStatus; diff --git a/examples/rust-service/generated/tasks/src/task.rs b/examples/rust-service/generated/tasks/src/task.rs new file mode 100644 index 0000000000..3002027996 --- /dev/null +++ b/examples/rust-service/generated/tasks/src/task.rs @@ -0,0 +1,85 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +/// One piece of work, from the moment it is written down until it is done. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Task { + pub id: i64, + pub title: String, + pub notes: Option, + pub status: Option, +} + +/// What a caller sends to create one `Task`: the members the server does not fill itself. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct TaskCreate { + pub title: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub notes: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl TaskCreate { + /// Every rule of the model this value breaks; empty when it breaks none. + pub fn validate(&self) -> Vec { + use meta_support::validation as check; + let mut out = Vec::new(); + check::length(&mut out, "title", Some(self.title.as_str()), Some(1), Some(120)); + check::length(&mut out, "notes", self.notes.as_deref(), None, Some(2000)); + out + } +} + +/// A change to one `Task`: a member left `None` is not touched. A member the model lets be +/// null is `Some(None)` to set it to null. +#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct TaskPatch { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default)] + #[serde(deserialize_with = "meta_support::wire::present")] + #[serde(skip_serializing_if = "Option::is_none")] + pub notes: Option>, + #[serde(default)] + #[serde(deserialize_with = "meta_support::wire::present")] + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option>, +} + +impl TaskPatch { + /// Every rule of the model this value breaks; empty when it breaks none. + pub fn validate(&self) -> Vec { + use meta_support::validation as check; + let mut out = Vec::new(); + check::length(&mut out, "title", self.title.as_deref(), Some(1), Some(120)); + check::length( + &mut out, + "notes", + meta_support::wire::set(&self.notes).map(|v| v.as_str()), + None, + Some(2000), + ); + out + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum TaskStatus { + #[serde(rename = "todo")] + Todo, + #[serde(rename = "doing")] + Doing, + #[serde(rename = "done")] + Done, +} + +impl TaskStatus { + /// The wire spelling of the member. + pub const fn as_str(self) -> &'static str { + match self { + TaskStatus::Todo => "todo", + TaskStatus::Doing => "doing", + TaskStatus::Done => "done", + } + } +} diff --git a/examples/rust-service/generated/tasks_http/Cargo.toml b/examples/rust-service/generated/tasks_http/Cargo.toml new file mode 100644 index 0000000000..9d484a0515 --- /dev/null +++ b/examples/rust-service/generated/tasks_http/Cargo.toml @@ -0,0 +1,15 @@ +# @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "tasks_http" +version = "0.1.0" +edition = "2021" +publish = false +description = "The REST routes of the MetaObjects package tasks." + +[dependencies] +meta_http = { path = "../meta_http" } +meta_service = { path = "../meta_service" } +meta_store = { path = "../meta_store" } +tasks = { path = "../tasks" } +tasks_service = { path = "../tasks_service" } +axum = { version = "0.8", default-features = false, features = ["json", "query"] } diff --git a/examples/rust-service/generated/tasks_http/rustfmt.toml b/examples/rust-service/generated/tasks_http/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/tasks_http/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/tasks_http/src/lib.rs b/examples/rust-service/generated/tasks_http/src/lib.rs new file mode 100644 index 0000000000..c675c67875 --- /dev/null +++ b/examples/rust-service/generated/tasks_http/src/lib.rs @@ -0,0 +1,103 @@ +// @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. + +//! The REST routes of the MetaObjects package `tasks` (ADR-0067 layer 5): each +//! route reads its request, calls one operation of [`TasksService`] and sends +//! what it answered. The rules are the service's. + +mod task; + +use std::sync::Arc; + +use axum::Router; +use axum::body::Bytes; +use axum::extract::{Path, RawQuery}; +use axum::http::HeaderMap; +use axum::routing::{get, post}; +use meta_http::ActorSource; +use tasks_service::TasksService; + +/// The service and the actor source every route shares. +struct App { + service: S, + actor: X, +} + +#[rustfmt::skip] +/// The package's routes, to mount under the API root. `actor` reads who a request +/// runs for; `()` reads no one. +pub fn router(service: TasksService, actor: X) -> Router +where + D: meta_service::Db + 'static, + A: Send + Sync + 'static, + P: tasks_service::TasksPolicy + 'static, + H: tasks_service::TasksHooks + 'static, + E: tasks_service::TasksEvents + 'static, + X: ActorSource, +{ + let app = Arc::new(App { service, actor }); + + let a = app.clone(); + let on_list_task = move |RawQuery(raw): RawQuery| async move { + let l = meta_http::list(raw.as_deref(), &task::LIST)?; + meta_http::page(a.service.list_task(&l.query, l.with_count).await, &[]) + }; + + let a = app.clone(); + let on_get_task = move |Path(id): Path| async move { + let id: i64 = meta_http::int_key(&id)?; + meta_http::ok(a.service.get_task(id).await, &[]) + }; + + let a = app.clone(); + let on_create_task = move |headers: HeaderMap, body: Bytes| async move { + let check = tasks::TaskPatch::validate; + let input = meta_http::create_body::(&body, &task::BODY, check)?; + let actor = a.actor.actor(&headers); + meta_http::created(a.service.create_task(actor.as_ref(), input).await, &[]) + }; + + let a = app.clone(); + let on_update_task = move |Path(id): Path, headers: HeaderMap, body: Bytes| async move { + let id: i64 = meta_http::int_key(&id)?; + let check = tasks::TaskPatch::validate; + let patch = meta_http::update_body(&body, &task::BODY, check)?; + let actor = a.actor.actor(&headers); + meta_http::ok(a.service.update_task(actor.as_ref(), id, patch).await, &[]) + }; + + let a = app.clone(); + let on_delete_task = move |Path(id): Path, headers: HeaderMap| async move { + let id: i64 = meta_http::int_key(&id)?; + let actor = a.actor.actor(&headers); + meta_http::no_content(a.service.delete_task(actor.as_ref(), id).await) + }; + + let a = app.clone(); + let on_start_task = move |Path(id): Path, headers: HeaderMap| async move { + let id: i64 = meta_http::int_key(&id)?; + let actor = a.actor.actor(&headers); + meta_http::ok(a.service.start_task(actor.as_ref(), id).await, &[]) + }; + + let a = app.clone(); + let on_finish_task = move |Path(id): Path, headers: HeaderMap| async move { + let id: i64 = meta_http::int_key(&id)?; + let actor = a.actor.actor(&headers); + meta_http::ok(a.service.finish_task(actor.as_ref(), id).await, &[]) + }; + + let a = app.clone(); + let on_reopen_task = move |Path(id): Path, headers: HeaderMap| async move { + let id: i64 = meta_http::int_key(&id)?; + let actor = a.actor.actor(&headers); + meta_http::ok(a.service.reopen_task(actor.as_ref(), id).await, &[]) + }; + + let mut router = Router::new(); + router = router.route("/tasks", get(on_list_task).post(on_create_task)); + router = router.route("/tasks/{id}", get(on_get_task).patch(on_update_task.clone()).put(on_update_task).delete(on_delete_task)); + router = router.route("/tasks/{id}/start", post(on_start_task)); + router = router.route("/tasks/{id}/finish", post(on_finish_task)); + router = router.route("/tasks/{id}/reopen", post(on_reopen_task)); + router +} diff --git a/examples/rust-service/generated/tasks_http/src/task.rs b/examples/rust-service/generated/tasks_http/src/task.rs new file mode 100644 index 0000000000..848fea0e4c --- /dev/null +++ b/examples/rust-service/generated/tasks_http/src/task.rs @@ -0,0 +1,38 @@ +// @generated by the MetaObjects service-routes generator. Do not edit: change the model and run `cargo meta gen`. + +//! The list and body rules of `Task`'s routes. + +use meta_http::{BodySpec, FilterRule, Kind, ListSpec, SortRule}; + +/// What `GET /tasks` accepts. +pub static LIST: ListSpec = ListSpec { + filters: &[ + FilterRule { + field: "title", + ops: &["eq", "ne", "in", "like", "isNull"], + kind: Kind::Text, + values: None, + }, + FilterRule { + field: "status", + ops: &["eq", "ne", "in", "like", "isNull"], + kind: Kind::Text, + values: Some(&["todo", "doing", "done"]), + }, + ], + sorts: &[ + SortRule { field: "title", descending: false }, + SortRule { field: "status", descending: false }, + ], + fields: &["id", "title", "notes", "status"], +}; + +/// What a body sent to `/tasks` may carry. +pub static BODY: BodySpec = BodySpec { + declared: &["id", "title", "notes", "status"], + create: &["title", "notes", "status"], + create_required: &["title"], + update: &["title", "notes", "status"], + update_not_null: &["title"], + reject_unknown: true, +}; diff --git a/examples/rust-service/generated/tasks_rules/Cargo.toml b/examples/rust-service/generated/tasks_rules/Cargo.toml new file mode 100644 index 0000000000..dbced059c7 --- /dev/null +++ b/examples/rust-service/generated/tasks_rules/Cargo.toml @@ -0,0 +1,10 @@ +# @generated by the MetaObjects rules-names generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "tasks_rules" +version = "0.1.0" +edition = "2021" +publish = false +description = "The rules names (states, transitions, commands, operations, permissions and errors) of the MetaObjects package tasks." + +[dependencies] +tasks = { path = "../tasks" } diff --git a/examples/rust-service/generated/tasks_rules/rustfmt.toml b/examples/rust-service/generated/tasks_rules/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/tasks_rules/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/tasks_rules/src/lib.rs b/examples/rust-service/generated/tasks_rules/src/lib.rs new file mode 100644 index 0000000000..878d203507 --- /dev/null +++ b/examples/rust-service/generated/tasks_rules/src/lib.rs @@ -0,0 +1,184 @@ +// @generated by the MetaObjects rules-names generator. Do not edit: change the model and run `cargo meta gen`. + +//! The rules names of the MetaObjects package `tasks`. +//! +//! Name a state, a transition, a permission or an error code through these types, and +//! code that names one the model renamed or removed stops compiling. + +/// A wire code the enforcing shell answers with on its own (ADR-0066 §6). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ShellError { + NotFound, + Forbidden, + InvalidTransition, + TransitionConditionFailed, + StateManaged, +} + +impl ShellError { + /// Every one. + pub const ALL: &[ShellError] = &[ + ShellError::NotFound, + ShellError::Forbidden, + ShellError::InvalidTransition, + ShellError::TransitionConditionFailed, + ShellError::StateManaged, + ]; + + /// Its wire code. + #[must_use] + pub const fn code(self) -> &'static str { + match self { + ShellError::NotFound => "not_found", + ShellError::Forbidden => "forbidden", + ShellError::InvalidTransition => "invalid_transition", + ShellError::TransitionConditionFailed => "transition_condition_failed", + ShellError::StateManaged => "state_managed", + } + } +} + +/// The rules names of `Task`. +pub mod task { + /// The lifecycle of `Task.status`: its states, initial and terminal states, and transitions. + pub mod status { + /// A state of the lifecycle: the model's own enum for the field. + pub use tasks::TaskStatus as State; + + /// The lifecycle's field. + pub const FIELD: &str = "status"; + + /// Every state, in the model's order. + pub const STATES: &[State] = &[State::Todo, State::Doing, State::Done]; + + /// The state a new record starts in (the field's `@default`). + pub const INITIAL: State = State::Todo; + + /// The states no transition leaves. + pub const TERMINAL: &[State] = &[]; + + /// A transition of the lifecycle. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub enum Transition { + Start, + Finish, + Reopen, + } + + impl Transition { + /// Every one. + pub const ALL: &[Transition] = + &[Transition::Start, Transition::Finish, Transition::Reopen]; + + /// Its name in the model. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Transition::Start => "start", + Transition::Finish => "finish", + Transition::Reopen => "reopen", + } + } + + /// The states it may start from (`@from`). + #[must_use] + pub const fn from(self) -> &'static [State] { + match self { + Transition::Start => &[State::Todo], + Transition::Finish => &[State::Todo, State::Doing], + Transition::Reopen => &[State::Done], + } + } + + /// The state it ends in (`@to`). + #[must_use] + pub const fn to(self) -> State { + match self { + Transition::Start => State::Doing, + Transition::Finish => State::Done, + Transition::Reopen => State::Todo, + } + } + } + } + + /// A command derived from a transition of `Task` (ADR-0066 §2): it takes the key and makes its + /// transition. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub enum Command { + Start, + Finish, + Reopen, + } + + impl Command { + /// Every one. + pub const ALL: &[Command] = &[Command::Start, Command::Finish, Command::Reopen]; + + /// Its name in the model: its transition's. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Command::Start => "start", + Command::Finish => "finish", + Command::Reopen => "reopen", + } + } + + /// The field of the lifecycle its transition belongs to. + #[must_use] + pub const fn lifecycle(self) -> &'static str { + match self { + Command::Start => "status", + Command::Finish => "status", + Command::Reopen => "status", + } + } + + /// The permission the shell asks the policy about; `None` when it is `@public`. + #[must_use] + pub const fn permission(self) -> Option { + match self { + Command::Start => Some(crate::Permission::TasksTaskStart), + Command::Finish => Some(crate::Permission::TasksTaskFinish), + Command::Reopen => None, + } + } + } +} + +/// A permission a point of the package asks about: what a grant table names. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Permission { + TasksTaskFinish, + TasksTaskStart, +} + +impl Permission { + /// Every one. + pub const ALL: &[Permission] = &[Permission::TasksTaskFinish, Permission::TasksTaskStart]; + + /// Its dotted name, as the policy is asked about it. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Permission::TasksTaskFinish => "tasks.Task.finish", + Permission::TasksTaskStart => "tasks.Task.start", + } + } +} + +/// A business error the package's commands declare (`@errors`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BusinessError {} + +impl BusinessError { + /// Every one. + pub const ALL: &[BusinessError] = &[]; + + /// Its wire code. + #[must_use] + pub const fn code(self) -> &'static str { + match self {} + } +} diff --git a/examples/rust-service/generated/tasks_service/Cargo.toml b/examples/rust-service/generated/tasks_service/Cargo.toml new file mode 100644 index 0000000000..722c6ba9df --- /dev/null +++ b/examples/rust-service/generated/tasks_service/Cargo.toml @@ -0,0 +1,16 @@ +# @generated by the MetaObjects service generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "tasks_service" +version = "0.1.0" +edition = "2021" +publish = false +description = "The service layer of the MetaObjects package tasks." + +[dependencies] +meta_service = { path = "../meta_service" } +meta_store = { path = "../meta_store" } +meta_support = { path = "../meta_support" } +tasks = { path = "../tasks" } +tasks_rules = { path = "../tasks_rules" } +tasks_store = { path = "../tasks_store" } +serde_json = "1" diff --git a/examples/rust-service/generated/tasks_service/rustfmt.toml b/examples/rust-service/generated/tasks_service/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/tasks_service/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/tasks_service/src/lib.rs b/examples/rust-service/generated/tasks_service/src/lib.rs new file mode 100644 index 0000000000..84b991b48a --- /dev/null +++ b/examples/rust-service/generated/tasks_service/src/lib.rs @@ -0,0 +1,130 @@ +// @generated by the MetaObjects service generator. Do not edit: change the model and run `cargo meta gen`. + +//! The service layer of the MetaObjects package `tasks` (ADR-0067 layer 4). +//! +//! [`TasksService`] runs each operation over the store crate, a write in one transaction, +//! calling the hand-written pieces it is built with at their points: the policy, the +//! bodies, the hooks and the event hook. + +mod task; + +use std::future::Future; + +use tasks as model; + +pub use meta_service::{BodyError, Cx, Db, Page, ServiceError, WriteEvent, WriteKind}; + +/// What every operation of the package answers an error with. +pub type TasksError = ServiceError; + +/// The policy: whether the actor may pass a permission point, given the loaded row and the +/// validated input as JSON. Asked before anything is written; a refusal is 403 `forbidden`. Who +/// holds a permission is data, so the answer is the application's. +pub trait TasksPolicy: Send + Sync { + /// Whether `actor` may pass the point that asks about `permission`. + fn allows<'a>( + &'a self, + permission: tasks_rules::Permission, + actor: Option<&'a A>, + row: Option<&'a serde_json::Value>, + input: Option<&'a serde_json::Value>, + conn: &'a mut C, + ) -> impl Future> + Send + 'a; +} + +/// A derived write, as its before hook is told of it: the input or patch to write, which the hook +/// may change, and the row an update or a delete starts from. +pub enum TasksBefore<'a> { + CreateTask(&'a mut model::TaskCreate), + UpdateTask { patch: &'a mut model::TaskPatch, current: &'a model::Task }, + DeleteTask(&'a model::Task), +} + +/// A derived write, as its after hook is told of it: the row written, the row before an update, and +/// the row a delete removed. +pub enum TasksAfter<'a> { + CreateTask(&'a model::Task), + UpdateTask { row: &'a model::Task, previous: &'a model::Task }, + DeleteTask(&'a model::Task), +} + +/// The hooks around each derived write, in its transaction: the before hook may change the input or +/// patch or refuse, the after hook may refuse, and a refusal undoes the write. Each does nothing +/// unless implemented; `()` implements neither. +pub trait TasksHooks: Send + Sync { + /// Before a create, an update or a delete, after the row is loaded and before it is validated. + fn before<'a>( + &'a self, + _write: TasksBefore<'a>, + _cx: Cx<'a, A, C>, + ) -> impl Future> + Send + 'a { + async { Ok(()) } + } + + /// After a create, an update or a delete, before the event hook. + fn after<'a>( + &'a self, + _write: TasksAfter<'a>, + _cx: Cx<'a, A, C>, + ) -> impl Future> + Send + 'a { + async { Ok(()) } + } +} + +impl TasksHooks for () {} + +/// The event hook: told of every write last, inside its transaction, so a refusal undoes the write. +/// `()` is the one that does nothing. +pub trait TasksEvents: Send + Sync { + /// One write. + fn on_write<'a>( + &'a self, + _event: &'a WriteEvent<'a, A>, + _conn: &'a mut C, + ) -> impl Future> + Send + 'a { + async { Ok(()) } + } +} + +impl TasksEvents for () {} + +/// The service of the MetaObjects package `tasks`: `D` the store, `A` the actor, `P` the policy, +/// `H` the hooks and `E` the event hook. +pub struct TasksService { + pub db: D, + pub policy: P, + pub hooks: H, + pub events: E, + actor: std::marker::PhantomData, +} + +impl TasksService { + /// A service with no hooks and no event hook. + pub fn new(db: D, policy: P) -> Self { + TasksService { db, policy, hooks: (), events: (), actor: std::marker::PhantomData } + } +} + +impl TasksService { + /// The service with these hooks. + pub fn with_hooks

(self, hooks: H2) -> TasksService { + TasksService { + db: self.db, + policy: self.policy, + hooks, + events: self.events, + actor: std::marker::PhantomData, + } + } + + /// The service with these event hook. + pub fn with_events(self, events: E2) -> TasksService { + TasksService { + db: self.db, + policy: self.policy, + hooks: self.hooks, + events, + actor: std::marker::PhantomData, + } + } +} diff --git a/examples/rust-service/generated/tasks_service/src/task.rs b/examples/rust-service/generated/tasks_service/src/task.rs new file mode 100644 index 0000000000..2f269fb465 --- /dev/null +++ b/examples/rust-service/generated/tasks_service/src/task.rs @@ -0,0 +1,303 @@ +// @generated by the MetaObjects service generator. Do not edit: change the model and run `cargo meta gen`. + +use meta_service::{Cx, Page, ServiceError, WriteEvent, WriteKind}; +use tasks_store::task as store; +use tasks_rules::task as rules; + +type Row = tasks::Task; +type Create = tasks::TaskCreate; +type Patch = tasks::TaskPatch; + +impl crate::TasksService +where + D: meta_service::Db, + A: Sync, + P: crate::TasksPolicy, + H: crate::TasksHooks, + E: crate::TasksEvents, +{ + /// A page of `Task` rows: the filter, sort and page of `query` (50 rows when it names no limit, + /// `limit_too_large` above 1000), ordered by the key when it names no sort; with the count of + /// the rows the filter selects when `with_count`. + pub async fn list_task( + &self, + query: &meta_store::Query, + with_count: bool, + ) -> Result, ServiceError> { + let mut c = self.db.read().await?; + let mut query = query.clone(); + let limit = meta_service::page_limit(query.limit, 50, Some(1000))?; + query.limit = Some(limit); + if query.sort.is_empty() { + query.sort.push(meta_store::Sort { field: "id".to_string(), descending: false }); + } + let rows = store::list(&mut *c, &query).await?; + let total = match with_count { + true => Some(store::count(&mut *c, query.filter.as_ref()).await?), + false => None, + }; + Ok(Page { rows, total }) + } + + /// The `Task` row `id` names: `not_found` when there is none. + pub async fn get_task(&self, id: i64) -> Result { + let mut c = self.db.read().await?; + store::get(&mut *c, id).await?.ok_or(ServiceError::NotFound) + } + + /// Create a `Task`: the before hook (it may replace the input or refuse), validate it, insert + /// it, the after hook and the event hook. Answers the row written. In one transaction. + pub async fn create_task(&self, actor: Option<&A>, input: Create) -> Result { + let mut tx = self.db.begin().await?; + let out = self.create_task_in(&mut *tx, actor, input).await; + meta_service::finish::(tx, out).await + } + + /// `create_task` on `conn`, inside the caller's transaction. + pub async fn create_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + mut input: Create, + ) -> Result { + let cx = Cx { conn: &mut *conn, actor }; + let before = crate::TasksBefore::CreateTask(&mut input); + self.hooks.before(before, cx).await?; + meta_service::validated(input.validate())?; + // rules.lifecycle.create is "initial": a create starts `status` in its initial state. + if input.status.is_some_and(|s| s != rules::status::INITIAL) { + return Err(ServiceError::StateManaged); + } + let row = store::create(&mut *conn, &input).await?; + let cx = Cx { conn: &mut *conn, actor }; + let after = crate::TasksAfter::CreateTask(&row); + self.hooks.after(after, cx).await?; + let mut event = WriteEvent::new(WriteKind::Create, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(&row.id)); + event.row = Some(meta_service::json(&row)); + self.events.on_write(&event, &mut *conn).await?; + Ok(row) + } + + /// Update the `Task` row `id` names with `patch`: load it under a row lock (`not_found`), the + /// before hook, validate it, write it, the after hook and the event hook. In one transaction. + pub async fn update_task( + &self, + actor: Option<&A>, + id: i64, + patch: Patch, + ) -> Result { + let mut tx = self.db.begin().await?; + let out = self.update_task_in(&mut *tx, actor, id, patch).await; + meta_service::finish::(tx, out).await + } + + /// `update_task` on `conn`, inside the caller's transaction. + pub async fn update_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + id: i64, + mut patch: Patch, + ) -> Result { + let current = meta_store::get_for_update(&mut *conn, &store::TABLE, id).await?; + let current: Row = current.ok_or(ServiceError::NotFound)?; + let cx = Cx { conn: &mut *conn, actor }; + let before = crate::TasksBefore::UpdateTask { patch: &mut patch, current: ¤t }; + self.hooks.before(before, cx).await?; + meta_service::validated(patch.validate())?; + // A lifecycle moves only through its transitions (ADR-0066 §6): naming the state + // the row is in is no move. + if let Some(state) = patch.status.take() { + if state != current.status { + return Err(ServiceError::StateManaged); + } + } + let row = store::update(&mut *conn, id, &patch).await?; + let row = row.ok_or(ServiceError::NotFound)?; + let cx = Cx { conn: &mut *conn, actor }; + let after = crate::TasksAfter::UpdateTask { row: &row, previous: ¤t }; + self.hooks.after(after, cx).await?; + let mut event = WriteEvent::new(WriteKind::Update, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(&row.id)); + event.row = Some(meta_service::json(&row)); + event.previous = Some(meta_service::json(¤t)); + self.events.on_write(&event, &mut *conn).await?; + Ok(row) + } + + /// Delete the `Task` row `id` names: load it under a row lock (`not_found`), the before hook, + /// the delete, the after hook and the event hook. In one transaction. + pub async fn delete_task(&self, actor: Option<&A>, id: i64) -> Result<(), ServiceError> { + let mut tx = self.db.begin().await?; + let out = self.delete_task_in(&mut *tx, actor, id).await; + meta_service::finish::(tx, out).await + } + + /// `delete_task` on `conn`, inside the caller's transaction. + pub async fn delete_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + id: i64, + ) -> Result<(), ServiceError> { + let current = meta_store::get_for_update(&mut *conn, &store::TABLE, id).await?; + let current: Row = current.ok_or(ServiceError::NotFound)?; + let cx = Cx { conn: &mut *conn, actor }; + let before = crate::TasksBefore::DeleteTask(¤t); + self.hooks.before(before, cx).await?; + store::delete(&mut *conn, id).await?; + let cx = Cx { conn: &mut *conn, actor }; + let after = crate::TasksAfter::DeleteTask(¤t); + self.hooks.after(after, cx).await?; + let mut event = WriteEvent::new(WriteKind::Delete, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(¤t.id)); + event.row = Some(meta_service::json(¤t)); + self.events.on_write(&event, &mut *conn).await?; + Ok(()) + } + + /// The `start` move of the `Task` row `id` names (ADR-0066 §2), in ADR-0066 §6's order: load it + /// under a row lock (`not_found`), the permission point (`forbidden`), the state + /// (`invalid_transition`), the guarded update (`invalid_transition`, or + /// `transition_condition_failed` when its condition fails), the event hook. Answers the row + /// written. In one transaction. + pub async fn start_task(&self, actor: Option<&A>, id: i64) -> Result { + let mut tx = self.db.begin().await?; + let out = self.start_task_in(&mut *tx, actor, id).await; + meta_service::finish::(tx, out).await + } + + /// `start_task` on `conn`, inside the caller's transaction. + pub async fn start_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + id: i64, + ) -> Result { + let current = meta_store::get_for_update(&mut *conn, &store::TABLE, id).await?; + let current: Row = current.ok_or(ServiceError::NotFound)?; + let row_json = meta_service::json(¤t); + let seen = (Some(&row_json), None); + let permission = tasks_rules::Permission::TasksTaskStart; + let allowed = self.policy.allows(permission, actor, seen.0, seen.1, &mut *conn); + if !allowed.await? { + return Err(ServiceError::Forbidden); + } + let t = rules::status::Transition::Start; + if !meta_service::in_state(¤t.status, t.from()) { + return Err(ServiceError::InvalidTransition); + } + let condition = None; + let (from, to) = (t.from(), t.to()); + let m = meta_service::Move { field: "status", from, to, condition }; + meta_service::make_move(&mut *conn, &store::TABLE, &id, &m).await?; + let mut event = WriteEvent::new(WriteKind::Transition, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(&id)); + event.operation = Some("startTask"); + event.lifecycle = Some("status"); + event.transition = Some("start"); + event.from = Some(meta_service::state_name(¤t.status)); + event.to = Some(meta_service::state_name(&m.to)); + self.events.on_write(&event, &mut *conn).await?; + let row = store::get(&mut *conn, id).await?; + let row = row.ok_or(ServiceError::NotFound)?; + Ok(row) + } + + /// The `finish` move of the `Task` row `id` names (ADR-0066 §2), in ADR-0066 §6's order: load + /// it under a row lock (`not_found`), the permission point (`forbidden`), the state + /// (`invalid_transition`), the guarded update (`invalid_transition`, or + /// `transition_condition_failed` when its condition fails), the event hook. Answers the row + /// written. In one transaction. + pub async fn finish_task(&self, actor: Option<&A>, id: i64) -> Result { + let mut tx = self.db.begin().await?; + let out = self.finish_task_in(&mut *tx, actor, id).await; + meta_service::finish::(tx, out).await + } + + /// `finish_task` on `conn`, inside the caller's transaction. + pub async fn finish_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + id: i64, + ) -> Result { + let current = meta_store::get_for_update(&mut *conn, &store::TABLE, id).await?; + let current: Row = current.ok_or(ServiceError::NotFound)?; + let row_json = meta_service::json(¤t); + let seen = (Some(&row_json), None); + let permission = tasks_rules::Permission::TasksTaskFinish; + let allowed = self.policy.allows(permission, actor, seen.0, seen.1, &mut *conn); + if !allowed.await? { + return Err(ServiceError::Forbidden); + } + let t = rules::status::Transition::Finish; + if !meta_service::in_state(¤t.status, t.from()) { + return Err(ServiceError::InvalidTransition); + } + let condition = None; + let (from, to) = (t.from(), t.to()); + let m = meta_service::Move { field: "status", from, to, condition }; + meta_service::make_move(&mut *conn, &store::TABLE, &id, &m).await?; + let mut event = WriteEvent::new(WriteKind::Transition, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(&id)); + event.operation = Some("finishTask"); + event.lifecycle = Some("status"); + event.transition = Some("finish"); + event.from = Some(meta_service::state_name(¤t.status)); + event.to = Some(meta_service::state_name(&m.to)); + self.events.on_write(&event, &mut *conn).await?; + let row = store::get(&mut *conn, id).await?; + let row = row.ok_or(ServiceError::NotFound)?; + Ok(row) + } + + /// The `reopen` move of the `Task` row `id` names (ADR-0066 §2), in ADR-0066 §6's order: load + /// it under a row lock (`not_found`), the permission point (`forbidden`), the state + /// (`invalid_transition`), the guarded update (`invalid_transition`, or + /// `transition_condition_failed` when its condition fails), the event hook. Answers the row + /// written. In one transaction. + pub async fn reopen_task(&self, actor: Option<&A>, id: i64) -> Result { + let mut tx = self.db.begin().await?; + let out = self.reopen_task_in(&mut *tx, actor, id).await; + meta_service::finish::(tx, out).await + } + + /// `reopen_task` on `conn`, inside the caller's transaction. + pub async fn reopen_task_in( + &self, + conn: &mut D::Conn, + actor: Option<&A>, + id: i64, + ) -> Result { + let current = meta_store::get_for_update(&mut *conn, &store::TABLE, id).await?; + let current: Row = current.ok_or(ServiceError::NotFound)?; + // It is @public: no permission point. + let t = rules::status::Transition::Reopen; + if !meta_service::in_state(¤t.status, t.from()) { + return Err(ServiceError::InvalidTransition); + } + let condition = None; + let (from, to) = (t.from(), t.to()); + let m = meta_service::Move { field: "status", from, to, condition }; + meta_service::make_move(&mut *conn, &store::TABLE, &id, &m).await?; + let mut event = WriteEvent::new(WriteKind::Transition, actor); + event.entity = Some("Task"); + event.key = Some(meta_service::json(&id)); + event.operation = Some("reopenTask"); + event.lifecycle = Some("status"); + event.transition = Some("reopen"); + event.from = Some(meta_service::state_name(¤t.status)); + event.to = Some(meta_service::state_name(&m.to)); + self.events.on_write(&event, &mut *conn).await?; + let row = store::get(&mut *conn, id).await?; + let row = row.ok_or(ServiceError::NotFound)?; + Ok(row) + } +} diff --git a/examples/rust-service/generated/tasks_store/Cargo.toml b/examples/rust-service/generated/tasks_store/Cargo.toml new file mode 100644 index 0000000000..15d823153b --- /dev/null +++ b/examples/rust-service/generated/tasks_store/Cargo.toml @@ -0,0 +1,11 @@ +# @generated by the MetaObjects repository generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "tasks_store" +version = "0.1.0" +edition = "2021" +publish = false +description = "Data access for the stored entities of the MetaObjects package tasks." + +[dependencies] +meta_store = { path = "../meta_store" } +tasks = { path = "../tasks" } diff --git a/examples/rust-service/generated/tasks_store/rustfmt.toml b/examples/rust-service/generated/tasks_store/rustfmt.toml new file mode 100644 index 0000000000..e2e6d34dcb --- /dev/null +++ b/examples/rust-service/generated/tasks_store/rustfmt.toml @@ -0,0 +1,8 @@ +# @generated by MetaObjects. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +use_small_heuristics = "Max" +short_array_element_width_threshold = 0 +reorder_imports = false +reorder_modules = false diff --git a/examples/rust-service/generated/tasks_store/src/lib.rs b/examples/rust-service/generated/tasks_store/src/lib.rs new file mode 100644 index 0000000000..98dbf2e5d1 --- /dev/null +++ b/examples/rust-service/generated/tasks_store/src/lib.rs @@ -0,0 +1,7 @@ +// @generated by the MetaObjects repository generator. Do not edit: change the model and run `cargo meta gen`. + +//! Data access for the stored entities of the MetaObjects package `tasks`. +//! +//! One module per entity: its `TABLE` and its reads and writes, over any `meta_store::Conn`. + +pub mod task; diff --git a/examples/rust-service/generated/tasks_store/src/task.rs b/examples/rust-service/generated/tasks_store/src/task.rs new file mode 100644 index 0000000000..fb238e98ae --- /dev/null +++ b/examples/rust-service/generated/tasks_store/src/task.rs @@ -0,0 +1,76 @@ +// @generated by the MetaObjects repository generator. Do not edit: change the model and run `cargo meta gen`. + +use meta_store::{Column, Conn, Filter, Kind, Query, StoreError, Table}; + +/// Where `Task` rows are stored: `tasks`. +pub const TABLE: Table = Table { + object: "Task", + schema: None, + name: "tasks", + key: Some("id"), + columns: &[ + Column::new("id", "id", Kind::Long), + Column::new("title", "title", Kind::Text), + Column::new("notes", "notes", Kind::Text), + Column::new("status", "status", Kind::Text), + ], + writable: true, + discriminator: None, + read: None, +}; + +/// The `Task` rows the query selects, in its order and page. +pub async fn list( + c: &mut C, + query: &Query, +) -> Result, StoreError> { + meta_store::list(c, &TABLE, query).await +} + +/// How many rows the filter selects. +pub async fn count( + c: &mut C, + filter: Option<&Filter>, +) -> Result { + meta_store::count(c, &TABLE, filter).await +} + +/// The row whose `id` is `id`, or `None`. +pub async fn get(c: &mut C, id: i64) -> Result, StoreError> { + meta_store::get(c, &TABLE, id).await +} + +/// Inserts the row and reads it back as stored, with what the database filled in. +pub async fn create( + c: &mut C, + body: &tasks::TaskCreate, +) -> Result { + meta_store::create(c, &TABLE, body).await +} + +/// Sets the members the patch carries on the row whose `id` is `id` and reads it back; `None` when +/// there is no such row. +pub async fn update( + c: &mut C, + id: i64, + patch: &tasks::TaskPatch, +) -> Result, StoreError> { + meta_store::update(c, &TABLE, id, patch).await +} + +/// Deletes the row whose `id` is `id`; `false` when there was none. +pub async fn delete(c: &mut C, id: i64) -> Result { + meta_store::delete(c, &TABLE, id).await +} + +/// The guarded update of the lifecycle `status`: moves the row whose `id` is `id` to `to` only +/// while its state is one of `from`, in one statement. `false` when no row matched: it is gone, or +/// another writer moved it first. +pub async fn transition_status( + c: &mut C, + id: i64, + from: &[tasks::TaskStatus], + to: tasks::TaskStatus, +) -> Result { + meta_store::transition(c, &TABLE, id, "status", from, &to, None).await +} diff --git a/examples/rust-service/metaobjects.config.json b/examples/rust-service/metaobjects.config.json new file mode 100644 index 0000000000..927ee0a4e4 --- /dev/null +++ b/examples/rust-service/metaobjects.config.json @@ -0,0 +1,10 @@ +{ + "generators": [ + "entity", + "rules-names", + "contract-types", + "repository", + "service", + "service-routes" + ] +} diff --git a/examples/rust-service/metaobjects/meta.app.yaml b/examples/rust-service/metaobjects/meta.app.yaml new file mode 100644 index 0000000000..27ff64c559 --- /dev/null +++ b/examples/rust-service/metaobjects/meta.app.yaml @@ -0,0 +1,22 @@ +metadata: + package: tasks + children: + - object.entity: + name: Task + description: One piece of work, from the moment it is written down until it is done. + children: + - source.rdb: { table: tasks } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id], generation: increment } + - field.string: { name: title, maxLength: 120, required: true, filterable: true, sortable: true, db.indexed: true } + - field.string: { name: notes, maxLength: 2000 } + - field.enum: + name: status + values: [todo, doing, done] + default: todo + filterable: true + db.indexed: true + children: + - transition.action: { name: start, from: [todo], to: doing } + - transition.action: { name: finish, from: [todo, doing], to: done } + - transition.action: { name: reopen, from: [done], to: todo, public: true } diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 48c1c09173..9bdf7b930f 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -222,6 +222,7 @@ errors, Python error envelopes wrapped as `{"detail": ...}`.) | Java (Spring) | `@RestController` (`codegen-spring`) | `ToolProvider`-compile → embedded Tomcat (`TomcatHost`) over a real socket + in-memory repo behind the generated repo interface | in-memory | | Kotlin (Spring) | `@RestController` (`codegen-kotlin`) | kotlin-compile-testing → embedded Tomcat (`TomcatHost`) over a real socket + in-memory H2 behind the generated `Table` | in-memory | | Python (FastAPI) | `APIRouter` (`router_generator`) | `render_router` → import → `TestClient` + in-memory repo behind the generated DI dependency | in-memory | +| Rust (axum) | the `service-routes` crate over the generated service and `repository` store (`metaobjects-codegen/tests/api_contract.rs`) | `cargo meta gen` → `cargo build` of a probe → axum on a real socket + a raw HTTP client; `core`, `write-through`, `secret-fields`, `list-query` and `rules` only, the rest on the runner's ledger | SQLite in memory | **Why the JVM generated lanes run a real Tomcat.** They used to drive the controller through MockMvc, which hands it a request no servlet container ever built — and three diff --git a/fixtures/api-contract-conformance/list-query/README.md b/fixtures/api-contract-conformance/list-query/README.md index 9571d650e5..2a118e8f61 100644 --- a/fixtures/api-contract-conformance/list-query/README.md +++ b/fixtures/api-contract-conformance/list-query/README.md @@ -51,5 +51,7 @@ answer every scenario by construction. Runners: TypeScript `server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts` (one Postgres container for the file, reseeded before every scenario), and C# `server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs` (the -generated routes on Kestrel against Postgres). Both run every scenario. The other ports' -runners arrive with their 1.3.0 REST-standard work. +generated routes on Kestrel against Postgres), and Rust +`server/rust/metaobjects-codegen/tests/api_contract.rs` (the generated axum routes against +SQLite in memory). All three run every scenario. The other ports' runners arrive with their +1.3.0 REST-standard work. diff --git a/fixtures/api-contract-conformance/rules/README.md b/fixtures/api-contract-conformance/rules/README.md index 99b4c6b56c..6c348ee257 100644 --- a/fixtures/api-contract-conformance/rules/README.md +++ b/fixtures/api-contract-conformance/rules/README.md @@ -74,4 +74,5 @@ framework's own. | Port | Lane | |---|---| | TypeScript | `server/typescript/packages/integration-tests/test/api-contract-rules.test.ts`, both output layouts | +| Rust | `server/rust/metaobjects-codegen/tests/api_contract.rs` sends every scenario over HTTP to the generated `service-routes` crate on SQLite, and each settings variant to its own generated project; `tests/service.rs` runs the same scenarios through the generated service, beneath the transport | | C#, Java, Kotlin, Python | not yet: each port's service generator is its own 1.3.0 work | diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index 153887902a..b5920bc3c8 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -25,13 +25,24 @@ The generators of the rules layers themselves (ADR-0067) are the other exception vocabulary is their job. Each adds only files of its own for `with/`, and moves none of what it writes for `without/`. Today those are TypeScript's `rules-names`, which writes nothing for `without/`, and `contract-types`, whose entity contracts do not depend on the vocabulary and whose -operations module (and the value object only an operation reaches) does. +operations module (and the value object only an operation reaches) does. In Rust, `rules-names` +and `contract-types` write nothing for `without/` and, for `with/`, only files of their own. The +Rust data-access generator (`repository`, ADR-0067 layer 3) writes the same files for both models, +because it stores every entity either way; the vocabulary changes only the file of the entity that +holds the lifecycle, and only by appending that lifecycle's guarded update (`transition_status`) at +its end. The service generators (ADR-0067 layers 4 and 5) are the enforcing shells, so they also CHANGE files they write for `without/`: TypeScript's `service` adds a file per derived transition command and per declared operation and changes the package index (its policy, bodies and interfaces) and the lifecycle entity's create and update (which check its state), and `service-routes` and `service-routes-hono` change their transports (the new routes). The test pins both lists, and every other file stays byte-identical. +The Rust `service` adds the declared operations' file and changes the service crate's manifest +(the rules and contract crates it names), its library (the policy, the bodies and the move types) +and the lifecycle entity's file (its commands and state checks); every other file it writes changes +only in its `impl` header, which gains the policy and bodies type parameters. The Rust +`service-routes` changes only its transport crate's manifest (the rules crate it names) and its +library (the transition and operation routes). A generator that started reading an operation or a transition by accident would emit something half-built; these tests are what notice: @@ -43,7 +54,7 @@ something half-built; these tests are what notice: | Java | `server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java` | | Kotlin | `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt` | | Python | `server/python/tests/test_rules_inert.py` | -| Rust | `server/rust/metaobjects-codegen/tests/rules_inert.rs` (every generator it ships: `entity`, `client`, `commands`) | +| Rust | `server/rust/metaobjects-codegen/tests/rules_inert.rs` (every flat generator it ships; the rules-layer generators are held to adding files only, the data-access generator to appending the guarded update, and the service to its pinned changes) | Regenerate `without/` from `with/` by deleting every `transition.*` child and the `api.operational` node, nothing else. diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index a198d4dc19..b1f75e4e51 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -21,21 +21,21 @@ "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "output-prompt": { "concept": "Per-template output-format prompt fragment generator.", "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "render-helper": { - "concept": "Per-renderable-template render helper (typed render wrappers). BOTH template subtypes render (ADR-0052), so on csharp/java/kotlin/python this covers template.output AND template.prompt; on typescript a prompt's render handle is the separate `prompt-render` generator instead, so typescript's render-helper is template.output only. Same stable name, one concept, one per-port split — stated here because the concept line is shared and the split is not.", + "concept": "Per-renderable-template render helper (typed render wrappers). BOTH template subtypes render (ADR-0052), so on csharp/java/kotlin/python/rust this covers template.output AND template.prompt; on typescript a prompt's render handle is the separate `prompt-render` generator instead, so typescript's render-helper is template.output only. Same stable name, one concept, one per-port split — stated here because the concept line is shared and the split is not.", "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "extractor": { "concept": "Per-template typed extract helper: tolerant recovery of the typed response from dirty model text; throws only when a @required field is lost.", @@ -105,32 +105,32 @@ "ports": ["typescript", "csharp", "kotlin", "python", "java"] }, "rules-names": { - "concept": "Business-rules name constants (ADR-0067 layer 0): each lifecycle's states, initial and terminal states and transitions, the permission each derived command and each operation asks for, and the error codes. A layer generator: it acts on the rules vocabulary, so the codegen-noop rules corpus does not hold it.", + "concept": "Business-rules name constants (ADR-0067 layer 0): each lifecycle's states, initial and terminal states and transitions, the permission each derived command and each operation asks for, and the error codes. A layer generator: it acts on the rules vocabulary, so the codegen-noop rules corpus does not hold it. On rust they are closed enums in a `_rules` crate, which also names each derived command and declared operation.", "tier": "native", "layer": "model", "eject": "full", - "ports": ["typescript", "csharp"] + "ports": ["typescript", "csharp", "rust"] }, "contract-types": { - "concept": "Contract types with no persistence mapping (ADR-0067 layer 1): each store-backed entity's read, create and update shapes, each projection's read shape, each declared operation's input, output and errors, and the wire error bodies. TypeScript writes the whole layer. C# so far writes each entity's create and update records, which leave out the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) and tell an omitted member from an explicit null. The other ports add theirs with their rules-layer work.", + "concept": "Contract types with no persistence mapping (ADR-0067 layer 1): each store-backed entity's read, create and update shapes, each projection's read shape, each declared operation's input, output and errors, and the wire error bodies. TypeScript writes the whole layer. C# so far writes each entity's create and update records, which leave out the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) and tell an omitted member from an explicit null. On rust an entity's read, create and patch shapes are the entity generator's model crate, which carries no persistence mapping, and this generator writes a `_contract` crate per package with a declared operation: each operation's input, output, business errors and error body, the read shape of a returned projection that is not a served read, and the wire error contract. The other ports add theirs with their rules-layer work.", "tier": "native", "layer": "model", "eject": "full", - "ports": ["typescript", "csharp"] + "ports": ["typescript", "csharp", "rust"] }, "service": { - "concept": "The service layer (ADR-0067 layer 4): one module per metadata package, a function per operation, and a factory that binds them to the dependencies passed in. Each store-backed entity gets its derived list, get, create, update and delete; every write runs in one transaction (a savepoint inside a caller's) with the declared write rules (ADR-0045). TypeScript so far, behind its own transport (`service-routes`); the other ports add theirs with their rules-layer work.", + "concept": "The service layer (ADR-0067 layer 4): one module per metadata package, a function per operation, and a factory that binds them to the dependencies passed in. Each store-backed entity gets its derived list, get, create, update and delete; every write runs in one transaction (a savepoint inside a caller's) with the declared write rules (ADR-0045). TypeScript, behind its own transport (`service-routes`), and Rust (over the `repository` store crates, its write running inside a caller's transaction through its `_in` twin); the other ports add theirs with their rules-layer work.", "tier": "native", "layer": "service", "eject": "full", - "ports": ["typescript"] + "ports": ["typescript", "rust"] }, "service-routes": { - "concept": "A thin REST transport over the service layer (ADR-0067 layer 5), one per metadata package: each route parses the request, calls one service operation and sends what it answered, and holds no rules. It answers the shared REST contract as `routes` does. TypeScript (Fastify) so far.", + "concept": "A thin REST transport over the service layer (ADR-0067 layer 5), one per metadata package: each route parses the request, calls one service operation and sends what it answered, and holds no rules. It answers the shared REST contract as `routes` does. TypeScript (Fastify) and Rust (axum, one router per package with an actor extractor; opt-in at `cargo meta init --transport`, because it brings a web framework into the build).", "tier": "native", "layer": "api", "eject": "full", - "ports": ["typescript"] + "ports": ["typescript", "rust"] }, "service-routes-hono": { "concept": "The `service-routes` transport on Hono: the same routes over the service layer (ADR-0067 layer 5), mounted on a Hono app, answering the shared REST contract the same way. TYPESCRIPT ONLY by design, as `routes-hono` is: Hono is a TypeScript framework.", @@ -140,7 +140,7 @@ "ports": ["typescript"] }, "prompt-render": { - "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", + "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", "layer": "capability", "eject": "full", @@ -177,11 +177,11 @@ "ports": ["csharp"] }, "repository": { - "concept": "Per-entity repository seam (Java: Spring Data interface; Kotlin: an open Exposed persistence base with CRUD + patch bodies).", + "concept": "Per-entity repository seam (Java: Spring Data interface; Kotlin: an open Exposed persistence base with CRUD + patch bodies; Rust: a store crate per package over sqlx, with list, count, get, create, update, delete and the guarded lifecycle update).", "tier": "native", "layer": "persistence", "eject": "full", - "ports": ["java", "kotlin"] + "ports": ["java", "kotlin", "rust"] }, "dto": { "concept": "Per-entity Spring DTO.", @@ -609,8 +609,11 @@ "engine": [ "metaobjects_codegen::emitted", "metaobjects_codegen::generator", + "metaobjects_codegen::inbound", + "metaobjects_codegen::layers", "metaobjects_codegen::names", "metaobjects_codegen::plan", + "metaobjects_codegen::render", "metaobjects_codegen::writer" ] } diff --git a/fixtures/list-query-conformance/README.md b/fixtures/list-query-conformance/README.md index 136e585956..7d1f3daa4c 100644 --- a/fixtures/list-query-conformance/README.md +++ b/fixtures/list-query-conformance/README.md @@ -74,3 +74,7 @@ key), so the TypeScript mounts parse with a depth sized to the cap. To regenerate after an intended change, run `UPDATE_LIST_QUERY_FIXTURES=1 bun test test/list-query-conformance.test.ts`, then review every changed answer, because the answers are the cross-port contract. +- C#: `server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs`. +- Rust: `server/rust/metaobjects-codegen/tests/list_query_conformance.rs`, against the parser the + generated `meta_http` crate ships, with the allowlist derived by the `service-routes` generator's + own derivation. diff --git a/fixtures/naming-conformance/README.md b/fixtures/naming-conformance/README.md index 09144db3a2..e009a79841 100644 --- a/fixtures/naming-conformance/README.md +++ b/fixtures/naming-conformance/README.md @@ -138,6 +138,7 @@ checks, and asserts each `shapeOnlyCases` pair is ACCEPTED: | C# | `server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs` (pluralizers + refusal — `CSharpNaming.AssertNoCollectionNameCollisions`, wired into `CodegenRunner.Run`); `server/csharp/MetaObjects.Codegen.Tests/DbContextForeignKeyConfigTests.cs` (the historical Address/Addresses fixture, now an expected-error test at both the unit and `CodegenRunner.Run` integration level) | | Java / Kotlin | `server/java/codegen-base/src/test/java/com/metaobjects/generator/util/RouteNamingTest.java` (pluralizers + refusal — `RouteNaming.assertNoCollectionNameCollisions`, wired into `MetaDataGeneratorMojo#executeGenerators` and the codegen mode of `MetaDataVerifyMojo`; Kotlin inherits both — it runs through the same Maven goals — and `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRouteNamingTest.kt` checks the refusal on models the Kotlin facade loads) | | Python | `server/python/tests/codegen/test_route_path_naming.py` (pluralizers); `server/python/tests/codegen/test_collection_name_collision.py` (refusal — `assert_no_collection_name_collisions`, wired into `run_gen` in `runner.py`) | +| Rust | `server/rust/metaobjects/tests/naming_conformance.rs` (both `cases` columns, the `collisionCases` refusal through `assert_no_collection_name_collisions`, and the `shapeOnlyCases` acceptances) | No HTTP server, no database — this corpus is intentionally a pure function check, unlike `api-contract-conformance` (which is the right place for the diff --git a/fixtures/persistence-conformance/README.md b/fixtures/persistence-conformance/README.md index d57dfdf226..80429c62e5 100644 --- a/fixtures/persistence-conformance/README.md +++ b/fixtures/persistence-conformance/README.md @@ -375,7 +375,8 @@ writes nothing; prove it with a follow-up `op: get` or `op: count`. including one an adopter writes: a NULL operand in a condition matches nothing, as SQL's three-valued logic says. It carries `engines: [postgres, mysql]`, so the Postgres and MySQL runners run it; the MySQL run covers the read-back in the Kysely and Drizzle drivers. The -TypeScript runner drives `ObjectManager.guardedUpdate` there. C#, Java and Kotlin defer it +TypeScript runner drives `ObjectManager.guardedUpdate` there, and the Rust runner the generated +store's `meta_store::transition` on Postgres. C#, Java and Kotlin defer it by name, with the 1.3.0 row that builds each one's guarded update (L-CS-2, L-JV-2, L-KT-2), and run it once that lands. Python defers it by name (L-PY-2). diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index cc286b3465..46b995ea62 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,7 +7,7 @@ format are in [`spec/code-writer.md`](../../spec/code-writer.md). - `cases/*.json` with `"dialect": "core"` pin the language-neutral core: indentation, blocks, blank-line requests, snippets, fit-or-break lists, line endings and the error codes. Every port's writer runs them with the options the case states. -- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`) pin that +- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`, `"rust"`) pin that language's writer: import or `using` collection and ordering, doc comments and its defaults. A runner runs the `core` cases and its own dialect's, and skips the others by name. @@ -16,7 +16,7 @@ Runners: - TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts` (`core` and `typescript`). - Java, `server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java` (`core` and `java`). - Python, `server/python/tests/codegen/test_writer_conformance.py` (`core` and `python`). -- Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core`). +- Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core` and `rust`). - C#, `server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs` (`core` and `csharp`). The ports without a writer yet (Kotlin) run the `core` cases when their writers @@ -25,3 +25,9 @@ land, and add cases for their own dialect beside these. The `csharp` ops are `header` (lines), `using`, `usingStatic` (a namespace or type), `usingAlias` (alias, target) and `docSummary` (lines), beside the core ops. A `csharp` case may state `"options": {"usingOrder": "sorted"}`; the default order is the order the generator named them. + +The `rust` ops are `use` (a path, then the names), `doc` and `prose` (one text each), +`docBreak` and `assign` (a head, then parts), beside the core ops. A `rust` case states no +options and takes the dialect's defaults. Every `rust` case's expected output is unchanged by +`rustfmt` (edition 2021) under the `rustfmt.toml` every generated crate carries +(`RUSTFMT_TOML` in the Rust writer): rustfmt is the oracle, since generated Rust is held to it. diff --git a/fixtures/writer-conformance/cases/rust-assign-breaks.json b/fixtures/writer-conformance/cases/rust-assign-breaks.json new file mode 100644 index 0000000000..1e3b3c4510 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-breaks.json @@ -0,0 +1,34 @@ +{ + "description": "When the right-hand side fits on neither line, `assign` keeps it on the head's line and breaks its last list.", + "dialect": "rust", + "ops": [ + [ + "assign", + "pub static FIELDS: &[PayloadField] =", + [ + "&", + { + "list": { + "open": "[", + "items": [ + "PayloadField::scalar(\"field_number_00\")", + "PayloadField::scalar(\"field_number_01\")", + "PayloadField::scalar(\"field_number_02\")", + "PayloadField::scalar(\"field_number_03\")" + ], + "close": "]" + } + }, + ";" + ] + ] + ], + "expected": [ + "pub static FIELDS: &[PayloadField] = &[", + " PayloadField::scalar(\"field_number_00\"),", + " PayloadField::scalar(\"field_number_01\"),", + " PayloadField::scalar(\"field_number_02\"),", + " PayloadField::scalar(\"field_number_03\"),", + "];" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-assign-fits.json b/fixtures/writer-conformance/cases/rust-assign-fits.json new file mode 100644 index 0000000000..c92368a9c5 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-fits.json @@ -0,0 +1,37 @@ +{ + "description": "`assign` writes `head rhs` on one line when it fits.", + "dialect": "rust", + "ops": [ + [ + "open", + "fn main() {" + ], + [ + "assign", + "let x =", + [ + "f", + { + "list": { + "open": "(", + "items": [ + "a", + "b" + ], + "close": ")" + } + }, + ";" + ] + ], + [ + "close", + "}" + ] + ], + "expected": [ + "fn main() {", + " let x = f(a, b);", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-assign-next-line.json b/fixtures/writer-conformance/cases/rust-assign-next-line.json new file mode 100644 index 0000000000..27946f9c2c --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-next-line.json @@ -0,0 +1,47 @@ +{ + "description": "When `head rhs` does not fit but the right-hand side alone fits one level in, `assign` writes the head and then the right-hand side on the next line, an array as well as a call, as rustfmt does under the generated crates' settings.", + "dialect": "rust", + "ops": [ + [ + "assign", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS_HERE: PayloadField =", + [ + "PayloadField::scalar", + { + "list": { + "open": "(", + "items": [ + "\"first_name\"" + ], + "close": ")" + } + }, + ";" + ] + ], + [ + "assign", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS: &[PayloadField] =", + [ + "&", + { + "list": { + "open": "[", + "items": [ + "PayloadField::scalar(\"first_name\")", + "PayloadField::scalar(\"surname\")" + ], + "close": "]" + } + }, + ";" + ] + ] + ], + "expected": [ + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS_HERE: PayloadField =", + " PayloadField::scalar(\"first_name\");", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS: &[PayloadField] =", + " &[PayloadField::scalar(\"first_name\"), PayloadField::scalar(\"surname\")];" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-defaults.json b/fixtures/writer-conformance/cases/rust-defaults.json new file mode 100644 index 0000000000..55448b16b5 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-defaults.json @@ -0,0 +1,81 @@ +{ + "description": "The Rust dialect indents four spaces, breaks at 100 columns and puts a comma after the last item of a broken list, as rustfmt does.", + "dialect": "rust", + "ops": [ + [ + "open", + "fn main() {" + ], + [ + "line", + "let names = ", + { + "list": { + "open": "vec![", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"", + "\"n14\"", + "\"n15\"", + "\"n16\"", + "\"n17\"", + "\"n18\"", + "\"n19\"", + "\"n20\"", + "\"n21\"", + "\"n22\"", + "\"n23\"" + ], + "close": "]" + } + }, + ";" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "fn main() {", + " let names = vec![", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\",", + " \"n14\",", + " \"n15\",", + " \"n16\",", + " \"n17\",", + " \"n18\",", + " \"n19\",", + " \"n20\",", + " \"n21\",", + " \"n22\",", + " \"n23\",", + " ];", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json b/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json new file mode 100644 index 0000000000..d94e97be37 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json @@ -0,0 +1,20 @@ +{ + "description": "`doc` writes an author's text as `///` lines, one per line of the text, a bare `///` for an empty line and never re-wrapped; the text's own leading and trailing blank lines are dropped.", + "dialect": "rust", + "ops": [ + [ + "doc", + "\nThe customer.\n\nSee the billing guide for how a customer is charged, which is a long sentence an author wrote on one line.\n" + ], + [ + "line", + "pub struct Customer;" + ] + ], + "expected": [ + "/// The customer.", + "///", + "/// See the billing guide for how a customer is charged, which is a long sentence an author wrote on one line.", + "pub struct Customer;" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-prose-wraps.json b/fixtures/writer-conformance/cases/rust-prose-wraps.json new file mode 100644 index 0000000000..12a134e8d1 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-prose-wraps.json @@ -0,0 +1,38 @@ +{ + "description": "`prose` writes generated text as `///` lines wrapped at a word boundary so no line passes the width; each line of the text is its own paragraph, and `docBreak` writes the bare `///` between two paragraphs.", + "dialect": "rust", + "ops": [ + [ + "open", + "impl A {" + ], + [ + "prose", + "Parse a reply to the prompt that is exactly the JSON of the response type, with nothing around it at all." + ], + [ + "docBreak" + ], + [ + "prose", + "# Errors" + ], + [ + "line", + "fn f() {}" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "impl A {", + " /// Parse a reply to the prompt that is exactly the JSON of the response type, with nothing", + " /// around it at all.", + " ///", + " /// # Errors", + " fn f() {}", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-use-fills.json b/fixtures/writer-conformance/cases/rust-use-fills.json new file mode 100644 index 0000000000..d355473f67 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-use-fills.json @@ -0,0 +1,30 @@ +{ + "description": "A `use` past 100 columns breaks after the brace and fills the names onto lines one level in, each followed by a comma, as many to a line as fit, then `};` on its own line.", + "dialect": "rust", + "ops": [ + [ + "use", + "metaobjects_render::extract", + "Name00", + "Name01", + "Name02", + "Name03", + "Name04", + "Name05", + "Name06", + "Name07", + "Name08", + "Name09", + "Name10", + "Name11", + "Name12", + "Name13" + ] + ], + "expected": [ + "use metaobjects_render::extract::{", + " Name00, Name01, Name02, Name03, Name04, Name05, Name06, Name07, Name08, Name09, Name10, Name11,", + " Name12, Name13,", + "};" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-use-fits.json b/fixtures/writer-conformance/cases/rust-use-fits.json new file mode 100644 index 0000000000..e494212fb8 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-use-fits.json @@ -0,0 +1,21 @@ +{ + "description": "A `use` of several names that fits is one line with the names in braces; a `use` of one name has no braces.", + "dialect": "rust", + "ops": [ + [ + "use", + "serde", + "Serialize" + ], + [ + "use", + "std::collections", + "BTreeMap", + "HashMap" + ] + ], + "expected": [ + "use serde::Serialize;", + "use std::collections::{BTreeMap, HashMap};" + ] +} diff --git a/scripts/ci-lane-map.txt b/scripts/ci-lane-map.txt index 646376b84d..0fdd75213d 100644 --- a/scripts/ci-lane-map.txt +++ b/scripts/ci-lane-map.txt @@ -38,6 +38,7 @@ packs/* | packs | an independent pack (ADR-0069): its own lane only under --affected (the hosted workflows select by port, where packs/ is ts); core never reads packs/ (scripts/check-pack-boundary.ts) server/typescript/* | ts-fast ts-unit packs | the TypeScript server port; packs runs too, as a canary that reports a pack the change breaks and blocks nothing (ADR-0069) examples/dynamic-grid/* | ts-fast ts-unit | a workspace member: ts-fast typechecks it, ts-unit runs its suite, and no other port reads it +examples/rust-service/* | rust | the Rust service example: the rust lane verifies its generated crates and runs its test client/web/* | ts-fast ts-unit packs | the universal web client, built and tested by the TypeScript lanes; packs as for server/typescript server/java/* | java-slow | the Java and Kotlin ports (the reactor holds both conformance suites) server/python/* | python | the Python port diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index ebb7162745..961e8b5f78 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -599,7 +599,7 @@ gate_site_reference() { bun_install && bun scripts/build-site-reference.ts --che # exercised) are the ones worth a test at all. See scripts/maven-coordinate.mjs. # And the publish workflows' tag check (scripts/check-release-tag.mjs), whose test also reads # each real manifest, so a layout change fails here rather than on a release tag. -gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && bash tools/prerelease/test-prerelease-link.sh && bash tools/prerelease/test-estate-run.sh; } +gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && node scripts/test-rust-release.mjs && bash tools/prerelease/test-prerelease-link.sh && bash tools/prerelease/test-estate-run.sh; } # ── repo-root scripts/ typechecks ───────────────────────────────────────────── # `bun test` transpiles per file and never typechecks, and `bun run @@ -968,7 +968,17 @@ gate_conf_rust() { && cargo test --locked -q -- --nocapture \ && gate_rust_load_bench \ && gate_rust_gen_bench \ - && gate_rust_publish_dry_run ) + && gate_rust_publish_dry_run ) \ + && gate_rust_example +} +# The worked service example (examples/rust-service/): its committed generated crates must be +# what `cargo meta gen` writes now (a forced verify, which renders), and its app's HTTP test runs +# over them. Built into server/rust/target/, this checkout's own. +gate_rust_example() { + ( cd server/rust \ + && cargo run --locked -q -p metaobjects-cli --bin cargo-meta -- meta verify --full --project ../../examples/rust-service ) \ + && CARGO_TARGET_DIR="$PWD/server/rust/target/examples" \ + cargo test --locked -q --manifest-path examples/rust-service/Cargo.toml } # 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 diff --git a/scripts/eject-release-gate.test.ts b/scripts/eject-release-gate.test.ts index 19fd66e5af..42d31b2cf8 100644 --- a/scripts/eject-release-gate.test.ts +++ b/scripts/eject-release-gate.test.ts @@ -104,7 +104,7 @@ describe("eject release gate — the command and its wiring", () => { // check after it is the branch check, so a fixture on another branch tells the two apart: // a refused version stops before "not on main", and an allowed one reaches it. test("release.mjs asks the gate first in its preflight, and stops on a refusal", () => { - const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "lib/changelog-fragments.mjs", "lib/release-branch.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; + const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "lib/changelog-fragments.mjs", "lib/release-branch.mjs", "lib/rust-release.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; const onBranch = (pending: (typeof ENTRY)[]) => { const root = repoWith(JSON.stringify(manifest(pending)), RELEASE_SCRIPTS); const git = (...args: string[]) => spawnSync("git", ["-C", root, ...args], { encoding: "utf8" }); diff --git a/scripts/lib/rust-release.mjs b/scripts/lib/rust-release.mjs new file mode 100644 index 0000000000..8776bcc1f9 --- /dev/null +++ b/scripts/lib/rust-release.mjs @@ -0,0 +1,194 @@ +// The Rust crates' part of a release (ADR-0065 Amendment 3): whether this cut publishes them, +// in what order, and the version edit that puts them on the shared line. +// +// Pure functions, so `scripts/test-rust-release.mjs` can hold every rule to cases; +// `scripts/release.mjs` supplies what git, cargo and crates.io answer. +// +// The rules are the ones every registry already follows (docs/RELEASING.md): +// +// - Publish what changed. The crates publish only when a file they ship changed since the last +// `rust-v` tag, and adopt the shared version when they do, skipping the numbers they +// sat out. With no such tag the crates have never shipped, so the cut publishes them. +// - A change to `expected-registry.json` (the vocabulary every port byte-matches) publishes +// every registry, the crates included, changed file or not. +// - The crates publish in dependency order, each after the crates it depends on, because +// crates.io refuses a crate whose dependency is not yet there. + +/** + * The part of `cargo metadata --format-version 1 --no-deps` the publish order reads. + * + * @typedef {{ + * workspace_members?: string[], + * packages: { + * id: string, + * name: string, + * publish?: string[] | null, + * dependencies: {name: string, kind?: string | null}[], + * }[], + * }} CargoMetadata + */ + +/** The workspace that holds the crates, relative to the repository root. */ +export const RUST_DIR = "server/rust"; + +/** The tag a release cuts for the crates: `rust-v1.3.0`. */ +export const RUST_TAG_PREFIX = "rust-v"; + +/** The manifest whose change makes every registry publish. */ +export const EXPECTED_REGISTRY = "fixtures/registry-conformance/expected-registry.json"; + +/** What a crate directory holds that is not shipped in it: tests, examples, benches, baselines. */ +const NOT_SHIPPED = new Set(["tests", "examples", "benches", "baselines"]); + +/** + * Whether a repository path is part of what the Rust crates ship: a crate's sources, build + * script, data, manifest, README or licence, or the workspace manifest and lockfile. A + * crate's tests, examples, benches and benchmark baselines are not. + * + * @param {string} path + * @returns {boolean} + */ +export function isRustProductPath(path) { + const prefix = `${RUST_DIR}/`; + if (!path.startsWith(prefix)) return false; + const parts = path.slice(prefix.length).split("/"); + if (parts.length === 1) return parts[0] === "Cargo.toml" || parts[0] === "Cargo.lock"; + return !NOT_SHIPPED.has(parts[1] ?? ""); +} + +/** + * `1.3.0` or `1.3.0-rc.2` as numbers to compare: a final release sorts after its candidates. + * + * @param {string} v + * @returns {number[] | null} + */ +function versionKey(v) { + const m = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-rc\.(\d+))?$/); + if (!m) return null; + return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? Infinity : Number(m[4])]; +} + +/** + * @param {number[]} a + * @param {number[]} b + * @returns {number} + */ +function compareKeys(a, b) { + for (let i = 0; i < 4; i++) { + const x = a[i] ?? 0; + const y = b[i] ?? 0; + if (x !== y) return x < y ? -1 : 1; + } + return 0; +} + +/** + * The newest `rust-v*` tag among `tags`, or null when the crates have never been tagged. + * + * @param {string[]} tags + * @returns {string | null} + */ +export function newestRustTag(tags) { + /** @type {{tag: string, key: number[]} | null} */ + let best = null; + for (const t of tags) { + if (!t.startsWith(RUST_TAG_PREFIX)) continue; + const key = versionKey(t.slice(RUST_TAG_PREFIX.length)); + if (key && (best === null || compareKeys(key, best.key) > 0)) best = { tag: t, key }; + } + return best?.tag ?? null; +} + +/** + * Whether this cut publishes the crates. + * + * @param {{lastTag: string|null, changedPaths: string[], mode?: "auto"|"publish"|"skip"}} input + * `changedPaths` are the repository paths changed since `lastTag` (ignored without one); + * `mode` is the release's `--crates` choice, `auto` unless the person cutting it overrode. + * @returns {{publish: boolean, reason: string}} + */ +export function rustPublishDecision({ lastTag, changedPaths, mode = "auto" }) { + if (mode === "publish") return { publish: true, reason: "--crates=publish" }; + if (mode === "skip") return { publish: false, reason: "--crates=skip" }; + if (mode !== "auto") throw new Error(`unknown --crates mode "${mode}" (auto, publish or skip)`); + if (lastTag === null) return { publish: true, reason: "the crates have never been published" }; + if (changedPaths.includes(EXPECTED_REGISTRY)) { + return { publish: true, reason: `${EXPECTED_REGISTRY} changed since ${lastTag}, which publishes every registry` }; + } + const shipped = changedPaths.filter(isRustProductPath); + if (shipped.length > 0) { + const more = shipped.length > 3 ? ` and ${shipped.length - 3} more` : ""; + return { publish: true, reason: `changed since ${lastTag}: ${shipped.slice(0, 3).join(", ")}${more}` }; + } + return { publish: false, reason: `no file the crates ship changed since ${lastTag}` }; +} + +/** + * The publishable workspace crates in the order they must publish: each after every crate it + * depends on. `metadata` is what `cargo metadata --format-version 1 --no-deps` prints. A + * dev-dependency does not order anything: cargo leaves one without a version out of the + * published manifest, and one with a version needs only to exist by the time someone runs + * the crate's tests. Ties break on the name, so the order is the same on every machine. + * + * @param {CargoMetadata} metadata + * @returns {string[]} + * @throws when the crates depend on each other in a cycle. + */ +export function rustPublishOrder(metadata) { + const members = new Set(metadata.workspace_members ?? []); + const crates = metadata.packages.filter( + (p) => (members.size === 0 || members.has(p.id)) && !(Array.isArray(p.publish) && p.publish.length === 0), + ); + const names = new Set(crates.map((p) => p.name)); + const needs = new Map(crates.map((p) => [p.name, new Set( + p.dependencies + .filter((d) => d.kind !== "dev" && names.has(d.name) && d.name !== p.name) + .map((d) => d.name), + )])); + /** @type {string[]} */ + const order = []; + while (needs.size > 0) { + const ready = [...needs].filter(([, deps]) => [...deps].every((d) => !needs.has(d))).map(([n]) => n).sort(); + if (ready.length === 0) { + throw new Error(`the Rust crates depend on each other in a cycle: ${[...needs.keys()].sort().join(", ")}`); + } + for (const n of ready) { order.push(n); needs.delete(n); } + } + return order; +} + +/** + * A crate manifest with every version the release sets moved to `version`: the + * `[workspace.package]` version, and the version requirement on each dependency given by + * `path` (a sibling crate). Nothing else in the text changes. + * + * @param {string} text + * @param {string} version + * @returns {string} + */ +export function bumpRustManifest(text, version) { + let out = ""; + let section = ""; + for (const line of text.split(/(?<=\n)/)) { + const header = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (header) section = (header[1] ?? "").trim(); + let next = line; + if (section === "workspace.package") next = next.replace(/^(\s*version\s*=\s*")[^"]*(")/, `$1${version}$2`); + if (/\bpath\s*=/.test(next)) next = next.replace(/(\bversion\s*=\s*")[^"]*(")/, `$1${version}$2`); + out += next; + } + return out; +} + +/** + * Whether crates.io already holds `version` of a crate, from the JSON its + * `/api/v1/crates/` endpoint answers. A crate that does not exist answers 404, which + * the caller reads as free before calling this. + * + * @param {{versions?: {num: string}[]}} json + * @param {string} version + * @returns {boolean} + */ +export function crateVersionTaken(json, version) { + return (json.versions ?? []).some((v) => v.num === version); +} diff --git a/scripts/release.mjs b/scripts/release.mjs index e6123f1c33..34d4efee67 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -1,10 +1,16 @@ #!/usr/bin/env bun -// One-command lockstep release of the @metaobjectsdev/* npm packages. +// One-command lockstep release of the @metaobjectsdev/* npm packages, and of the Rust crates +// when they have changed (ADR-0065 Amendment 3). // // bun run release # do it (stops for confirm before publish) // bun run release --dry-run # everything except publish/tag/push // bun run release --yes # skip the interactive confirm (CI) // bun run release --preflight-only # run PHASE 0 and stop +// bun run release --crates=publish|skip # override whether the crates ship +// +// The Rust crates publish to crates.io behind the same confirm, after npm, in dependency +// order, when a file they ship changed since the last `rust-v*` tag (or they never shipped, +// or expected-registry.json moved). scripts/lib/rust-release.mjs holds those rules. // // --preflight-only is NOT --dry-run. --dry-run still runs Phase 1, which writes the // new version into every package.json of the lockstep set, rebuilds, and regenerates bun.lock — @@ -33,6 +39,10 @@ import { FRAGMENT_DIR, assembleChangelog, fragmentProblems, readFragments } from import { createInterface } from "node:readline/promises"; import { publishSet } from "./publish-set.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; +import { + RUST_DIR, RUST_TAG_PREFIX, bumpRustManifest, crateVersionTaken, newestRustTag, rustPublishDecision, + rustPublishOrder, +} from "./lib/rust-release.mjs"; import { ejectReleaseRefusalAt } from "./eject-release-gate.mjs"; import { releaseBranchRefusal, newestNpmReleaseTag, latestRegressionRefusal, unmergedMaintenanceRefusal, @@ -42,6 +52,7 @@ const VERSION = process.argv[2]; const DRY = process.argv.includes("--dry-run"); const PREFLIGHT_ONLY = process.argv.includes("--preflight-only"); const YES = process.argv.includes("--yes"); +const CRATES_MODE = process.argv.find((a) => a.startsWith("--crates="))?.slice("--crates=".length) ?? "auto"; // A scratch root for the post-publish smoke that no stray node_modules can shadow. // See PHASE 11. Kept beside the other helpers so the reason travels with the call. @@ -186,6 +197,50 @@ if (taken.length) ok(`preflight: on ${branch}, synced, ${VERSION} free on all ${set.length} packages`); ok(`lockstep set @ ${current}: ${set.length} packages → ${VERSION}`); +// --- the Rust crates: do they ship this cut, and can they? ----------------- +// Decided here, with npm's checks, for the same reason: everything after the version bump is +// committed and pushed before the first publish, so a dead token or a taken number found at +// the publish step strands the release half-shipped. +const rustTag = newestRustTag(out("git tag -l").split("\n")); +let rust; +try { + rust = rustPublishDecision({ + lastTag: rustTag, + changedPaths: rustTag ? out(`git diff --name-only ${rustTag} HEAD`).split("\n").filter(Boolean) : [], + mode: CRATES_MODE, + }); +} catch (e) { die(e.message); } +let crates = []; +if (!rust.publish) { + ok(`crates.io: sits this release out (${rust.reason})`); +} else { + crates = rustPublishOrder(JSON.parse(out(`cd ${RUST_DIR} && cargo metadata --format-version 1 --no-deps --locked`))); + // cargo reads a token from CARGO_REGISTRY_TOKEN or from the file `cargo login` writes. + const cargoHome = process.env.CARGO_HOME ?? join(homedir(), ".cargo"); + const credentials = ["credentials.toml", "credentials"].map((f) => join(cargoHome, f)).find(existsSync); + if (!process.env.CARGO_REGISTRY_TOKEN && !(credentials && /\btoken\s*=/.test(readFileSync(credentials, "utf8")))) { + die("crates.io has no token: publishing the crates would fail after the version bump is\n" + + " already committed. Run `cargo login` with a crates.io API token that has the\n" + + " publish-update scope (and publish-new for a crate's first release), or set\n" + + " CARGO_REGISTRY_TOKEN. Pass --crates=skip to cut without the crates."); + } + // crates.io asks automated clients to name themselves in the User-Agent. + const agent = { "user-agent": "metaobjects-release (https://github.com/metaobjectsdev/metaobjects)" }; + const takenCrates = (await Promise.all(crates.map(async (name) => { + try { + const r = await fetch(`https://crates.io/api/v1/crates/${name}`, { headers: agent, signal: AbortSignal.timeout(15_000) }); + if (r.status === 404) return null; // never published = free + if (!r.ok) die(`crates.io answered HTTP ${r.status} for ${name} — cannot verify ${VERSION} is free`); + return crateVersionTaken(await r.json(), VERSION) ? name : null; + } catch { die(`could not reach crates.io to verify ${VERSION} is free (${name})`); } + }))).filter(Boolean); + if (takenCrates.length) { + die(`${VERSION} is already published on crates.io for:\n ${takenCrates.join("\n ")}\n` + + "crates.io versions are permanent (a yank does not free the number) — pick the next free version."); + } + ok(`crates.io: ${crates.length} crates ship (${rust.reason}); ${VERSION} free on all of them`); +} + // The showcase corpus is what metaobjects.dev publishes as "real `meta gen` output", // so a stale tree is a stale claim on a public page. Checked BEFORE the version bump, // which is committed and pushed long before the first publish. @@ -242,6 +297,17 @@ for (const p of set) { writeFileSync(join(p.dir, "package.json"), JSON.stringify(p.pkg, null, 2) + "\n"); } ok(`bumped ${set.length} package.json → ${VERSION}`); +const rustManifests = []; +if (rust.publish) { + const members = JSON.parse(out(`cd ${RUST_DIR} && cargo metadata --format-version 1 --no-deps --locked`)) + .packages.map((p) => p.manifest_path); + for (const manifest of [join(RUST_DIR, "Cargo.toml"), ...members]) { + writeFileSync(manifest, bumpRustManifest(readFileSync(manifest, "utf8"), VERSION)); + rustManifests.push(manifest); + } + sh(`cd ${RUST_DIR} && cargo update --workspace --offline`, { quiet: true }); + ok(`bumped the Rust workspace → ${VERSION} (${rustManifests.length} manifests, Cargo.lock)`); +} // --- PHASE 2+3: clean build + relock -------------------------------------- sh("bun run clean", { quiet: true }); @@ -260,6 +326,15 @@ const bad = Object.entries(pj.dependencies || {}).filter(([k, v]) => k.startsWit if (bad.length) die(`packed cli pins stale/workspace sibling deps: ${JSON.stringify(bad)}`); ok(`packed deps verified: all @metaobjectsdev/* pinned to ${VERSION}`); +// --- pack-verify the crates: each packages and builds from its own tarball ------- +// `--workspace` resolves the sibling crates from the tarballs it just made, so a crate that +// would only build against a path in this checkout fails here, not on crates.io. +// `--allow-dirty` because the version bump above is not committed yet. +if (rust.publish) { + sh(`cd ${RUST_DIR} && cargo publish --dry-run --workspace --locked --allow-dirty`, { quiet: true }); + ok(`crates pack-verified: ${crates.join(", ")} @ ${VERSION}`); +} + // --- write the changelog computed in Phase 0 ----------------------------------------- // One file per change (scripts/lib/changelog-fragments.mjs): the fragments became ordinary // [Unreleased] entries in `assembled`, and the files go, so the release commit carries one @@ -292,6 +367,9 @@ ok("site payload regenerated for the new version"); // --- PHASE 6: STOP — confirm before the irreversible publish -------------- console.log(`\n\x1b[1mReady to publish ${VERSION} to npm \`latest\` (IRREVERSIBLE).\x1b[0m`); console.log(` packages: ${set.length} | packed deps: pinned | build: clean`); +console.log(rust.publish + ? ` and ${crates.length} crates to crates.io (IRREVERSIBLE): ${crates.join(", ")}` + : ` crates.io: none (${rust.reason})`); if (DRY) { ok("dry run — stopping before commit/publish/tag (no changes published)"); process.exit(0); } if (!YES) { const rl = createInterface({ input: process.stdin, output: process.stdout }); @@ -302,6 +380,7 @@ if (!YES) { // --- commit the release --------------------------------------------------- sh(`git add -A server/typescript/packages/*/package.json client/web/packages/*/package.json bun.lock CHANGELOG.md ${FRAGMENT_DIR} examples/showcase/site-payload.json`); +if (rust.publish) sh(`git add ${[...rustManifests, join(RUST_DIR, "Cargo.lock")].join(" ")}`); sh(`git commit -q -m "chore(release): @metaobjectsdev TypeScript packages ${VERSION}"`); ok("committed"); @@ -312,6 +391,15 @@ for (const pkg of ordered) { ok(`published ${pkg.short}@${VERSION}`); } +// --- PHASE 7b: the crates, in dependency order ------------------------------ +// After npm, so a dead npm token (the likelier failure) stops the cut before anything on +// crates.io is permanent. cargo waits for each crate to appear in the index before it +// returns, so the next crate can resolve it. +for (const name of crates) { + sh(`cd ${RUST_DIR} && cargo publish -p ${name} --locked`, { quiet: true }); + ok(`published ${name}@${VERSION} to crates.io`); +} + // --- PHASE 8: push (the tag is NOT cut here) ------------------------------- // This script publishes npm, which is one of FOUR registries. The PyPI/NuGet/Maven // version bump is a separate, later commit — so at this point the branch states the new npm @@ -343,10 +431,11 @@ const v = out(`cd ${sm} && ./node_modules/.bin/meta --version`); if (!v.includes(VERSION)) die(`smoke FAILED: clean install reports ${v}, expected ${VERSION}`); ok(`smoke: clean external install → meta --version = ${v}`); -console.log(`\n\x1b[32m\x1b[1m✅ ${VERSION} is live on npm latest.\x1b[0m`); +console.log(`\n\x1b[32m\x1b[1m✅ ${VERSION} is live on npm latest${rust.publish ? " and crates.io" : ""}.\x1b[0m`); console.log(`\n\x1b[1mNOT DONE — v${VERSION} is not tagged yet, by design.\x1b[0m`); console.log(` 1. Bump PyPI/NuGet/Maven, run \`bun run site:payload\`, commit, push.`); -console.log(` 2. Tag the ports: python-v${VERSION}, csharp-v${VERSION}, java-v${mavenVersion(VERSION)}.`); +console.log(` 2. Tag the ports: python-v${VERSION}, csharp-v${VERSION}, java-v${mavenVersion(VERSION)}` + + (rust.publish ? `, ${RUST_TAG_PREFIX}${VERSION}.` : ".")); console.log(` 3. \`bun scripts/finish-release.mjs ${VERSION}\` — gates the coordinates, then cuts v${VERSION}.`); console.log(` The website pins to v${VERSION}, so tagging before step 1 publishes three stale versions.`); console.log(` Docs version refs are NOT auto-bumped (low-value churn for a patch); batch them when convenient.`); diff --git a/scripts/test-rust-release.mjs b/scripts/test-rust-release.mjs new file mode 100644 index 0000000000..c960982816 --- /dev/null +++ b/scripts/test-rust-release.mjs @@ -0,0 +1,116 @@ +#!/usr/bin/env node +// Tests for scripts/lib/rust-release.mjs — whether a release publishes the Rust crates, in +// what order, and the version edit that puts them on the shared line. +// +// node scripts/test-rust-release.mjs +// +// The oracles are the release rules in docs/RELEASING.md (publish what changed; a change to +// expected-registry.json publishes every registry) and crates.io's own: a crate publishes +// after its dependencies, and a version once taken is taken. + +import { + isRustProductPath, newestRustTag, rustPublishDecision, rustPublishOrder, bumpRustManifest, + crateVersionTaken, EXPECTED_REGISTRY, +} from "./lib/rust-release.mjs"; + +let fails = 0; +const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); +const throws = (fn) => { try { fn(); return false; } catch { return true; } }; + +// What the crates ship. +check(isRustProductPath("server/rust/metaobjects/src/loader.rs"), "a crate's source is shipped"); +check(isRustProductPath("server/rust/metaobjects/data/library/iam/meta.iam.yaml"), "a crate's embedded data is shipped"); +check(isRustProductPath("server/rust/metaobjects-codegen/build.rs"), "a build script is shipped"); +check(isRustProductPath("server/rust/metaobjects-cli/Cargo.toml"), "a crate manifest is shipped"); +check(isRustProductPath("server/rust/Cargo.toml"), "the workspace manifest is shipped (it sets every crate's version)"); +check(isRustProductPath("server/rust/Cargo.lock"), "the lockfile is shipped (the binary is built from it)"); +check(!isRustProductPath("server/rust/metaobjects-codegen/tests/compile.rs"), "a crate's tests are not shipped"); +check(!isRustProductPath("server/rust/metaobjects/examples/load_bench.rs"), "a crate's examples are not shipped"); +check(!isRustProductPath("server/rust/metaobjects/baselines/load.json"), "benchmark baselines are not shipped"); +check(!isRustProductPath("server/rust/rustfmt.toml"), "a workspace file other than the manifest and lock is not shipped"); +check(!isRustProductPath("server/rustacean/src/x.rs"), "a sibling directory that merely starts with the name is not the workspace"); +check(!isRustProductPath("docs/ports/rust.md"), "the port's docs are not shipped"); + +// The newest tag. +check(newestRustTag([]) === null, "no tag: the crates never shipped"); +check(newestRustTag(["v1.3.0", "python-v1.3.0"]) === null, "other ports' tags are not the crates'"); +check(newestRustTag(["rust-v1.3.0", "rust-v1.10.0", "rust-v1.9.2"]) === "rust-v1.10.0", "versions compare as numbers, not text"); +check(newestRustTag(["rust-v1.3.0-rc.2", "rust-v1.3.0"]) === "rust-v1.3.0", "a final release is newer than its candidates"); +check(newestRustTag(["rust-v1.3.0-rc.2", "rust-v1.3.0-rc.10"]) === "rust-v1.3.0-rc.10", "candidates compare by number"); +check(newestRustTag(["rust-vnext", "rust-v1.3.0"]) === "rust-v1.3.0", "a tag that is not a version is ignored"); + +// Whether the cut publishes. +const decide = (lastTag, changedPaths, mode) => rustPublishDecision({ lastTag, changedPaths, mode }); +check(decide(null, []).publish, "never published: the first cut publishes, changed or not"); +check(!decide("rust-v1.3.0", ["docs/ports/rust.md", "server/rust/metaobjects/tests/x.rs"]).publish, + "only docs and tests changed: the crates sit the release out"); +check(decide("rust-v1.3.0", ["server/rust/metaobjects-render/src/render.rs"]).publish, "a shipped file changed: publish"); +check(decide("rust-v1.3.0", [EXPECTED_REGISTRY]).publish, "expected-registry.json changed: every registry publishes"); +check(decide("rust-v1.3.0", ["server/rust/metaobjects/src/a.rs"]).reason.includes("server/rust/metaobjects/src/a.rs"), + "the reason names the file that changed"); +check(decide("rust-v1.3.0", []).reason.includes("rust-v1.3.0"), "a skip names the tag it compared against"); +check(decide(null, [], "skip").publish === false, "--crates=skip overrides a first publish"); +check(decide("rust-v1.3.0", [], "publish").publish, "--crates=publish overrides an unchanged tree"); +check(throws(() => decide(null, [], "maybe")), "an unknown --crates mode is refused, not read as auto"); + +// The publish order, from what `cargo metadata --no-deps` prints. +const pkg = (name, deps, extra = {}) => ({ + id: `path+file:///ws/${name}#${name}@1.3.0`, name, + dependencies: deps.map(([n, kind]) => ({ name: n, kind: kind ?? null })), ...extra, +}); +const meta = (packages) => ({ packages, workspace_members: packages.map((p) => p.id) }); +const workspace = meta([ + pkg("metaobjects-cli", [["metaobjects"], ["metaobjects-codegen"], ["clap"]]), + pkg("metaobjects-codegen", [["metaobjects"], ["metaobjects-render"], ["serde"]]), + pkg("metaobjects-render", [["mustache-ng"], ["serde_json"]]), + pkg("metaobjects", [["serde_json"], ["indexmap"]]), +]); +check(JSON.stringify(rustPublishOrder(workspace)) + === JSON.stringify(["metaobjects", "metaobjects-render", "metaobjects-codegen", "metaobjects-cli"]), + "each crate after the crates it depends on, ties by name"); +check(JSON.stringify(rustPublishOrder(meta([pkg("b", []), pkg("a", [["b", "dev"]])]))) === JSON.stringify(["a", "b"]), + "a dev-dependency does not order anything"); +check(JSON.stringify(rustPublishOrder(meta([pkg("a", []), pkg("x", [], { publish: [] })]))) === JSON.stringify(["a"]), + "a crate marked publish = false is left out"); +check(JSON.stringify(rustPublishOrder(meta([pkg("a", [["b", "build"]]), pkg("b", [])]))) === JSON.stringify(["b", "a"]), + "a build-dependency orders like a normal one"); +check(throws(() => rustPublishOrder(meta([pkg("a", [["b"]]), pkg("b", [["a"]])]))), "a cycle is refused"); + +// The version edit. +const root = `[workspace] +members = ["metaobjects"] + +[workspace.package] +version = "1.2.0" +edition = "2024" + +[workspace.dependencies] +serde = { version = "1.0" } +`; +const bumpedRoot = bumpRustManifest(root, "1.3.0"); +check(bumpedRoot.includes('[workspace.package]\nversion = "1.3.0"'), "the workspace version moves"); +check(bumpedRoot.includes('serde = { version = "1.0" }'), "a registry dependency's requirement does not"); +check(bumpedRoot.replace('version = "1.3.0"', 'version = "1.2.0"') === root, "nothing else changes"); +const member = `[package] +name = "metaobjects-cli" +version.workspace = true + +[dependencies] +metaobjects = { path = "../metaobjects", version = "1.2.0" } +metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.2.0" } +clap = { version = "4.5", features = ["derive"] } +`; +const bumpedMember = bumpRustManifest(member, "1.3.0-rc.1"); +check(bumpedMember.includes('metaobjects = { path = "../metaobjects", version = "1.3.0-rc.1" }') + && bumpedMember.includes('metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.3.0-rc.1" }'), + "each sibling crate's requirement moves"); +check(bumpedMember.includes('clap = { version = "4.5", features = ["derive"] }'), "a registry dependency is left alone"); +check(bumpedMember.includes("version.workspace = true"), "an inherited version stays inherited"); + +// What crates.io answers. +check(crateVersionTaken({ versions: [{ num: "1.3.0" }, { num: "1.2.0" }] }, "1.3.0"), "a published version is taken"); +check(!crateVersionTaken({ versions: [{ num: "1.3.0-rc.1" }] }, "1.3.0"), "a candidate does not take the final number"); +check(!crateVersionTaken({}, "1.3.0"), "an answer with no versions takes nothing"); + +if (fails) { console.error(`\n${fails} failing`); process.exit(1); } +console.log("\nall rust-release checks pass"); diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 9a9c532e27..05e3eda173 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -100,7 +100,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metaobjects" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "saphyr", @@ -109,7 +109,7 @@ dependencies = [ [[package]] name = "metaobjects-cli" -version = "0.1.0" +version = "1.3.0" dependencies = [ "metaobjects", "metaobjects-codegen", @@ -119,17 +119,21 @@ dependencies = [ [[package]] name = "metaobjects-codegen" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "metaobjects", + "metaobjects-render", + "proc-macro2", + "saphyr", "serde", "serde_json", + "syn", ] [[package]] name = "metaobjects-render" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "mustache-ng", @@ -231,6 +235,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index 56356073ea..0bdd5cc062 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -1,18 +1,18 @@ # 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. # -# Four crates: +# Four crates, on the version line every port shares (`scripts/release.mjs` publishes them): # `metaobjects` metamodel registry, loader, canonical serializer. -# `metaobjects-codegen` the run engine (skip key, hash manifest, writer) and the -# `entity` generator. -# `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. # `metaobjects-render` prompt render, the reply parser and the output-format fragment. +# `metaobjects-codegen` the run engine (skip key, hash manifest, writer) and the shipped +# generators. +# `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. [workspace] resolver = "3" members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli", "metaobjects-render"] [workspace.package] -version = "0.1.0" +version = "1.3.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index 6b5e102d22..60b3998cce 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -24,9 +24,9 @@ name = "cargo-meta" path = "src/main.rs" [dependencies] -metaobjects = { path = "../metaobjects", version = "0.1.0" } -metaobjects-codegen = { path = "../metaobjects-codegen", version = "0.1.0" } -metaobjects-render = { path = "../metaobjects-render", version = "0.1.0" } +metaobjects = { path = "../metaobjects", version = "1.3.0" } +metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.3.0" } +metaobjects-render = { path = "../metaobjects-render", version = "1.3.0" } serde_json.workspace = true diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 1adbfb4db1..d6df1dc838 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -37,7 +37,7 @@ const USAGE: &str = "\ cargo meta: MetaObjects for Rust USAGE: - cargo meta init [--project ] + cargo meta init [--project ] [--transport] cargo meta gen [OPTIONS] [ENTITY...] cargo meta verify [--codegen] [--templates] [--full] [OPTIONS] cargo meta eject ... [--force] [--engine ] @@ -47,7 +47,8 @@ USAGE: COMMANDS: 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. + generators to run. Writes only what is missing. --transport lists the + opt-in axum transport (service-routes) too. 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 @@ -93,7 +94,8 @@ OPTIONS (everywhere): -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. +by name. Edit the list; no eject is needed. With no such file every generator runs but the +opt-in transport (service-routes), which `init --transport` lists. 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. @@ -122,7 +124,7 @@ const fn valued(name: &'static str) -> Flag { Flag { name, value: true } } -const INIT_FLAGS: &[Flag] = &[valued("--project")]; +const INIT_FLAGS: &[Flag] = &[valued("--project"), switch("--transport")]; const GEN_FLAGS: &[Flag] = &[ switch("--force"), valued("--generators"), @@ -371,7 +373,7 @@ fn list_generators( generators: &[Box], ) -> i32 { let listed = match generator_list::read(root) { - Ok(listed) => listed, + Ok(listed) => listed.as_deref().map(generator_list::names), Err(e) => { let _ = writeln!(err, "{TOOL}: {e}"); return 1; @@ -389,7 +391,7 @@ fn list_generators( None => { let _ = writeln!( out, - "No {GENERATOR_LIST_FILE}: every generator runs. `{TOOL} init` writes one to choose from." + "No {GENERATOR_LIST_FILE}: every generator runs but the opt-in ones. `{TOOL} init` writes one to choose from." ); } Some(names) => { @@ -410,7 +412,8 @@ fn list_generators( } } let on = |name: &str| match &listed { - None => String::new(), + None if generator_list::runs_unlisted(name) => String::new(), + None => " [opt-in]".to_string(), Some(names) if names.iter().any(|n| n == name) => " [configured]".to_string(), Some(_) => " [not configured]".to_string(), }; @@ -707,7 +710,7 @@ fn cmd_eject( } /// What `init` writes when it is missing: a path from the project root and its text. -fn init_files() -> [(&'static str, String); 4] { +fn init_files(transport: bool) -> [(&'static str, String); 4] { [ ( ".metaobjects/config.json", @@ -721,7 +724,7 @@ fn init_files() -> [(&'static str, String); 4] { "metaobjects/meta.app.yaml", "metadata:\n package: app\n children: []\n".to_string(), ), - (GENERATOR_LIST_FILE, generator_list::scaffold()), + (GENERATOR_LIST_FILE, generator_list::scaffold(transport)), ] } @@ -747,7 +750,7 @@ fn cmd_init( let has_metadata = std::fs::read_dir(root.join("metaobjects")) .map(|d| d.filter_map(Result::ok).next().is_some()) .unwrap_or(false); - for (rel, text) in init_files() { + for (rel, text) in init_files(s.has("--transport")) { let path = root.join(rel); if path.exists() { let _ = writeln!(out, "kept {rel} (already exists)"); @@ -955,6 +958,30 @@ mod tests { ) } + #[test] + fn init_lists_the_opt_in_transport_only_when_asked() { + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) + .join(format!("mo-cli-init-{}", std::process::id())); + for (flag, listed) in [(None, false), (Some("--transport"), true)] { + let dir = base.join(if listed { "with" } else { "without" }); + let mut list = vec!["init", "--project", dir.to_str().unwrap()]; + list.extend(flag); + let (code, _, err) = run_cli(&list); + assert_eq!(code, 0, "{err}"); + let text = std::fs::read_to_string(dir.join(GENERATOR_LIST_FILE)).unwrap(); + let names = generator_list::names(&generator_list::parse(&text).unwrap()); + assert_eq!( + names.iter().any(|n| n == "service-routes"), + listed, + "{text}" + ); + assert!(names.iter().any(|n| n == "service"), "{text}"); + } + std::fs::remove_dir_all(&base).unwrap(); + } + #[test] fn flags_split_from_words_in_either_spelling() { let s = split( diff --git a/server/rust/metaobjects-cli/src/templates.rs b/server/rust/metaobjects-cli/src/templates.rs index ecd225485c..84d7f82da3 100644 --- a/server/rust/metaobjects-cli/src/templates.rs +++ b/server/rust/metaobjects-cli/src/templates.rs @@ -89,12 +89,8 @@ pub fn derive_payload_field_tree( .map(|t| walk(tree, index, t, seen)) .unwrap_or_default() }); - PayloadField { - name: n.name.clone(), - fields: nested, - // Effective array-ness: `isArray` may be inherited through `extends`. - is_array: tree.resolved_is_array(f), - } + // Effective array-ness: `isArray` may be inherited through `extends`. + PayloadField::owned(n.name.clone(), nested, tree.resolved_is_array(f)) }) .collect(); seen.pop(); @@ -106,7 +102,7 @@ pub fn derive_payload_field_tree( fn field_names(fields: &[PayloadField], out: &mut HashSet) { for f in fields { - out.insert(f.name.clone()); + out.insert(f.name.to_string()); if let Some(nested) = &f.fields { field_names(nested, out); } diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index c2dbdc83b7..2b6c860cb5 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -53,11 +53,15 @@ impl Project { .current_dir(&self.0) // The suite's own environment must not decide what a test sees. .env_remove("CI") - // An owned generator crate is a real cargo build: keep it in the workspace's - // target directory so the engine builds once across runs, and unoptimized. + // An owned generator crate is a real cargo build: keep it under the target + // directory the suite was built into (the workspace's unless one was chosen), so + // the engine builds once across runs, and unoptimized. .env( "CARGO_TARGET_DIR", - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/owned-check"), + std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target")) + .join("owned-check"), ) .env("CARGO_PROFILE_DEV_OPT_LEVEL", "0") .env_remove("CARGO_ENCODED_RUSTFLAGS") @@ -255,14 +259,26 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl 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"]) + serde_json::json!([ + "entity", + "rules-names", + "contract-types", + "repository", + "service", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt" + ]) ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!( - out.contains("metaobjects.config.json runs: entity, client, commands"), + out.contains("metaobjects.config.json runs: entity, rules-names, contract-types, repository, service, client, commands, render-helper, output-parser, output-prompt"), "{out}" ); - assert_eq!(out.matches("[configured]").count(), 3, "{out}"); + assert_eq!(out.matches("[configured]").count(), 10, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 1, "{out}"); // An edited list is never overwritten by a second init. p.write( "metaobjects.config.json", @@ -275,7 +291,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 2, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 10, "{out}"); } #[test] @@ -313,7 +329,7 @@ fn the_generator_list_changes_what_runs_without_an_eject() { // Put it back and the crates come back. p.write( "metaobjects.config.json", - "{ \"generators\": [\"entity\", \"client\", \"commands\"] }", + "{ \"generators\": [\"entity\", \"rules-names\", \"contract-types\", \"repository\", \"service\", \"client\", \"commands\"] }", ); ok(&p.run(&["meta", "gen"])); assert_eq!(p.generated(), full); @@ -473,7 +489,14 @@ fn an_object_that_goes_away_has_its_files_removed_unless_one_was_edited() { fn gen_list_names_the_generators_and_how_an_owned_copy_compares() { let p = Project::new("list"); let out = ok(&p.run(&["meta", "gen", "--list"])); - for name in ["entity", "client", "commands"] { + for name in [ + "entity", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt", + ] { assert!( out.lines().any(|l| l.starts_with(&format!("{name} - "))), "{out}" @@ -570,7 +593,7 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica assert_eq!(r.status.code(), Some(2)); assert!( text(&r.stderr).contains( - "unknown or non-ejectable generator(s): nope; ejectable: entity, client, commands" + "unknown or non-ejectable generator(s): nope; ejectable: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt" ), "{}", text(&r.stderr) @@ -995,8 +1018,15 @@ fn a_bare_verify_runs_the_template_gate_beside_the_codegen_gate() { let r = p.run(&["meta", "verify"]); assert_eq!(r.status.code(), Some(1)); assert!(text(&r.stderr).contains("ERR_VAR_NOT_ON_PAYLOAD: nope")); - // `--codegen` alone never reads the templates. - ok(&p.run(&["meta", "verify", "--codegen"])); + // `--codegen` alone runs no template gate: the drift it reports is the render-helper generator's. + let r = p.run(&["meta", "verify", "--codegen"]); + assert_eq!(r.status.code(), Some(1)); + let err = text(&r.stderr); + assert!( + err.contains("render-helper drift: template \"AnswerPrompt\""), + "{err}" + ); + assert!(!err.contains("drift error(s) across"), "{err}"); } #[test] diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml index dfdc4ad635..d555e30740 100644 --- a/server/rust/metaobjects-codegen/Cargo.toml +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "metaobjects-codegen" -description = "MetaObjects code generation for Rust: the run engine and the entity, client and commands generators." +description = "MetaObjects code generation for Rust: the run engine and the shipped generators." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -14,10 +14,18 @@ categories = ["development-tools", "development-tools::build-utils"] build = "build.rs" [dependencies] -metaobjects = { path = "../metaobjects", version = "0.1.0" } +metaobjects = { path = "../metaobjects", version = "1.3.0" } +metaobjects-render = { path = "../metaobjects-render", version = "1.3.0" } serde_json.workspace = true indexmap.workspace = true serde.workspace = true +[dev-dependencies] +# The layout ratchet (tests/layout_ratchet.rs) parses generator source to find hand-typed layout. +syn = { version = "3", default-features = false, features = ["full", "visit", "parsing", "printing", "clone-impls"] } +proc-macro2 = { version = "1", features = ["span-locations"] } +# The persistence-corpus runner (tests/persistence_conformance.rs) reads the scenario YAML. +saphyr = "0.3.4" + [lints] workspace = true diff --git a/server/rust/metaobjects-codegen/examples/gen_bench.rs b/server/rust/metaobjects-codegen/examples/gen_bench.rs index 7bc37745d7..8520167714 100644 --- a/server/rust/metaobjects-codegen/examples/gen_bench.rs +++ b/server/rust/metaobjects-codegen/examples/gen_bench.rs @@ -35,6 +35,10 @@ use serde_json::{Map, Value, json}; const FITNESS: &str = include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); +/// The one prompt body the model's template names; every copy's template points at it. +const COACH_NOTE: &str = include_str!( + "../../../../fixtures/persistence-conformance/canonical/prompts/fitness/coach-note.mustache" +); const ROOT_PACKAGE: &str = "\"package\": \"fitness\""; /// An object that exists in every copy; the change scenario gives it a description. const CHANGE_AT: &str = "\"name\": \"AllTypes\""; @@ -146,6 +150,11 @@ fn main() { &project.join(".metaobjects/config.json"), r#"{ "schema_version": 1 }"#, ); + // The template the render-helper generator checks every copy's helper against. + write( + &project.join("prompts/fitness/coach-note.mustache"), + COACH_NOTE, + ); let model_file = |i: usize| project.join(format!("metaobjects/meta.fitness_x{i:02}.json")); for i in 0..copies { write(&model_file(i), ©_text(i)); diff --git a/server/rust/metaobjects-codegen/src/client.rs b/server/rust/metaobjects-codegen/src/client.rs index 45e6aea414..22dae76346 100644 --- a/server/rust/metaobjects-codegen/src/client.rs +++ b/server/rust/metaobjects-codegen/src/client.rs @@ -37,12 +37,15 @@ use std::collections::BTreeSet; +use metaobjects_codegen::emitted::CLIENT_TRANSPORT_RS; use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; use metaobjects_codegen::names::{literal, pascal, snake}; use metaobjects_codegen::plan::{ CLIENT_CRATE, CLIENT_SUFFIX, CratePlan, FieldPlan, Plan, Route, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, RUSTFMT_TOML, file, item, list, piece}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, RUSTFMT_TOML, file, fixed, item, list, piece, sibling_dep, toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 1; @@ -50,7 +53,7 @@ const FORMAT: u32 = 1; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`."; /// The client generator. #[derive(Debug, Clone, Copy, Default)] @@ -66,320 +69,123 @@ impl Generator for ClientGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = Vec::new(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - client_crate(&plan, cname, c, &mut files)?; - } - if !files.is_empty() { - files.extend(transport_crate()); - } - Ok(files) + self.render(ctx) } } -// ---- the transport crate --------------------------------------------------------------- - -/// The crate of HTTP plumbing the client crates share. It is generated, so the output -/// depends on nothing from MetaObjects. -fn transport_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"The HTTP transport of the generated MetaObjects client crates.\"\n\ - \n\ - [dependencies]\n\ - reqwest = {{ version = \"0.13\", features = [\"json\", \"query\"] }}\n\ - serde = {{ version = \"1\", features = [\"derive\"] }}\n\ - serde_json = \"1\"\n", - literal(CLIENT_CRATE) - ); - let file = |name: &str, text: String| EmittedFile::new(format!("{CLIENT_CRATE}/{name}"), text); - vec![ - file("Cargo.toml", manifest), - file("rustfmt.toml", RUSTFMT_TOML.to_string()), - file("src/lib.rs", format!("{BANNER}\n\n{TRANSPORT_RS}")), - ] -} - -/// `meta_client/src/lib.rs`, in rustfmt's output form under the generated `rustfmt.toml`. -const TRANSPORT_RS: &str = r##"//! The transport every generated client crate uses: one HTTP client, the list query, and -//! the error a call fails with. It follows the REST contract every MetaObjects server -//! generator implements, whatever language the server is written in. - -use std::fmt; - -use serde::de::DeserializeOwned; -use serde::Serialize; - -/// The HTTP library underneath, so a caller can set a client up without naming it as a -/// dependency of its own. -pub use reqwest; - -/// What a call returns. -pub type Result = std::result::Result; - -/// Why a call failed. -#[derive(Debug)] -pub enum Error { - /// The request did not get an answer. - Transport(reqwest::Error), - /// The server refused the request. `code` and `message` are its error body's `error` and - /// `message` members, when it sent them; `body` is the body as it arrived. - Api { status: u16, code: Option, message: Option, body: String }, - /// The server answered, and the body is not what the model says a row looks like. - Decode { status: u16, message: String }, -} - -impl Error { - /// The HTTP status of the answer, when there was one. - pub fn status(&self) -> Option { - match self { - Error::Transport(e) => e.status().map(|s| s.as_u16()), - Error::Api { status, .. } | Error::Decode { status, .. } => Some(*status), - } - } - - /// The server's error code (`not_found`, `validation`, ...), when it sent one. - pub fn code(&self) -> Option<&str> { - match self { - Error::Api { code, .. } => code.as_deref(), - _ => None, - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::Transport(e) => write!(f, "the request failed: {e}"), - Error::Api { status, code, message, .. } => { - write!(f, "the server answered {status}")?; - if let Some(code) = code { - write!(f, " {code}")?; - } - if let Some(message) = message { - write!(f, ": {message}")?; - } - Ok(()) - } - Error::Decode { status, message } => { - write!(f, "the server answered {status} with a body that does not fit: {message}") - } - } - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Transport(e) => Some(e), - _ => None, - } - } -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Transport(e) - } -} - -/// The API's address and the HTTP client that reaches it. -#[derive(Debug, Clone)] -pub struct Client { - http: reqwest::Client, - base: String, -} - -impl Client { - /// A client for the API at `base_url`: the server's address and the prefix its routes - /// are mounted under, as in `https://example.com/api`. - pub fn new(base_url: &str) -> Self { - Self::with_http(reqwest::Client::new(), base_url) - } - - /// The same, over an HTTP client you set up yourself (timeouts, headers, a proxy). - pub fn with_http(http: reqwest::Client, base_url: &str) -> Self { - Self { http, base: base_url.trim_end_matches('/').to_string() } - } - - /// The address every path is taken under. - pub fn base_url(&self) -> &str { - &self.base - } +impl ClientParts for ClientGenerator {} - fn url(&self, path: &str) -> String { - format!("{}/{}", self.base, path) +/// The pieces of the client generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait ClientParts { + /// Every file: one client crate per package with a served entity, then the transport + /// crate when there is any. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) } - /// `GET path`, read as `T`. - pub async fn get(&self, path: &str) -> Result { - read(self.http.get(self.url(path)).send().await?).await + /// The transport crate's files. + fn transport_crate(&self) -> Vec { + transport_crate() } - /// `GET path?query`, read as `T`. - pub async fn list(&self, path: &str, query: &Query) -> Result { - read(self.http.get(self.url(path)).query(query.pairs()).send().await?).await + /// A client crate's `Cargo.toml`, with a dependency on each model crate it names. + fn manifest(&self, name: &str, c: &CratePlan, deps: &BTreeSet) -> String { + cargo_toml(name, c, deps) } - /// `POST path` with a JSON body, read as `T`. - pub async fn post(&self, path: &str, body: &B) -> Result - where - B: Serialize + ?Sized, - T: DeserializeOwned, - { - read(self.http.post(self.url(path)).json(body).send().await?).await + /// A client crate's `src/lib.rs`: each module and what it exports. + fn lib_file(&self, package: &str, items: &[(String, Vec)]) -> String { + lib_file(package, items) } - /// `PATCH path` with a JSON body, read as `T`. - pub async fn patch(&self, path: &str, body: &B) -> Result - where - B: Serialize + ?Sized, - T: DeserializeOwned, - { - read(self.http.patch(self.url(path)).json(body).send().await?).await + /// One served entity's file: its client, then its query and sort types. + fn entity_file( + &self, + plan: &Plan, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result { + entity_file(self, plan, s, route, deps) } - /// `DELETE path`. - pub async fn delete(&self, path: &str) -> Result<()> { - let response = self.http.delete(self.url(path)).send().await?; - if response.status().is_success() { - return Ok(()); - } - Err(refusal(response).await) + /// One entity's client: the struct and a method per route. + fn client_item( + &self, + plan: &Plan, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result { + client_item(plan, s, route, deps) } -} -async fn read(response: reqwest::Response) -> Result { - let status = response.status(); - if !status.is_success() { - return Err(refusal(response).await); + /// One entity's list query and, when it sorts, its sort type. + fn query_items( + &self, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result, GenError> { + query_items(s, route, deps) } - let text = response.text().await?; - serde_json::from_str(&text) - .map_err(|e| Error::Decode { status: status.as_u16(), message: e.to_string() }) -} - -async fn refusal(response: reqwest::Response) -> Error { - let status = response.status().as_u16(); - let body = response.text().await.unwrap_or_default(); - let parsed: Option = serde_json::from_str(&body).ok(); - let member = |name: &str| { - parsed.as_ref().and_then(|v| v.get(name)).and_then(|v| v.as_str()).map(str::to_string) - }; - Error::Api { status, code: member("error"), message: member("message"), body } -} - -/// The order a sort puts rows in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Direction { - /// The order the model declares for the field (ascending when it declares none). - Default, - Ascending, - Descending, -} - -/// The query of a list request: filters, a sort and a window. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct Query { - pairs: Vec<(String, String)>, } -impl Query { - pub fn new() -> Self { - Self::default() - } - - /// The query's parameters, in the order they were added, not yet percent-encoded. - pub fn pairs(&self) -> &[(String, String)] { - &self.pairs - } - - fn set(&mut self, name: &str, value: String) { - self.pairs.retain(|(n, _)| n != name); - self.pairs.push((name.to_string(), value)); - } - - /// Keep the rows whose `field` passes `op` against `value`. Filters add up: a row must - /// pass them all. - pub fn filter(&mut self, field: &str, op: &str, value: impl fmt::Display) { - self.pairs.push((format!("filter[{field}][{op}]"), value.to_string())); - } - - /// Keep the rows whose `field` is one of `values`. - pub fn filter_in(&mut self, field: &str, values: impl IntoIterator) { - let joined: Vec = values.into_iter().map(|v| v.to_string()).collect(); - self.filter(field, "in", joined.join(",")); - } - - /// Sort by `field`. A later sort replaces an earlier one: the contract has one sort key. - pub fn sort(&mut self, field: &str, direction: Direction) { - let value = match direction { - Direction::Default => field.to_string(), - Direction::Ascending => format!("{field}:asc"), - Direction::Descending => format!("{field}:desc"), - }; - self.set("sort", value); - } - - /// Return at most `rows` rows. - pub fn limit(&mut self, rows: u64) { - self.set("limit", rows.to_string()); +/// The shipped [`ClientParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = Vec::new(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; + } + client_crate(parts, &plan, cname, c, &mut files)?; } - - /// Skip the first `rows` rows. - pub fn offset(&mut self, rows: u64) { - self.set("offset", rows.to_string()); + if !files.is_empty() { + files.extend(parts.transport_crate()); } - - /// Ask for the `{ rows, total }` answer a [`Page`] reads. - pub fn with_count(&mut self) { - self.set("withCount", "1".to_string()); - } -} - -/// One window of a list, and how many rows the filters match in all. -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct Page { - pub rows: Vec, - pub total: u64, + Ok(files) } -/// The path of one row: `collection/id`, with the id percent-encoded. -pub fn row(collection: &str, id: impl fmt::Display) -> String { - format!("{collection}/{}", segment(&id.to_string())) -} - -/// The path of the rows related to one row: `collection/id/relation`. -pub fn related(collection: &str, id: impl fmt::Display, relation: &str) -> String { - format!("{}/{relation}", row(collection, id)) -} +// ---- the transport crate --------------------------------------------------------------- -/// One path segment, percent-encoded: everything but RFC 3986's unreserved characters. -pub fn segment(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - for byte in text.bytes() { - if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { - out.push(char::from(byte)); - } else { - out.push_str(&format!("%{byte:02X}")); - } - } - out +/// The crate of HTTP plumbing the client crates share. It is generated, so the output +/// depends on nothing from MetaObjects. +pub fn transport_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, CLIENT_CRATE); + m.entry( + "description", + &toml_string("The HTTP transport of the generated MetaObjects client crates."), + ); + m.blank().table("dependencies"); + m.entry( + "reqwest", + r#"{ version = "0.13", features = ["json", "query"] }"#, + ); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + m.entry("serde_json", &toml_string("1")); + let manifest = m.finish(); + let file = |name: &str, text: String| EmittedFile::new(format!("{CLIENT_CRATE}/{name}"), text); + vec![ + file("Cargo.toml", manifest), + file("rustfmt.toml", RUSTFMT_TOML.to_string()), + file("src/lib.rs", fixed(BANNER, CLIENT_TRANSPORT_RS)), + ] } -"##; // ---- one client crate ------------------------------------------------------------------ -fn client_crate( +fn client_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -399,7 +205,7 @@ fn client_crate( exports.push(s.sort_name()); } lib_items.push((s.module(), exports)); - let text = entity_file(plan, s, route, &mut deps)?; + let text = parts.entity_file(plan, s, route, &mut deps)?; files.push(EmittedFile::new( format!("{name}/src/{}.rs", s.module()), text, @@ -408,7 +214,7 @@ fn client_crate( lib_items.sort(); files.push(EmittedFile::new( format!("{name}/Cargo.toml"), - cargo_toml(&name, c, &deps), + parts.manifest(&name, c, &deps), )); files.push(EmittedFile::new( format!("{name}/rustfmt.toml"), @@ -416,61 +222,55 @@ fn client_crate( )); files.push(EmittedFile::new( format!("{name}/src/lib.rs"), - lib_file(&c.package, &lib_items), + parts.lib_file(&c.package, &lib_items), )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan, deps: &BTreeSet) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`ClientParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan, deps: &BTreeSet) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); let package = if c.package.is_empty() { "the model's" } else { c.package.as_str() }; - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "A client for the REST API of the MetaObjects package {package}." - )) - )); - out.push_str("\n[dependencies]\n"); - out.push_str(&format!( - "{CLIENT_CRATE} = {{ path = \"../{CLIENT_CRATE}\" }}\n" - )); + )), + ); + m.blank().table("dependencies"); + m.entry(CLIENT_CRATE, &sibling_dep(CLIENT_CRATE)); for dep in deps { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } -fn lib_file(package: &str, items: &[(String, Vec)]) -> String { - let mut out = format!("{BANNER}\n\n"); +/// The shipped [`ClientParts::lib_file`]. +pub fn lib_file(package: &str, items: &[(String, Vec)]) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); if package.is_empty() { - out.push_str( - "//! A client for the REST API of the MetaObjects model that declares no package.\n", - ); + w.line("//! A client for the REST API of the MetaObjects model that declares no package."); } else { - out.push_str(&format!( - "//! A client for the REST API of the MetaObjects package `{package}`.\n" + w.line(format!( + "//! A client for the REST API of the MetaObjects package `{package}`." )); } - out.push('\n'); + w.blank(); for (module, _) in items { - out.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - out.push('\n'); + w.blank(); for (module, exports) in items { for e in exports { - out.push_str(&format!("pub use {module}::{e};\n")); + w.line(format!("pub use {module}::{e};")); } } - out + w.finish().expect("a lib.rs opens no block") } // ---- one entity ------------------------------------------------------------------------ @@ -596,7 +396,8 @@ fn filter_method(w: &mut CodeWriter, f: &FieldPlan, op: &str, p: &Param) { }); } -fn query_items( +/// The shipped [`ClientParts::query_items`]. +pub fn query_items( s: &StructPlan, route: &Route, deps: &mut BTreeSet, @@ -735,7 +536,8 @@ fn call(w: &mut CodeWriter, doc: &str, name: &str, args: Vec, returns: & }); } -fn client_item( +/// The shipped [`ClientParts::client_item`]. +pub fn client_item( plan: &Plan, s: &StructPlan, route: &Route, @@ -856,13 +658,15 @@ fn client_item( })?) } -fn entity_file( +/// The shipped [`ClientParts::entity_file`], through `parts`. +pub fn entity_file( + parts: &P, plan: &Plan, s: &StructPlan, route: &Route, deps: &mut BTreeSet, ) -> Result { - let mut items = vec![client_item(plan, s, route, deps)?]; - items.extend(query_items(s, route, deps)?); + let mut items = vec![parts.client_item(plan, s, route, deps)?]; + items.extend(parts.query_items(s, route, deps)?); Ok(file(BANNER, &items)) } diff --git a/server/rust/metaobjects-codegen/src/commands.rs b/server/rust/metaobjects-codegen/src/commands.rs index ac5eaf581c..a90b83e4aa 100644 --- a/server/rust/metaobjects-codegen/src/commands.rs +++ b/server/rust/metaobjects-codegen/src/commands.rs @@ -35,13 +35,17 @@ use std::collections::BTreeSet; +use metaobjects_codegen::emitted::COMMAND_HELPERS_RS; use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; use metaobjects_codegen::names::{literal, pascal, snake}; use metaobjects_codegen::plan::{ CLI_CRATE, CLI_SUFFIX, CLIENT_CRATE, CLIENT_SUFFIX, CratePlan, FieldPlan, Kind, Plan, Presence, Route, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, RUSTFMT_TOML, file, item, list, padded, piece}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, RUSTFMT_TOML, file, fixed, item, list, padded, piece, sibling_dep, + toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 1; @@ -49,7 +53,7 @@ const FORMAT: u32 = 1; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`."; /// The commands generator. #[derive(Debug, Clone, Copy, Default)] @@ -65,261 +69,105 @@ impl Generator for CommandsGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = Vec::new(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - command_crate(&plan, cname, c, &mut files)?; - } - if !files.is_empty() { - files.extend(helper_crate()); - } - Ok(files) - } -} - -// ---- the helper crate ------------------------------------------------------------------ - -/// The crate of helpers the command crates share. It is generated, so the output depends on -/// nothing from MetaObjects. -fn helper_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"What the generated MetaObjects command crates build a request with.\"\n\ - \n\ - [dependencies]\n\ - serde = \"1\"\n\ - serde_json = \"1\"\n\ - {CLIENT_CRATE} = {{ path = \"../{CLIENT_CRATE}\" }}\n\ - {SUPPORT_CRATE} = {{ path = \"../{SUPPORT_CRATE}\" }}\n", - literal(CLI_CRATE) - ); - let file = |name: &str, text: String| EmittedFile::new(format!("{CLI_CRATE}/{name}"), text); - vec![ - file("Cargo.toml", manifest), - file("rustfmt.toml", RUSTFMT_TOML.to_string()), - file("src/lib.rs", format!("{BANNER}\n\n{HELPERS_RS}")), - ] -} - -/// `meta_cli/src/lib.rs`, in rustfmt's output form under the generated `rustfmt.toml`. -const HELPERS_RS: &str = r##"//! What every generated command crate uses: the body a command line describes, the query -//! its filters describe, and the error a command fails with. - -use std::fmt; -use std::io::Read; - -use serde::de::DeserializeOwned; -use serde::Serialize; -use serde_json::{Map, Value}; - -/// What a command returns: the server's answer as JSON (`null` when it sent none). -pub type Answer = Result; - -/// Why a command failed. -#[derive(Debug)] -pub enum Error { - /// The command line asks for something the model does not allow, or is not well formed. - Usage(String), - /// The body breaks rules of the model: one message per rule. Nothing was sent. - Invalid(Vec), - /// The call failed. - Api(meta_client::Error), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::Usage(message) => f.write_str(message), - Error::Invalid(messages) => write!(f, "the body is not valid: {}", messages.join("; ")), - Error::Api(e) => e.fmt(f), - } + self.render(ctx) } } -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Api(e) => Some(e), - _ => None, - } +impl CommandsParts for CommandsGenerator {} + +/// The pieces of the commands generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait CommandsParts { + /// Every file: one command crate per package with a served entity, then the helper + /// crate when there is any. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) } -} - -impl From for Error { - fn from(e: meta_client::Error) -> Self { - Error::Api(e) - } -} -/// The body a `--json` argument gives: a JSON object, read from standard input when the -/// argument is `-`, and empty when there is no argument. -pub fn body(json: Option<&str>) -> Result, Error> { - let text = match json { - None => return Ok(Map::new()), - Some("-") => { - let mut text = String::new(); - std::io::stdin().read_to_string(&mut text).map_err(|e| { - Error::Usage(format!("cannot read the body from standard input: {e}")) - })?; - text - } - Some(text) => text.to_string(), - }; - match serde_json::from_str(&text) { - Ok(Value::Object(body)) => Ok(body), - Ok(_) => Err(Error::Usage("the body must be a JSON object".to_string())), - Err(e) => Err(Error::Usage(format!("the body is not JSON: {e}"))), + /// The helper crate's files. + fn helper_crate(&self) -> Vec { + helper_crate() } -} -/// Refuses a body member the model does not declare: a misspelled name must not be dropped -/// on the way to the server, which would refuse it too under its default setting. -pub fn known(body: &Map, members: &[&str]) -> Result<(), Error> { - let unknown: Vec<&str> = - body.keys().map(String::as_str).filter(|name| !members.contains(name)).collect(); - if unknown.is_empty() { - return Ok(()); + /// A command crate's `Cargo.toml`, with a dependency on each crate in `deps`. + fn manifest(&self, name: &str, c: &CratePlan, deps: &[&str]) -> String { + cargo_toml(name, c, deps) } - Err(Error::Usage(format!( - "the body sets {}, which the model does not declare (it declares: {})", - unknown.join(", "), - members.join(", ") - ))) -} -/// Sets one member of the body from its flag, when the flag was given. -pub fn put( - body: &mut Map, - name: &str, - value: Option, -) -> Result<(), Error> { - if let Some(value) = value { - let value = serde_json::to_value(value) - .map_err(|e| Error::Usage(format!("the value of {name} cannot be sent: {e}")))?; - body.insert(name.to_string(), value); + /// A command crate's `src/lib.rs`: its modules and the `Command` and `run` over them. + /// Each group is a module, its entity's type name and its route path. + fn lib_file( + &self, + package: &str, + groups: &[(String, String, String)], + ) -> Result { + lib_file(package, groups) } - Ok(()) -} -/// Sets one array member of the body from its repeated flag, when it was given at all. -pub fn put_all( - body: &mut Map, - name: &str, - values: Vec, -) -> Result<(), Error> { - if values.is_empty() { - return Ok(()); + /// One served entity's file: its subcommands and how each runs. + fn entity_file( + &self, + s: &StructPlan, + route: &Route, + model_crate: &str, + client_crate: &str, + ) -> Result { + entity_file(s, route, model_crate, client_crate) } - put(body, name, Some(values)) } -/// Reads the finished body as the model's type. -pub fn decode(body: Map) -> Result { - serde_json::from_value(Value::Object(body)) - .map_err(|e| Error::Usage(format!("the body does not fit the model: {e}"))) -} - -/// Refuses a body that breaks rules of the model. -pub fn check(found: Vec) -> Result<(), Error> { - if found.is_empty() { - return Ok(()); - } - Err(Error::Invalid(found.into_iter().map(|v| v.message).collect())) -} - -/// Adds the `--filter` tests to a query. A test is written `field:op=value`, and -/// `field=value` means `field:eq=value`. `allowed` is the model's allowlist. -pub fn filters( - query: &mut meta_client::Query, - tests: &[String], - allowed: &[(&str, &[&str])], -) -> Result<(), Error> { - for test in tests { - let Some((subject, value)) = test.split_once('=') else { - return Err(Error::Usage(format!("--filter {test}: expected field:op=value"))); - }; - let (field, op) = subject.split_once(':').unwrap_or((subject, "eq")); - let Some((_, ops)) = allowed.iter().find(|(name, _)| *name == field) else { - let names: Vec<&str> = allowed.iter().map(|(name, _)| *name).collect(); - return Err(Error::Usage(format!( - "--filter {test}: {field} is not a field this list filters on (it filters on: {})", - names.join(", ") - ))); - }; - if !ops.contains(&op) { - return Err(Error::Usage(format!( - "--filter {test}: {field} does not take {op} (it takes: {})", - ops.join(", ") - ))); +/// The shipped [`CommandsParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = Vec::new(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; } - query.filter(field, op, value); + command_crate(parts, &plan, cname, c, &mut files)?; } - Ok(()) -} - -/// Adds the `--sort` to a query: `field`, `field:asc` or `field:desc`. `allowed` is the -/// model's allowlist. -pub fn sort( - query: &mut meta_client::Query, - spec: Option<&str>, - allowed: &[&str], -) -> Result<(), Error> { - let Some(spec) = spec else { - return Ok(()); - }; - let (field, direction) = match spec.split_once(':') { - None => (spec, meta_client::Direction::Default), - Some((field, "asc")) => (field, meta_client::Direction::Ascending), - Some((field, "desc")) => (field, meta_client::Direction::Descending), - Some(_) => { - return Err(Error::Usage(format!( - "--sort {spec}: expected field, field:asc or field:desc" - ))); - } - }; - if !allowed.contains(&field) { - return Err(Error::Usage(format!( - "--sort {spec}: {field} is not a field this list sorts on (it sorts on: {})", - allowed.join(", ") - ))); + if !files.is_empty() { + files.extend(parts.helper_crate()); } - query.sort(field, direction); - Ok(()) + Ok(files) } -/// Adds the `--limit` and the `--offset` to a query. -pub fn window(query: &mut meta_client::Query, limit: Option, offset: Option) { - if let Some(limit) = limit { - query.limit(limit); - } - if let Some(offset) = offset { - query.offset(offset); - } -} - -/// What the server answered, as the JSON a command returns. -pub fn answer(found: &T) -> Answer { - serde_json::to_value(found) - .map_err(|e| Error::Usage(format!("the answer cannot be written as JSON: {e}"))) -} +// ---- the helper crate ------------------------------------------------------------------ -/// An answer as the text a command prints. -pub fn render(answer: &Value) -> String { - serde_json::to_string_pretty(answer).unwrap_or_else(|_| answer.to_string()) +/// The crate of helpers the command crates share. It is generated, so the output depends on +/// nothing from MetaObjects. +pub fn helper_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, CLI_CRATE); + m.entry( + "description", + &toml_string("What the generated MetaObjects command crates build a request with."), + ); + m.blank().table("dependencies"); + m.entry("serde", &toml_string("1")); + m.entry("serde_json", &toml_string("1")); + m.entry(CLIENT_CRATE, &sibling_dep(CLIENT_CRATE)); + m.entry(SUPPORT_CRATE, &sibling_dep(SUPPORT_CRATE)); + let manifest = m.finish(); + let file = |name: &str, text: String| EmittedFile::new(format!("{CLI_CRATE}/{name}"), text); + vec![ + file("Cargo.toml", manifest), + file("rustfmt.toml", RUSTFMT_TOML.to_string()), + file("src/lib.rs", fixed(BANNER, COMMAND_HELPERS_RS)), + ] } -"##; // ---- one command crate ----------------------------------------------------------------- -fn command_crate( +fn command_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -335,14 +183,14 @@ fn command_crate( for s in &served { let route = s.route.as_ref().expect("a served entity has a route"); groups.push((s.module(), s.type_name.clone(), route.path.clone())); - let text = entity_file(s, route, cname, &client_crate)?; + let text = parts.entity_file(s, route, cname, &client_crate)?; files.push(EmittedFile::new( format!("{name}/src/{}.rs", s.module()), text, )); } groups.sort(); - let manifest = cargo_toml(&name, c, &[cname, &client_crate]); + let manifest = parts.manifest(&name, c, &[cname, &client_crate]); files.push(EmittedFile::new(format!("{name}/Cargo.toml"), manifest)); files.push(EmittedFile::new( format!("{name}/rustfmt.toml"), @@ -350,39 +198,35 @@ fn command_crate( )); files.push(EmittedFile::new( format!("{name}/src/lib.rs"), - lib_file(&c.package, &groups)?, + parts.lib_file(&c.package, &groups)?, )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan, deps: &[&str]) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`CommandsParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan, deps: &[&str]) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); let package = if c.package.is_empty() { "the model's" } else { c.package.as_str() }; - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "Commands over the REST API of the MetaObjects package {package}." - )) - )); - out.push_str("\n[dependencies]\n"); - out.push_str("clap = { version = \"4\", features = [\"derive\"] }\n"); - out.push_str("serde_json = \"1\"\n"); + )), + ); + m.blank().table("dependencies"); + m.entry("clap", r#"{ version = "4", features = ["derive"] }"#); + m.entry("serde_json", &toml_string("1")); for dep in [CLI_CRATE, CLIENT_CRATE] .into_iter() .chain(deps.iter().copied()) { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } /// A match arm with one expression for a body: on one line when it fits, and in a block @@ -398,27 +242,27 @@ fn arm(w: &mut CodeWriter, pattern: &str, body: &str) { } } -fn lib_file(package: &str, groups: &[(String, String, String)]) -> Result { - let mut head = String::new(); +/// The shipped [`CommandsParts::lib_file`]. +pub fn lib_file(package: &str, groups: &[(String, String, String)]) -> Result { + let mut w = CodeWriter::new(); if package.is_empty() { - head.push_str( - "//! Commands over the REST API of the MetaObjects model that declares no package.\n", - ); + w.line("//! Commands over the REST API of the MetaObjects model that declares no package."); } else { - head.push_str(&format!( - "//! Commands over the REST API of the MetaObjects package `{package}`.\n" + w.line(format!( + "//! Commands over the REST API of the MetaObjects package `{package}`." )); } - head.push_str( - "//!\n//! Mount `Command` in your own `clap` parser and hand what it parsed to `run`.\n\n", - ); + w.line("//!"); + w.line("//! Mount `Command` in your own `clap` parser and hand what it parsed to `run`."); + w.blank(); for (module, _, _) in groups { - head.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - head.push('\n'); + w.blank(); for (module, type_name, _) in groups { - head.push_str(&format!("pub use {module}::{type_name}Command;\n")); + w.line(format!("pub use {module}::{type_name}Command;")); } + let head = w.finish()?; let what = if package.is_empty() { "What to do with the model.".to_string() } else { @@ -580,7 +424,8 @@ fn body_statements(w: &mut CodeWriter, flags: &[Flag<'_>], body_type: &str) { w.line(format!("{CLI_CRATE}::check(body.validate())?;")); } -fn entity_file( +/// The shipped [`CommandsParts::entity_file`]. +pub fn entity_file( s: &StructPlan, route: &Route, model_crate: &str, diff --git a/server/rust/metaobjects-codegen/src/contract_types.rs b/server/rust/metaobjects-codegen/src/contract_types.rs new file mode 100644 index 0000000000..69a2104951 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/contract_types.rs @@ -0,0 +1,755 @@ +//! The `contract-types` generator: the shapes a caller and a service exchange through a +//! package's declared operations, one crate per package (ADR-0067 §1, layer 1). +//! +//! In Rust the entity generator's model crate already is the contract for an entity: its read +//! struct, `Create` and `Patch` with `validate()`, and its value objects, with +//! no persistence mapping in any of them. This generator builds on it (it needs `entity`, as +//! C#'s does) and adds what the model crate has no place for. For the package `acme::shop` +//! that declares operations it writes: +//! +//! ```text +//! /acme_shop_contract/Cargo.toml the crate (the model crates, meta_contract) +//! /acme_shop_contract/src/lib.rs its modules and exports +//! /acme_shop_contract/src/.rs the read shape of a projection an operation returns +//! /acme_shop_contract/src/operations.rs each operation's input, output and errors +//! /meta_contract/ the wire error codes, statuses and bodies +//! ``` +//! +//! Per operation (`placeOrder`): `PlaceOrderInput`, the `@inputRef` value object; +//! `PlaceOrderOutput`, the `@outputRef` object (a `Vec` of it when `@many`); +//! `PlaceOrderBusinessError`, the codes its body may return (`@errors`), serialized as the code; +//! and `PlaceOrderError`, the error body it answers with, whose code is a fixed one or a business +//! one. A projection's read shape is the struct the entity generator writes for an object: a +//! view-backed projection is a served read, which the model crate already holds, and any other is +//! written here. A model that declares no operation gets nothing from this generator. +//! +//! Which operations and what they resolve to come from the engine walk +//! ([`metaobjects::rules_names::rules_names_of`] and the model's own references), so an owned +//! copy changes the files' shape and keeps that walk. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::rules_names::{OperationKind, rules_names_of}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_codegen::emitted::CONTRACT_RS; +use metaobjects_codegen::generator::{ + ERR_NAME_COLLISION, ERR_UNSUPPORTED, EmittedFile, GenContext, GenError, Generator, +}; +use metaobjects_codegen::names::{PRELUDE_TYPES, crate_name, literal, type_ident}; +use metaobjects_codegen::plan::{ + CONTRACT_CRATE, EnumPlan, FieldPlan, NullMembers, Plan, SUPPORT_CRATE, StructPlan, Ty, + is_served_read, +}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, RUSTFMT_TOML, file, fixed, item, list, sibling_dep, toml_string, +}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +/// The line every generated Rust file starts with. +pub const BANNER: &str = "// @generated by the MetaObjects contract-types generator. Do not edit: change the model and run `cargo meta gen`."; + +const MANIFEST_BANNER: &str = "@generated by the MetaObjects contract-types generator. Do not edit: change the model and run `cargo meta gen`."; + +pub use metaobjects_codegen::plan::CONTRACT_SUFFIX; + +const ATTR_INPUT_REF: &str = "inputRef"; +const ATTR_OUTPUT_REF: &str = "outputRef"; +const ATTR_MANY: &str = "many"; +const SUB_PROJECTION: &str = "projection"; +const OPERATIONS_MODULE: &str = "operations"; + +/// The contract-types generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct ContractTypesGenerator; + +impl Generator for ContractTypesGenerator { + fn name(&self) -> &str { + "contract-types" + } + + fn identity(&self) -> String { + format!("contract-types:{FORMAT}") + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + self.render(ctx) + } +} + +impl ContractTypesParts for ContractTypesGenerator {} + +/// The pieces of the contract-types generator's output, one method each (ADR-0063 item 7). +/// Each default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait ContractTypesParts { + /// Every file: one contract crate per package with a declared operation, and the shared + /// wire error crate. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) + } + + /// The wire error crate's files. + fn errors_crate(&self) -> Vec { + errors_crate() + } + + /// A contract crate's `Cargo.toml`. + fn manifest(&self, c: &ContractCrate) -> String { + cargo_toml(c) + } + + /// A contract crate's `src/lib.rs`: its modules and exports. + fn lib_file(&self, c: &ContractCrate) -> String { + lib_file(c) + } + + /// A projection's file: its read shape and its enums. + fn shape_file( + &self, + plan: &Plan, + s: &StructPlan, + current: &str, + shadowed: &BTreeSet, + ) -> Result { + shape_file(plan, s, current, shadowed) + } + + /// A contract crate's `src/operations.rs`. + fn operations_file(&self, c: &ContractCrate) -> Result { + operations_file(self, c) + } + + /// One operation's types. + fn operation_item(&self, w: &mut CodeWriter, o: &OperationContract) { + operation_item(w, o); + } +} + +// ---- the plan ---------------------------------------------------------------------------- + +/// One declared operation, with its references resolved to Rust paths. +pub struct OperationContract { + pub name: String, + pub kind: OperationKind, + /// The type-name stem: the operation's name in pascal case (`placeOrder`: `PlaceOrder`). + pub stem: String, + /// The `@inputRef` value object's path, when declared. + pub input: Option, + /// The `@outputRef` object's path, when declared. + pub output: Option, + /// `@many`: the output is a list. + pub many: bool, + /// Each business error's code with its variant, in declaration order. + pub errors: Vec<(String, String)>, +} + +/// One package's contract crate. +pub struct ContractCrate { + /// The crate's name (`acme_shop_contract`). + pub name: String, + /// The package (`acme::shop`), or `""` for a model with none. + pub package: String, + /// The projections whose read shape the crate holds: each one's module, file text and the + /// types it exports. + pub shapes: Vec<(String, String, Vec)>, + pub operations: Vec, + /// The generated crates it names. + pub deps: BTreeSet, +} + +/// The Rust path of the planned object `node`, from the crate `current`. +fn type_path( + plan: &Plan, + node: NodeId, + current: &str, + deps: &mut BTreeSet, +) -> Option { + let s = plan.structs.iter().find(|s| s.node == node)?; + if s.crate_name == current { + return Some(format!("crate::{}", s.type_name)); + } + deps.insert(s.crate_name.clone()); + Some(format!("{}::{}", s.crate_name, s.type_name)) +} + +fn is_true(tree: &Tree, node: NodeId, attr: &str) -> bool { + tree.attr(node, attr).and_then(serde_json::Value::as_bool) == Some(true) +} + +/// The shipped [`ContractTypesParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let tree = ctx.tree; + let index = ObjectIndex::build(tree, ctx.root); + let packages: Vec<_> = rules_names_of( + tree, + ctx.root, + &index, + &ctx.collection.config.rules, + &|_| true, + ) + .into_iter() + .filter(|p| !p.operations.is_empty()) + .collect(); + if packages.is_empty() { + return Ok(Vec::new()); + } + + // The projections an operation returns get a read shape; no other projection is planned, + // so one the operations never reach cannot fail the run. + let mut shapes: HashSet = HashSet::new(); + for p in &packages { + for o in &p.operations { + if let Some(out) = index.ref_target(tree, o.node, ATTR_OUTPUT_REF) + && tree.node(out).sub_type == SUB_PROJECTION + && !tree.node(out).is_abstract + // A served projection's read shape is in its model crate already. + && !is_served_read(tree, out) + { + shapes.insert(out); + } + } + } + let base = Plan::of(ctx)?; + let plan = Plan::with_projections(ctx, CONTRACT_SUFFIX, &shapes)?; + check_model_crates_unmoved(&base, &plan)?; + let selected = base.selected_crates(ctx.entities)?; + + let mut crates: BTreeMap = BTreeMap::new(); + for p in packages { + // A run limited to some entities writes the contract crates of their packages only. + if selected + .as_ref() + .is_some_and(|sel| !sel.contains(&crate_name(&p.package))) + { + continue; + } + let name = format!("{}{CONTRACT_SUFFIX}", crate_name(&p.package)); + if base.crates.contains_key(&name) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "the contract crate of {:?} and a model crate are both {name}", + p.package + ), + )); + } + let mut stems: BTreeMap = BTreeMap::new(); + let mut ops = Vec::new(); + let mut deps = BTreeSet::new(); + for o in p.operations { + let stem = type_ident(&o.name); + if let Some(other) = stems.insert(stem.clone(), o.name.clone()) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "the operations {other:?} and {:?} of {:?} would both be named {stem}", + o.name, p.package + ), + )); + } + let resolve = |attr: &str, deps: &mut BTreeSet| { + match index + .ref_target(tree, o.node, attr) + { + None => Ok(None), + Some(target) => type_path(&plan, target, &name, deps).map(Some).ok_or_else(|| { + GenError::new( + ERR_UNSUPPORTED, + format!( + "the operation {} names {} in @{attr}, which is not a concrete entity, value object or projection the Rust generators write", + o.name, + tree.resolution_key(target) + ), + ) + }), + } + }; + let input = resolve(ATTR_INPUT_REF, &mut deps)?; + let output = resolve(ATTR_OUTPUT_REF, &mut deps)?; + let mut variants: BTreeMap = BTreeMap::new(); + let mut errors = Vec::new(); + for code in &o.errors { + let v = type_ident(code); + if let Some(other) = variants.insert(v.clone(), code.clone()) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "the business errors {other:?} and {code:?} of {} would both be the Rust variant {v}", + o.name + ), + )); + } + errors.push((code.clone(), v)); + } + ops.push(OperationContract { + many: is_true(tree, o.node, ATTR_MANY), + kind: o.kind, + stem, + input, + output, + errors, + name: o.name, + }); + } + crates.insert( + name.clone(), + ContractCrate { + name, + package: p.package, + shapes: Vec::new(), + operations: ops, + deps, + }, + ); + } + + // The read shapes, each in its package's contract crate. + for (cname, cplan) in &plan.crates { + if !cname.ends_with(CONTRACT_SUFFIX) || base.crates.contains_key(cname) { + continue; + } + // A projection of a package the run did not select is not written. + if selected + .as_ref() + .is_some_and(|sel| !sel.contains(&crate_name(&cplan.package))) + { + continue; + } + // A package that declares no operation still holds the read shape of a projection + // another package's operation returns. + let c = crates + .entry(cname.clone()) + .or_insert_with(|| ContractCrate { + name: cname.clone(), + package: cplan.package.clone(), + shapes: Vec::new(), + operations: Vec::new(), + deps: BTreeSet::new(), + }); + // A std type the crate's own types shadow is spelled by its full path. + let shadowed: BTreeSet = cplan + .structs + .iter() + .flat_map(|&i| { + let s = &plan.structs[i]; + std::iter::once(s.type_name.clone()) + .chain(s.enums.iter().map(|e| e.type_name.clone())) + }) + .filter(|n| PRELUDE_TYPES.contains(&n.as_str())) + .collect(); + let mut support = false; + for &i in &cplan.structs { + let s = &plan.structs[i]; + let mut exports = vec![s.type_name.clone()]; + exports.extend(s.enums.iter().map(|e| e.type_name.clone())); + support |= s + .fields + .iter() + .any(|f| matches!(f.ty, Ty::Decimal | Ty::Duration)); + let text = parts.shape_file(&plan, s, cname, &shadowed)?; + c.shapes.push((s.module(), text, exports)); + } + c.shapes.sort_by(|a, b| a.0.cmp(&b.0)); + c.deps.extend(cplan.deps.iter().cloned()); + if support { + c.deps.insert(SUPPORT_CRATE.to_string()); + } + } + + let mut files = Vec::new(); + if !crates.is_empty() { + files.extend(parts.errors_crate()); + } + for c in crates.values() { + let name = &c.name; + for (module, text, _) in &c.shapes { + files.push(EmittedFile::new( + format!("{name}/src/{module}.rs"), + text.clone(), + )); + } + if !c.operations.is_empty() { + files.push(EmittedFile::new( + format!("{name}/src/{OPERATIONS_MODULE}.rs"), + parts.operations_file(c)?, + )); + } + files.push(EmittedFile::new( + format!("{name}/Cargo.toml"), + parts.manifest(c), + )); + files.push(EmittedFile::new( + format!("{name}/rustfmt.toml"), + RUSTFMT_TOML.to_string(), + )); + files.push(EmittedFile::new( + format!("{name}/src/lib.rs"), + parts.lib_file(c), + )); + } + Ok(files) +} + +/// The model crates the entity generator writes must be the same with the projections planned: +/// a shared enum only a projection uses would otherwise be one the entity generator never +/// writes. +fn check_model_crates_unmoved(base: &Plan, plan: &Plan) -> Result<(), GenError> { + for (cname, c) in &plan.crates { + let Some(b) = base.crates.get(cname) else { + continue; + }; + for (_, e) in &c.shared_enums { + if !b + .shared_enums + .iter() + .any(|(_, x)| x.type_name == e.type_name) + { + return Err(GenError::new( + ERR_UNSUPPORTED, + format!( + "the shared enum {} is used only by a projection an operation returns, so the entity generator does not write it; give an entity or value object a field of it", + e.type_name + ), + )); + } + } + } + Ok(()) +} + +// ---- emit ---------------------------------------------------------------------------------- + +/// The shipped [`ContractTypesParts::errors_crate`]: `meta_contract`, the wire error codes, +/// statuses and bodies every contract crate names. +pub fn errors_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, CONTRACT_CRATE); + m.entry( + "description", + &toml_string("The wire error contract of the generated MetaObjects REST API: codes, statuses and bodies."), + ); + m.blank().table("dependencies"); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + let file = + |name: &str, text: String| EmittedFile::new(format!("{CONTRACT_CRATE}/{name}"), text); + vec![ + file("Cargo.toml", m.finish()), + file("rustfmt.toml", RUSTFMT_TOML.to_string()), + file("src/lib.rs", fixed(BANNER, CONTRACT_RS)), + ] +} + +/// The shipped [`ContractTypesParts::manifest`]. +pub fn cargo_toml(c: &ContractCrate) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, &c.name); + let package = if c.package.is_empty() { + "the model's" + } else { + c.package.as_str() + }; + m.entry( + "description", + &toml_string(&format!( + "The contract types of the declared operations of the MetaObjects package {package}." + )), + ); + m.blank().table("dependencies"); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + let mut deps = c.deps.clone(); + deps.insert(CONTRACT_CRATE.to_string()); + for dep in &deps { + m.entry(dep, &sibling_dep(dep)); + } + m.finish() +} + +/// The shipped [`ContractTypesParts::lib_file`]. +pub fn lib_file(c: &ContractCrate) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); + if c.package.is_empty() { + w.line("//! The contract types of the operations of the MetaObjects model that declares no package."); + } else { + w.line(format!( + "//! The contract types of the operations of the MetaObjects package `{}`.", + c.package + )); + } + w.line("//!"); + w.line( + "//! `operations` holds what each operation takes, returns and answers an error with; an", + ); + w.line("//! entity's own shapes are in its model crate. The wire error bodies are `meta_contract`'s."); + w.blank(); + for (module, _, _) in &c.shapes { + w.line(format!("mod {module};")); + } + if !c.operations.is_empty() { + w.line(format!("pub mod {OPERATIONS_MODULE};")); + } + if !c.shapes.is_empty() { + w.blank(); + for (module, _, exports) in &c.shapes { + for e in exports { + w.line(format!("pub use {module}::{e};")); + } + } + } + w.finish().expect("a lib.rs opens no block") +} + +fn std_name(shadowed: &BTreeSet, short: &str, full: &str) -> String { + if shadowed.contains(short) { + full.to_string() + } else { + short.to_string() + } +} + +fn ty_text(ty: &Ty, current: &str, shadowed: &BTreeSet) -> String { + match ty { + Ty::Str => std_name(shadowed, "String", "std::string::String"), + Ty::Prim(p) => (*p).to_string(), + Ty::Ip => "std::net::IpAddr".to_string(), + Ty::Decimal => format!("{SUPPORT_CRATE}::wire::Decimal"), + Ty::Duration => format!("{SUPPORT_CRATE}::wire::Duration"), + Ty::Ref(r) if r.crate_name == current => format!("crate::{}", r.type_name), + Ty::Ref(r) => format!("{}::{}", r.crate_name, r.type_name), + Ty::Map(v) => format!( + "std::collections::BTreeMap<{}, {}>", + std_name(shadowed, "String", "std::string::String"), + ty_text(v, current, shadowed) + ), + } +} + +/// A read member's type: optional when the model lets it be absent (a credential always is). +fn member_type(f: &FieldPlan, current: &str, shadowed: &BTreeSet) -> String { + let mut text = ty_text(&f.ty, current, shadowed); + if f.boxed { + text = format!("{}<{text}>", std_name(shadowed, "Box", "std::boxed::Box")); + } + if f.array { + text = format!("{}<{text}>", std_name(shadowed, "Vec", "std::vec::Vec")); + } + if f.optional || f.credential { + text = format!( + "{}<{text}>", + std_name(shadowed, "Option", "std::option::Option") + ); + } + text +} + +/// The shipped [`ContractTypesParts::shape_file`]: a projection's read shape, a row as a +/// service returns it, read the way the entity generator reads one (the same names, member +/// types and `wire.nullMembers`), and the enums its fields declare. A projection is read-only, +/// so it has nothing a caller sends and no `validate()`. +pub fn shape_file( + plan: &Plan, + s: &StructPlan, + current: &str, + shadowed: &BTreeSet, +) -> Result { + let mut items = vec![item(|w| read_struct(w, plan, s, current, shadowed)).map_err(wrap)?]; + for e in &s.enums { + items.push(item(|w| enum_item(w, e)).map_err(wrap)?); + } + Ok(file(BANNER, &items)) +} + +fn read_struct( + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + current: &str, + shadowed: &BTreeSet, +) { + if let Some(doc) = &s.doc { + w.doc(doc); + } + w.line("#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]"); + if s.fields.is_empty() { + w.line(format!("pub struct {} {{}}", s.type_name)); + return; + } + w.block(format!("pub struct {} {{", s.type_name), |w| { + for f in &s.fields { + if let Some(doc) = &f.doc { + w.doc(doc); + } + let mut attrs: Vec = Vec::new(); + if f.bare_ident() != f.wire { + attrs.push(format!("rename = {}", literal(&f.wire))); + } + if f.optional || f.credential { + // A row follows the project's `wire.nullMembers`; a credential is never part + // of one. + if f.credential { + attrs.push("default".to_string()); + } + if f.credential || plan.null_members == NullMembers::Omit { + attrs.push("skip_serializing_if = \"Option::is_none\"".to_string()); + } + } + // rustfmt breaks an attribute's arguments without a trailing comma, so arguments + // that do not fit one line are written as one attribute each. + let joined = format!("#[serde({})]", attrs.join(", ")); + if attrs.is_empty() { + } else if w.fits(&joined) { + w.line(joined); + } else { + for a in attrs { + w.line(format!("#[serde({a})]")); + } + } + w.line(format!( + "pub {}: {},", + f.ident, + member_type(f, current, shadowed) + )); + } + }); +} + +/// An enum a projection's field declares, written as the entity generator writes one: its +/// variants serialize as the member symbols. +fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { + if let Some(doc) = &e.doc { + w.doc(doc); + } + w.line( + "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]", + ); + w.block(format!("pub enum {} {{", e.type_name), |w| { + for m in &e.members { + if m.variant != m.wire { + w.line(format!("#[serde(rename = {})]", literal(&m.wire))); + } + w.line(format!("{},", m.variant)); + } + }); + w.blank(); + w.block(format!("impl {} {{", e.type_name), |w| { + w.line("/// The wire spelling of the member."); + w.block("pub const fn as_str(self) -> &'static str {", |w| { + w.block("match self {", |w| { + for m in &e.members { + w.line(format!( + "{}::{} => {},", + e.type_name, + m.variant, + literal(&m.wire) + )); + } + }); + }); + }); +} + +fn wrap(e: impl std::fmt::Display) -> GenError { + GenError::new(ERR_UNSUPPORTED, e.to_string()) +} + +/// The shipped [`ContractTypesParts::operations_file`], through `parts`. +pub fn operations_file( + parts: &P, + c: &ContractCrate, +) -> Result { + let mut items = Vec::new(); + items.push( + item(|w| { + w.line("//! What each declared operation takes, returns and answers an error with."); + w.blank(); + let mut names = vec!["ErrorBody", "OperationCode"]; + if c.operations.iter().any(|o| o.errors.is_empty()) { + names.insert(1, "NoBusinessError"); + } + w.use_list(CONTRACT_CRATE, &names); + }) + .map_err(wrap)?, + ); + for o in &c.operations { + items.push(item(|w| parts.operation_item(w, o)).map_err(wrap)?); + } + Ok(file(BANNER, &items)) +} + +/// The shipped [`ContractTypesParts::operation_item`]. +pub fn operation_item(w: &mut CodeWriter, o: &OperationContract) { + let stem = &o.stem; + let what = format!("`{}` (a {})", o.name, o.kind.as_str()); + if let Some(input) = &o.input { + w.prose(&format!("What {what} takes: its `@inputRef`.")); + w.line(format!("pub type {stem}Input = {input};")); + w.blank(); + } + if let Some(output) = &o.output { + let ty = if o.many { + format!("Vec<{output}>") + } else { + output.clone() + }; + w.prose(&format!( + "What {what} returns: its `@outputRef`{}.", + if o.many { ", a list (`@many`)" } else { "" } + )); + w.line(format!("pub type {stem}Output = {ty};")); + w.blank(); + } + let business = format!("{stem}BusinessError"); + if o.errors.is_empty() { + w.prose(&format!("The business errors of {what}: it declares none.")); + w.line(format!("pub type {business} = NoBusinessError;")); + } else { + w.prose(&format!( + "A business error the body of {what} may return (`@errors`), written as its code." + )); + w.line("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]"); + w.block(format!("pub enum {business} {{"), |w| { + for (code, v) in &o.errors { + w.line(format!("#[serde(rename = {})]", literal(code))); + w.line(format!("{v},")); + } + }); + w.blank(); + w.block(format!("impl {business} {{"), |w| { + w.doc("Every one, in declaration order."); + w.assign( + &format!("pub const ALL: &[{business}] ="), + vec![ + list( + "&[", + o.errors.iter().map(|(_, v)| format!("{business}::{v}")), + "]", + ), + ";".into(), + ], + ); + w.blank().doc("Its wire code."); + w.line("#[must_use]"); + w.block("pub const fn code(self) -> &'static str {", |w| { + w.block("match self {", |w| { + for (code, v) in &o.errors { + w.line(format!("{business}::{v} => {},", literal(code))); + } + }); + }); + }); + } + w.blank(); + w.prose(&format!( + "The error body {what} answers with: a fixed code or one of its business errors." + )); + w.line(format!( + "pub type {stem}Error = ErrorBody>;" + )); +} diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index 3ec99ba6a9..d89c84376c 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -28,6 +28,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use metaobjects_codegen::engine::{OWNED_GENERATORS_DIR, OWNED_MAIN, OWNED_MANIFEST}; +use metaobjects_codegen::writer::{CodeWriter, Manifest, toml_string}; /// A shipped generator `eject` can hand over. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -45,6 +46,10 @@ pub struct Reference { pub layer: &'static str, /// The shipped generators it builds on: a project's generator list names them too. pub needs: &'static [&'static str], + /// Run only when the project's generator list names it: `cargo meta init` leaves it out + /// unless asked, and a project with no list does not run it. The transport is one: it + /// brings a web framework into the build. + pub opt_in: bool, /// One line for `gen --list`. pub summary: &'static str, /// The shipped source, which is also the owned copy's text. @@ -73,6 +78,7 @@ pub const REFERENCES: &[Reference] = &[ Reference { name: "entity", tier: "native", + opt_in: false, layer: "model", module: "entity", type_name: "EntityGenerator", @@ -81,9 +87,83 @@ pub const REFERENCES: &[Reference] = &[ objects, create and patch inputs, validate()", source: include_str!("entity.rs"), }, + Reference { + name: "rules-names", + tier: "native", + opt_in: false, + layer: "model", + module: "rules_names", + type_name: "RulesNamesGenerator", + needs: &["entity"], + summary: "rules crates, one per package with a lifecycle or an operation: states, \ + transitions, derived commands, operations, permissions and business errors as \ + enums (ADR-0067 layer 0; needs entity)", + source: include_str!("rules_names.rs"), + }, + Reference { + name: "contract-types", + tier: "native", + opt_in: false, + layer: "model", + module: "contract_types", + type_name: "ContractTypesGenerator", + needs: &["entity"], + summary: "contract crates, one per package with a declared operation: each operation's \ + input, output, business errors and error body, the read shape of a projection \ + it returns, and the shared wire error crate (ADR-0067 layer 1; needs entity)", + source: include_str!("contract_types.rs"), + }, + Reference { + name: "repository", + tier: "native", + opt_in: false, + layer: "persistence", + module: "repository", + type_name: "RepositoryGenerator", + needs: &["entity"], + summary: "store crates, one per package with stored entities: each entity's table and \ + its list, count, get, create, update, delete and guarded lifecycle update over \ + sqlx, on Postgres and SQLite, and the shared data-access crate (needs entity)", + source: include_str!("repository.rs"), + }, + Reference { + name: "service", + tier: "native", + opt_in: false, + layer: "service", + module: "service", + type_name: "ServiceGenerator", + needs: &["entity", "rules-names", "contract-types", "repository"], + summary: "service crates, one per package with stored entities: each operation in one \ + transaction, with the policy, body, hook and event traits it calls, the \ + lifecycle checks and the declared operations (ADR-0067 layer 4; needs entity, \ + rules-names, contract-types and repository)", + source: include_str!("service.rs"), + }, + Reference { + name: "service-routes", + tier: "native", + opt_in: true, + layer: "api", + module: "service_routes", + type_name: "ServiceRoutesGenerator", + needs: &[ + "entity", + "rules-names", + "contract-types", + "repository", + "service", + ], + summary: "transport crates, one per package with a service: an axum router whose each \ + route reads its request, calls one service operation and sends what it \ + answered, under the shared REST contract (ADR-0067 layer 5; needs service and \ + the four it builds on)", + source: include_str!("service_routes.rs"), + }, Reference { name: "client", tier: "native", + opt_in: false, layer: "client", module: "client", type_name: "ClientGenerator", @@ -95,6 +175,7 @@ pub const REFERENCES: &[Reference] = &[ Reference { name: "commands", tier: "native", + opt_in: false, layer: "client", module: "commands", type_name: "CommandsGenerator", @@ -103,6 +184,44 @@ pub const REFERENCES: &[Reference] = &[ over the client (needs entity and client; Rust only)", source: include_str!("commands.rs"), }, + Reference { + name: "render-helper", + tier: "native", + opt_in: false, + layer: "capability", + module: "render_helper", + type_name: "RenderHelperGenerator", + needs: &["entity"], + summary: "prompt crates, one per package with templates: a typed render function per \ + template.output and template.prompt, drift-checked against its payload at \ + build time (needs entity)", + source: include_str!("render_helper.rs"), + }, + Reference { + name: "output-parser", + tier: "native", + opt_in: false, + layer: "capability", + module: "output_parser", + type_name: "OutputParserGenerator", + needs: &["entity"], + summary: "parser crates, one per package with responding prompts: a strict parse and a \ + tolerant extract of each template.prompt's reply into its @responseRef type \ + (needs entity)", + source: include_str!("output_parser.rs"), + }, + Reference { + name: "output-prompt", + tier: "native", + opt_in: false, + layer: "capability", + module: "output_prompt", + type_name: "OutputPromptGenerator", + needs: &[], + summary: "format crates, one per package with responding prompts: the output-format \ + fragment that tells a model how to shape its answer", + source: include_str!("output_prompt.rs"), + }, ]; /// The shipped generator of that name. @@ -310,10 +429,10 @@ impl EngineSource { } } - /// The dependency line for one engine crate, as written in `codegen/Cargo.toml`. - fn dependency(&self, name: &str) -> String { + /// The requirement on one engine crate, as written in `codegen/Cargo.toml`. + fn requirement(&self, name: &str) -> String { match self { - EngineSource::Registry => format!("{name} = \"={}\"", env!("CARGO_PKG_VERSION")), + EngineSource::Registry => toml_string(&format!("={}", env!("CARGO_PKG_VERSION"))), EngineSource::Path(root) => { // `codegen/Cargo.toml` sits one directory below the project root. let base = if root.is_absolute() { @@ -321,116 +440,120 @@ impl EngineSource { } else { Path::new("..").join(root) }; - format!("{name} = {{ path = {} }}", toml_string(&base.join(name))) + format!("{{ path = {} }}", toml_path(&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)), + Some(r) => format!("{{ git = {}, rev = {} }}", toml_string(url), toml_string(r)), + None => format!("{{ git = {} }}", toml_string(url)), }, } } - fn note(&self) -> &'static str { + /// The comment above the engine dependencies, one line each. + fn note(&self) -> &'static [&'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" - } + EngineSource::Registry => &[ + "The engine is the crates.io release this project ejected from, pinned exactly: an", + "owned copy is that release's source. Upgrade the three versions together, then", + "compare each copy with `cargo meta gen --list`. To build against a checkout or a", + "git revision instead, replace each line with `{ path = \"...\" }` or", + "`{ git = \"...\", rev = \"...\" }`, or eject with `--engine`.", + ], + EngineSource::Path(_) => &[ + "The engine is a checkout of the repository's `server/rust`. Change the three paths", + "if it moves, or point them at a git revision or a crates.io release.", + ], + EngineSource::Git { .. } => &[ + "The engine is a git revision of the repository. Change the three entries to move to", + "another revision, a checkout (`path`) or a crates.io release.", + ], } } } -/// 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('\\', "/"); - toml_str(&text) +/// A path as a TOML basic string, with `/` separators on every platform. +fn toml_path(path: &Path) -> String { + toml_string(&path.to_string_lossy().replace('\\', "/")) } /// 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\ - [package]\n\ - name = \"codegen\"\n\ - version = \"0.0.0\"\n\ - edition = \"2024\"\n\ - publish = false\n\ - \n\ - [[bin]]\n\ - name = \"codegen\"\n\ - path = \"main.rs\"\n\ - \n\ - {}\ - [dependencies]\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\ - # The generators run on every `cargo meta gen`: build them optimized, once.\n\ - [profile.dev]\n\ - opt-level = 2\n\ - debug = false\n\ - \n\ - # Its own workspace, so an enclosing one neither claims nor rejects it.\n\ - [workspace]\n", - engine.note(), - engine.dependency("metaobjects"), - engine.dependency("metaobjects-cli"), - engine.dependency("metaobjects-codegen"), - ) + let mut m = Manifest::new(); + m.comment("The generators this project owns (`cargo meta eject`). This crate is yours."); + m.comment("`cargo meta gen` and `cargo meta verify` build and run it while it exists."); + m.table("package"); + m.entry("name", &toml_string("codegen")); + m.entry("version", &toml_string("0.0.0")); + m.entry("edition", &toml_string("2024")); + m.entry("publish", "false"); + m.blank().table("[bin]"); + m.entry("name", &toml_string("codegen")); + m.entry("path", &toml_string("main.rs")); + m.blank(); + for line in engine.note() { + m.comment(line); + } + m.table("dependencies"); + for name in ["metaobjects", "metaobjects-cli", "metaobjects-codegen"] { + m.entry(name, &engine.requirement(name)); + } + m.comment("What the shipped generators themselves import. Add your own beside it."); + m.entry( + "serde_json", + r#"{ version = "1", features = ["preserve_order"] }"#, + ); + m.blank() + .comment("The generators run on every `cargo meta gen`: build them optimized, once."); + m.table("profile.dev"); + m.entry("opt-level", "2"); + m.entry("debug", "false"); + m.blank() + .comment("Its own workspace, so an enclosing one neither claims nor rejects it."); + m.table("workspace"); + m.finish() } /// The owned crate's generator list, with `owned` taken from `generators/` and every other /// generator shipped. pub fn scaffold_main(owned: &[&Reference]) -> String { - let mut out = String::from( - "//! The generators `cargo meta gen` and `cargo meta verify` run for this project.\n\ - //!\n\ - //! This file is yours. Each module under `generators/` is a copy `cargo meta eject` made\n\ - //! of the shipped generator of that name; edit it freely. Keep each generator in the\n\ - //! list once: its owned copy or the shipped one, never both (they write the same files).\n\ - \n\ - use metaobjects_codegen::Generator;\n\ - \n\ - mod generators {\n", + let mut w = CodeWriter::new(); + w.line("//! The generators `cargo meta gen` and `cargo meta verify` run for this project."); + w.line("//!"); + w.line( + "//! This file is yours. Each module under `generators/` is a copy `cargo meta eject` made", ); - for r in owned { - out.push_str(&format!(" pub mod {};\n", r.module)); - } - out.push_str("}\n\nfn main() {\n let generators: Vec> = vec![\n"); - for r in REFERENCES { - let entry = if owned.contains(&r) { - r.owned_entry() - } else { - r.shipped_entry() - }; - out.push_str(&format!(" {entry},\n")); - } - out.push_str(" ];\n std::process::exit(metaobjects_cli::owned_main(generators));\n}\n"); - out + w.line("//! of the shipped generator of that name; edit it freely. Keep each generator in the"); + w.line( + "//! list once: its owned copy or the shipped one, never both (they write the same files).", + ); + w.blank(); + w.line("use metaobjects_codegen::Generator;"); + w.blank(); + w.block("mod generators {", |w| { + for r in owned { + w.line(format!("pub mod {};", r.module)); + } + }); + w.blank(); + w.block("fn main() {", |w| { + w.block_with( + "let generators: Vec> = vec![", + "];", + |w| { + for r in REFERENCES { + let entry = if owned.contains(&r) { + r.owned_entry() + } else { + r.shipped_entry() + }; + w.line(format!("{entry},")); + } + }, + ); + w.line("std::process::exit(metaobjects_cli::owned_main(generators));"); + }); + w.finish() + .expect("the owned main.rs closes every block it opens") } fn write_new(path: &Path, text: &str) -> Result<(), EjectError> { diff --git a/server/rust/metaobjects-codegen/src/emitted/client_transport.rs b/server/rust/metaobjects-codegen/src/emitted/client_transport.rs new file mode 100644 index 0000000000..f94d224900 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/client_transport.rs @@ -0,0 +1,265 @@ +//! The transport every generated client crate uses: one HTTP client, the list query, and +//! the error a call fails with. It follows the REST contract every MetaObjects server +//! generator implements, whatever language the server is written in. + +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +/// The HTTP library underneath, so a caller can set a client up without naming it as a +/// dependency of its own. +pub use reqwest; + +/// What a call returns. +pub type Result = std::result::Result; + +/// Why a call failed. +#[derive(Debug)] +pub enum Error { + /// The request did not get an answer. + Transport(reqwest::Error), + /// The server refused the request. `code` and `message` are its error body's `error` and + /// `message` members, when it sent them; `body` is the body as it arrived. + Api { status: u16, code: Option, message: Option, body: String }, + /// The server answered, and the body is not what the model says a row looks like. + Decode { status: u16, message: String }, +} + +impl Error { + /// The HTTP status of the answer, when there was one. + pub fn status(&self) -> Option { + match self { + Error::Transport(e) => e.status().map(|s| s.as_u16()), + Error::Api { status, .. } | Error::Decode { status, .. } => Some(*status), + } + } + + /// The server's error code (`not_found`, `validation`, ...), when it sent one. + pub fn code(&self) -> Option<&str> { + match self { + Error::Api { code, .. } => code.as_deref(), + _ => None, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Transport(e) => write!(f, "the request failed: {e}"), + Error::Api { status, code, message, .. } => { + write!(f, "the server answered {status}")?; + if let Some(code) = code { + write!(f, " {code}")?; + } + if let Some(message) = message { + write!(f, ": {message}")?; + } + Ok(()) + } + Error::Decode { status, message } => { + write!(f, "the server answered {status} with a body that does not fit: {message}") + } + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Transport(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Transport(e) + } +} + +/// The API's address and the HTTP client that reaches it. +#[derive(Debug, Clone)] +pub struct Client { + http: reqwest::Client, + base: String, +} + +impl Client { + /// A client for the API at `base_url`: the server's address and the prefix its routes + /// are mounted under, as in `https://example.com/api`. + pub fn new(base_url: &str) -> Self { + Self::with_http(reqwest::Client::new(), base_url) + } + + /// The same, over an HTTP client you set up yourself (timeouts, headers, a proxy). + pub fn with_http(http: reqwest::Client, base_url: &str) -> Self { + Self { http, base: base_url.trim_end_matches('/').to_string() } + } + + /// The address every path is taken under. + pub fn base_url(&self) -> &str { + &self.base + } + + fn url(&self, path: &str) -> String { + format!("{}/{}", self.base, path) + } + + /// `GET path`, read as `T`. + pub async fn get(&self, path: &str) -> Result { + read(self.http.get(self.url(path)).send().await?).await + } + + /// `GET path?query`, read as `T`. + pub async fn list(&self, path: &str, query: &Query) -> Result { + read(self.http.get(self.url(path)).query(query.pairs()).send().await?).await + } + + /// `POST path` with a JSON body, read as `T`. + pub async fn post(&self, path: &str, body: &B) -> Result + where + B: Serialize + ?Sized, + T: DeserializeOwned, + { + read(self.http.post(self.url(path)).json(body).send().await?).await + } + + /// `PATCH path` with a JSON body, read as `T`. + pub async fn patch(&self, path: &str, body: &B) -> Result + where + B: Serialize + ?Sized, + T: DeserializeOwned, + { + read(self.http.patch(self.url(path)).json(body).send().await?).await + } + + /// `DELETE path`. + pub async fn delete(&self, path: &str) -> Result<()> { + let response = self.http.delete(self.url(path)).send().await?; + if response.status().is_success() { + return Ok(()); + } + Err(refusal(response).await) + } +} + +async fn read(response: reqwest::Response) -> Result { + let status = response.status(); + if !status.is_success() { + return Err(refusal(response).await); + } + let text = response.text().await?; + serde_json::from_str(&text) + .map_err(|e| Error::Decode { status: status.as_u16(), message: e.to_string() }) +} + +async fn refusal(response: reqwest::Response) -> Error { + let status = response.status().as_u16(); + let body = response.text().await.unwrap_or_default(); + let parsed: Option = serde_json::from_str(&body).ok(); + let member = |name: &str| { + parsed.as_ref().and_then(|v| v.get(name)).and_then(|v| v.as_str()).map(str::to_string) + }; + Error::Api { status, code: member("error"), message: member("message"), body } +} + +/// The order a sort puts rows in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// The order the model declares for the field (ascending when it declares none). + Default, + Ascending, + Descending, +} + +/// The query of a list request: filters, a sort and a window. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Query { + pairs: Vec<(String, String)>, +} + +impl Query { + pub fn new() -> Self { + Self::default() + } + + /// The query's parameters, in the order they were added, not yet percent-encoded. + pub fn pairs(&self) -> &[(String, String)] { + &self.pairs + } + + fn set(&mut self, name: &str, value: String) { + self.pairs.retain(|(n, _)| n != name); + self.pairs.push((name.to_string(), value)); + } + + /// Keep the rows whose `field` passes `op` against `value`. Filters add up: a row must + /// pass them all. + pub fn filter(&mut self, field: &str, op: &str, value: impl fmt::Display) { + self.pairs.push((format!("filter[{field}][{op}]"), value.to_string())); + } + + /// Keep the rows whose `field` is one of `values`. + pub fn filter_in(&mut self, field: &str, values: impl IntoIterator) { + let joined: Vec = values.into_iter().map(|v| v.to_string()).collect(); + self.filter(field, "in", joined.join(",")); + } + + /// Sort by `field`. A later sort replaces an earlier one: the contract has one sort key. + pub fn sort(&mut self, field: &str, direction: Direction) { + let value = match direction { + Direction::Default => field.to_string(), + Direction::Ascending => format!("{field}:asc"), + Direction::Descending => format!("{field}:desc"), + }; + self.set("sort", value); + } + + /// Return at most `rows` rows. + pub fn limit(&mut self, rows: u64) { + self.set("limit", rows.to_string()); + } + + /// Skip the first `rows` rows. + pub fn offset(&mut self, rows: u64) { + self.set("offset", rows.to_string()); + } + + /// Ask for the `{ rows, total }` answer a [`Page`] reads. + pub fn with_count(&mut self) { + self.set("withCount", "1".to_string()); + } +} + +/// One window of a list, and how many rows the filters match in all. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Page { + pub rows: Vec, + pub total: u64, +} + +/// The path of one row: `collection/id`, with the id percent-encoded. +pub fn row(collection: &str, id: impl fmt::Display) -> String { + format!("{collection}/{}", segment(&id.to_string())) +} + +/// The path of the rows related to one row: `collection/id/relation`. +pub fn related(collection: &str, id: impl fmt::Display, relation: &str) -> String { + format!("{}/{relation}", row(collection, id)) +} + +/// One path segment, percent-encoded: everything but RFC 3986's unreserved characters. +pub fn segment(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} diff --git a/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs b/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs new file mode 100644 index 0000000000..4cc5731000 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs @@ -0,0 +1,205 @@ +//! What every generated command crate uses: the body a command line describes, the query +//! its filters describe, and the error a command fails with. + +use std::fmt; +use std::io::Read; + +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::{Map, Value}; + +/// What a command returns: the server's answer as JSON (`null` when it sent none). +pub type Answer = Result; + +/// Why a command failed. +#[derive(Debug)] +pub enum Error { + /// The command line asks for something the model does not allow, or is not well formed. + Usage(String), + /// The body breaks rules of the model: one message per rule. Nothing was sent. + Invalid(Vec), + /// The call failed. + Api(meta_client::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Usage(message) => f.write_str(message), + Error::Invalid(messages) => write!(f, "the body is not valid: {}", messages.join("; ")), + Error::Api(e) => e.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Api(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: meta_client::Error) -> Self { + Error::Api(e) + } +} + +/// The body a `--json` argument gives: a JSON object, read from standard input when the +/// argument is `-`, and empty when there is no argument. +pub fn body(json: Option<&str>) -> Result, Error> { + let text = match json { + None => return Ok(Map::new()), + Some("-") => { + let mut text = String::new(); + std::io::stdin().read_to_string(&mut text).map_err(|e| { + Error::Usage(format!("cannot read the body from standard input: {e}")) + })?; + text + } + Some(text) => text.to_string(), + }; + match serde_json::from_str(&text) { + Ok(Value::Object(body)) => Ok(body), + Ok(_) => Err(Error::Usage("the body must be a JSON object".to_string())), + Err(e) => Err(Error::Usage(format!("the body is not JSON: {e}"))), + } +} + +/// Refuses a body member the model does not declare: a misspelled name must not be dropped +/// on the way to the server, which would refuse it too under its default setting. +pub fn known(body: &Map, members: &[&str]) -> Result<(), Error> { + let unknown: Vec<&str> = + body.keys().map(String::as_str).filter(|name| !members.contains(name)).collect(); + if unknown.is_empty() { + return Ok(()); + } + Err(Error::Usage(format!( + "the body sets {}, which the model does not declare (it declares: {})", + unknown.join(", "), + members.join(", ") + ))) +} + +/// Sets one member of the body from its flag, when the flag was given. +pub fn put( + body: &mut Map, + name: &str, + value: Option, +) -> Result<(), Error> { + if let Some(value) = value { + let value = serde_json::to_value(value) + .map_err(|e| Error::Usage(format!("the value of {name} cannot be sent: {e}")))?; + body.insert(name.to_string(), value); + } + Ok(()) +} + +/// Sets one array member of the body from its repeated flag, when it was given at all. +pub fn put_all( + body: &mut Map, + name: &str, + values: Vec, +) -> Result<(), Error> { + if values.is_empty() { + return Ok(()); + } + put(body, name, Some(values)) +} + +/// Reads the finished body as the model's type. +pub fn decode(body: Map) -> Result { + serde_json::from_value(Value::Object(body)) + .map_err(|e| Error::Usage(format!("the body does not fit the model: {e}"))) +} + +/// Refuses a body that breaks rules of the model. +pub fn check(found: Vec) -> Result<(), Error> { + if found.is_empty() { + return Ok(()); + } + Err(Error::Invalid(found.into_iter().map(|v| v.message).collect())) +} + +/// Adds the `--filter` tests to a query. A test is written `field:op=value`, and +/// `field=value` means `field:eq=value`. `allowed` is the model's allowlist. +pub fn filters( + query: &mut meta_client::Query, + tests: &[String], + allowed: &[(&str, &[&str])], +) -> Result<(), Error> { + for test in tests { + let Some((subject, value)) = test.split_once('=') else { + return Err(Error::Usage(format!("--filter {test}: expected field:op=value"))); + }; + let (field, op) = subject.split_once(':').unwrap_or((subject, "eq")); + let Some((_, ops)) = allowed.iter().find(|(name, _)| *name == field) else { + let names: Vec<&str> = allowed.iter().map(|(name, _)| *name).collect(); + return Err(Error::Usage(format!( + "--filter {test}: {field} is not a field this list filters on (it filters on: {})", + names.join(", ") + ))); + }; + if !ops.contains(&op) { + return Err(Error::Usage(format!( + "--filter {test}: {field} does not take {op} (it takes: {})", + ops.join(", ") + ))); + } + query.filter(field, op, value); + } + Ok(()) +} + +/// Adds the `--sort` to a query: `field`, `field:asc` or `field:desc`. `allowed` is the +/// model's allowlist. +pub fn sort( + query: &mut meta_client::Query, + spec: Option<&str>, + allowed: &[&str], +) -> Result<(), Error> { + let Some(spec) = spec else { + return Ok(()); + }; + let (field, direction) = match spec.split_once(':') { + None => (spec, meta_client::Direction::Default), + Some((field, "asc")) => (field, meta_client::Direction::Ascending), + Some((field, "desc")) => (field, meta_client::Direction::Descending), + Some(_) => { + return Err(Error::Usage(format!( + "--sort {spec}: expected field, field:asc or field:desc" + ))); + } + }; + if !allowed.contains(&field) { + return Err(Error::Usage(format!( + "--sort {spec}: {field} is not a field this list sorts on (it sorts on: {})", + allowed.join(", ") + ))); + } + query.sort(field, direction); + Ok(()) +} + +/// Adds the `--limit` and the `--offset` to a query. +pub fn window(query: &mut meta_client::Query, limit: Option, offset: Option) { + if let Some(limit) = limit { + query.limit(limit); + } + if let Some(offset) = offset { + query.offset(offset); + } +} + +/// What the server answered, as the JSON a command returns. +pub fn answer(found: &T) -> Answer { + serde_json::to_value(found) + .map_err(|e| Error::Usage(format!("the answer cannot be written as JSON: {e}"))) +} + +/// An answer as the text a command prints. +pub fn render(answer: &Value) -> String { + serde_json::to_string_pretty(answer).unwrap_or_else(|_| answer.to_string()) +} diff --git a/server/rust/metaobjects-codegen/src/emitted/contract.rs b/server/rust/metaobjects-codegen/src/emitted/contract.rs new file mode 100644 index 0000000000..6cd1a577e8 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/contract.rs @@ -0,0 +1,157 @@ +//! The wire error contract every generated route and the enforcing shell answer with +//! (docs/features/api-contract.md, ADR-0066 §6): the fixed codes, their HTTP statuses and the +//! error bodies. The `contract-types` generator's crates name an operation's errors through it. + +use serde::{Deserialize, Serialize}; + +/// A fixed wire error code: the five the enforcing shell answers with on its own, then the +/// six the REST contract's transport does. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + NotFound, + Forbidden, + InvalidTransition, + TransitionConditionFailed, + StateManaged, + Validation, + InvalidJson, + InvalidId, + MethodNotAllowed, + ConstraintViolation, + Internal, +} + +impl ErrorCode { + /// The codes the enforcing shell answers with on its own (ADR-0066 §6). + pub const SHELL: &[ErrorCode] = &[ + ErrorCode::NotFound, + ErrorCode::Forbidden, + ErrorCode::InvalidTransition, + ErrorCode::TransitionConditionFailed, + ErrorCode::StateManaged, + ]; + + /// The codes the REST contract's transport answers with. + pub const CONTRACT: &[ErrorCode] = &[ + ErrorCode::Validation, + ErrorCode::InvalidJson, + ErrorCode::InvalidId, + ErrorCode::MethodNotAllowed, + ErrorCode::ConstraintViolation, + ErrorCode::Internal, + ]; + + /// Its wire code. + #[must_use] + pub const fn code(self) -> &'static str { + match self { + ErrorCode::NotFound => "not_found", + ErrorCode::Forbidden => "forbidden", + ErrorCode::InvalidTransition => "invalid_transition", + ErrorCode::TransitionConditionFailed => "transition_condition_failed", + ErrorCode::StateManaged => "state_managed", + ErrorCode::Validation => "validation", + ErrorCode::InvalidJson => "invalid_json", + ErrorCode::InvalidId => "invalid_id", + ErrorCode::MethodNotAllowed => "method_not_allowed", + ErrorCode::ConstraintViolation => "constraint_violation", + ErrorCode::Internal => "internal", + } + } + + /// Its HTTP status. `None` for `constraint_violation`, which has none of its own: it is + /// [`ConstraintKind::status`] of the constraint the database refused. + #[must_use] + pub const fn status(self) -> Option { + match self { + ErrorCode::NotFound => Some(404), + ErrorCode::Forbidden => Some(403), + ErrorCode::InvalidTransition + | ErrorCode::TransitionConditionFailed + | ErrorCode::StateManaged => Some(409), + ErrorCode::Validation | ErrorCode::InvalidJson | ErrorCode::InvalidId => Some(400), + ErrorCode::MethodNotAllowed => Some(405), + ErrorCode::ConstraintViolation => None, + ErrorCode::Internal => Some(500), + } + } +} + +/// An operation's error code: a fixed one, or one of the business errors its body declares +/// (`@errors`). On the wire both are the bare code. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(untagged)] +pub enum OperationCode { + Fixed(ErrorCode), + Business(B), +} + +/// The business errors of an operation that declares none. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum NoBusinessError {} + +/// Every error body: a short code, and a human message that is not part of the contract. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ErrorBody { + pub error: C, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +/// One step of a path into a request body: a member name or an array index. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PathSegment { + Index(u64), + Key(String), +} + +/// One problem with a request body. A client treats a `code` it does not know as `custom`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ValidationIssue { + pub code: String, + pub path: Vec, + pub message: String, +} + +/// 400: the body failed its schema. Every issue is listed, not the first. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ValidationErrorBody { + /// Always [`ErrorCode::Validation`]. + pub error: ErrorCode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, + pub issues: Vec, +} + +/// The kind of constraint the database refused a write on. The body never names the SQL. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConstraintKind { + Unique, + ForeignKey, + Check, + NotNull, +} + +impl ConstraintKind { + /// The HTTP status a refusal on this kind of constraint answers with. + #[must_use] + pub const fn status(self) -> u16 { + match self { + ConstraintKind::Unique | ConstraintKind::ForeignKey => 409, + ConstraintKind::Check | ConstraintKind::NotNull => 400, + } + } +} + +/// 409 (`unique`, `foreign_key`) or 400 (`check`, `not_null`): the database refused the write. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConstraintViolationBody { + /// Always [`ErrorCode::ConstraintViolation`]. + pub error: ErrorCode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, + pub constraint: ConstraintKind, +} diff --git a/server/rust/metaobjects-codegen/src/emitted/http.rs b/server/rust/metaobjects-codegen/src/emitted/http.rs new file mode 100644 index 0000000000..fff0e8f861 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/http.rs @@ -0,0 +1,442 @@ +//! The REST mechanics the `service-routes` generator's crates share (ADR-0067 layer 5): how a +//! request becomes a call on a generated service, and how what the service answered becomes a +//! response. +//! +//! The routes are written into each package's transport crate; this crate holds only what every +//! one of them shares, so each refusal has one spelling in every app: the list query's named 400s +//! ([`list_query`]), `invalid_json`, `invalid_id`, `unknown_fields`, a `validation` 400 listing +//! every issue, `constraint_violation`, `method_not_allowed`, and a 500 that names nothing +//! (`internal`). It holds no rules: those are the service's. + +use axum::Json; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use meta_service::{Page, ServiceError}; +use meta_store::{Filter, Op, StoreError}; +use meta_support::validation::{self, Violation}; +// The list query reads decimals, durations and formats through these. +use meta_support::wire; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value, json}; + +mod list_query; + +pub use list_query::{FilterRule, Kind, ListQuery, ListSpec, Node, Refusal, Search, Sort, SortRule}; + +/// Who a request runs for, read from the request: the app's own authentication. The routes hand +/// the actor to the service untouched, which hands it to the policy, the bodies, the hooks and the +/// event hook. `()` is the source that finds no actor, which a policy may refuse. +pub trait ActorSource: Send + Sync + 'static { + fn actor(&self, headers: &HeaderMap) -> Option; +} + +impl ActorSource for () { + fn actor(&self, _headers: &HeaderMap) -> Option { + None + } +} + +/// An [`ActorSource`] that is a function of the headers. +pub struct ActorFn(pub F); + +impl ActorSource for ActorFn +where + F: Fn(&HeaderMap) -> Option + Send + Sync + 'static, +{ + fn actor(&self, headers: &HeaderMap) -> Option { + (self.0)(headers) + } +} + +/// What a body may carry, for one entity's create or update route. +pub struct BodySpec { + /// Every field the entity declares: any other key is unknown. + pub declared: &'static [&'static str], + /// The keys a create keeps. A declared key the client may not set is dropped, never refused. + pub create: &'static [&'static str], + /// The keys a create must carry, not null. + pub create_required: &'static [&'static str], + /// The keys an update keeps. + pub update: &'static [&'static str], + /// The keys an update may omit but may not set to null. + pub update_not_null: &'static [&'static str], + /// `api.unknownFields: reject` (the default): a body with an undeclared key is refused. + pub reject_unknown: bool, +} + +/// A response with a JSON body. +pub fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +fn refuse(status: StatusCode, code: &str) -> Response { + reply(status, json!({ "error": code })) +} + +/// `405 method_not_allowed`: the write verbs of a read-only route. +pub async fn method_not_allowed() -> Response { + refuse(StatusCode::METHOD_NOT_ALLOWED, "method_not_allowed") +} + +/// `400 invalid_id`: an `{id}` the key cannot hold. +pub fn invalid_id() -> Response { + refuse(StatusCode::BAD_REQUEST, "invalid_id") +} + +/// The whole-number key `text` spells: an optional `-` and ASCII digits with no leading zero, +/// no exponent, hex, plus sign, whitespace or negative zero, and in the key type's range. +pub fn int_key(text: &str) -> Result { + let digits = text.strip_prefix('-').unwrap_or(text); + let canonical = !digits.is_empty() + && digits.bytes().all(|b| b.is_ascii_digit()) + && (digits == "0" || !digits.starts_with('0')) + && text != "-0"; + match canonical.then(|| text.parse::().ok()).flatten() { + Some(key) => Ok(key), + None => Err(invalid_id()), + } +} + +/// A list query and whether its count was asked for, ready for a service's list call. +pub struct Listed { + pub query: meta_store::Query, + pub with_count: bool, +} + +/// Parse a list route's query string against `spec`: the store query, or the named 400. +pub fn list(raw: Option<&str>, spec: &ListSpec) -> Result { + let parsed = list_query::parse(raw.unwrap_or(""), spec) + .map_err(|r| reply(StatusCode::BAD_REQUEST, r.body()))?; + let mut filters: Vec = parsed.filter.map(filter).into_iter().collect(); + if let Some(search) = parsed.search { + let fields = search.fields.iter().map(|f| f.to_string()).collect(); + filters.push(Filter::Search { term: search.term, fields }); + } + let filter = match filters.len() { + 0 => None, + 1 => filters.pop(), + _ => Some(Filter::And(filters)), + }; + let sort = parsed + .sort + .map(|s| meta_store::Sort { field: s.field, descending: s.descending }) + .into_iter() + .collect(); + let query = meta_store::Query { filter, sort, limit: parsed.limit, offset: parsed.offset }; + Ok(Listed { query, with_count: parsed.with_count }) +} + +fn filter(node: Node) -> Filter { + match node { + Node::And(all) => Filter::And(all.into_iter().map(filter).collect()), + Node::Or(any) => Filter::Or(any.into_iter().map(filter).collect()), + Node::Leaf { field, op, value } => { + // The parser admits only the operators the store has. + let op = Op::of(&op).unwrap_or(Op::Eq); + Filter::Field { field, op, value } + } + } +} + +/// What a route answers: its response, either way. A refusal found before the service is +/// called is the `Err`, so a route reads each part of its request with `?`. +pub type Reply = Result; + +/// A list page: the rows, or `{ rows, total }` when the count was asked for. +pub fn page(out: Result, ServiceError>, secret: &[&str]) -> Reply { + Ok(match out { + Ok(Page { rows, total: None }) => answer(StatusCode::OK, &rows, secret), + Ok(Page { rows, total: Some(total) }) => match to_json(&rows, secret) { + Ok(rows) => reply(StatusCode::OK, json!({ "rows": rows, "total": total })), + Err(e) => internal(&e), + }, + Err(e) => error(e), + }) +} + +/// What an operation answered: `200` with it, less the credentials `secret` names. +pub fn ok(out: Result, secret: &[&str]) -> Reply { + send(StatusCode::OK, out, secret) +} + +/// What a create answered: `201` with the row, less the credentials `secret` names. +pub fn created(out: Result, secret: &[&str]) -> Reply { + send(StatusCode::CREATED, out, secret) +} + +fn send(status: StatusCode, out: Result, secret: &[&str]) -> Reply { + Ok(match out { + Ok(v) => answer(status, &v, secret), + Err(e) => error(e), + }) +} + +/// `204` on success, whatever the operation answered. +pub fn no_content(out: Result) -> Reply { + Ok(match out { + Ok(_) => StatusCode::NO_CONTENT.into_response(), + Err(e) => error(e), + }) +} + +/// `value` as JSON, with no credential `secret` names on any row in it. +fn to_json(value: &T, secret: &[&str]) -> Result { + let mut value = serde_json::to_value(value)?; + if !secret.is_empty() { + let strip = |row: &mut Value| { + if let Value::Object(m) = row { + for k in secret { + m.remove(*k); + } + } + }; + match &mut value { + Value::Array(rows) => rows.iter_mut().for_each(strip), + row => strip(row), + } + } + Ok(value) +} + +fn answer(status: StatusCode, value: &T, secret: &[&str]) -> Response { + match to_json(value, secret) { + Ok(body) => reply(status, body), + Err(e) => internal(&e), + } +} + +fn internal(e: &dyn std::fmt::Display) -> Response { + // The full error is the server's: the body names no SQL, table or value. + eprintln!("meta_http: internal error: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "internal") +} + +/// The response for a service error. +pub fn error(e: ServiceError) -> Response { + let status = StatusCode::from_u16(e.status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + match e { + ServiceError::Validation(violations) => validation_failed(issues(&violations)), + ServiceError::LimitTooLarge { max } => { + reply(status, json!({ "error": "limit_too_large", "maxLimit": max })) + } + ServiceError::Refused { code, message } => { + let mut body = json!({ "error": code }); + if let Some(m) = message { + body["message"] = Value::from(m); + } + reply(status, body) + } + ServiceError::Store(StoreError::UnknownField { field, .. }) + | ServiceError::Store(StoreError::BadValue { field, .. }) => { + let message = format!("'{field}' is not a value the store can hold"); + validation_failed(vec![issue("custom", &field, &message)]) + } + ServiceError::Store(StoreError::Database(db)) => match constraint(&db) { + Some((kind, status)) => { + reply(status, json!({ "error": "constraint_violation", "constraint": kind })) + } + None => internal(&db), + }, + ServiceError::Store(other) => internal(&other), + other if status.is_server_error() => internal(&other), + other => refuse(status, other.code()), + } +} + +/// The kind of constraint a database refused a write by, and its status: 409 for a conflict with +/// another row, 400 for the request's own value. +fn constraint(e: &sqlx::Error) -> Option<(&'static str, StatusCode)> { + use sqlx::error::ErrorKind; + let sqlx::Error::Database(db) = e else { return None }; + Some(match db.kind() { + ErrorKind::UniqueViolation => ("unique", StatusCode::CONFLICT), + ErrorKind::ForeignKeyViolation => ("foreign_key", StatusCode::CONFLICT), + ErrorKind::NotNullViolation => ("not_null", StatusCode::BAD_REQUEST), + ErrorKind::CheckViolation => ("check", StatusCode::BAD_REQUEST), + _ => return None, + }) +} + +/// `400 validation`, listing every issue. +fn validation_failed(issues: Vec) -> Response { + reply(StatusCode::BAD_REQUEST, json!({ "error": "validation", "issues": issues })) +} + +/// One issue: its code (Zod's name for the failure), the member's path and a sentence. +fn issue(code: &str, field: &str, message: &str) -> Value { + json!({ "code": code, "path": path(field), "message": message }) +} + +/// `outer[0].inner` as `["outer", 0, "inner"]`. +fn path(field: &str) -> Value { + let mut out = Vec::new(); + for part in field.split('.').filter(|p| !p.is_empty()) { + let mut rest = part; + if let Some(at) = rest.find('[') { + out.push(Value::from(&rest[..at])); + rest = &rest[at..]; + while let Some(close) = rest.find(']') { + match rest[1..close].parse::() { + Ok(n) => out.push(Value::from(n)), + Err(_) => out.push(Value::from(&rest[1..close])), + } + rest = &rest[close + 1..]; + } + } else { + out.push(Value::from(rest)); + } + } + Value::Array(out) +} + +/// The issues of the model's rules a value breaks, each by Zod's name for it. +pub fn issues(violations: &[Violation]) -> Vec { + violations + .iter() + .map(|v| { + let code = match v.rule { + validation::RULE_LENGTH | validation::RULE_ARRAY | validation::RULE_NUMERIC => { + // The checks say which bound was broken: "at least" is the lower one. + if v.message.contains("at least") { + "too_small" + } else { + "too_big" + } + } + validation::RULE_REGEX | validation::RULE_FORMAT => "invalid_format", + _ => "custom", + }; + issue(code, &v.field, &v.message) + }) + .collect() +} + +/// A request body as JSON, or `400 invalid_json`. +fn json_body(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|_| refuse(StatusCode::BAD_REQUEST, "invalid_json")) +} + +/// The members of a body the route keeps: `400 invalid_json`, a `validation` 400 for a body that +/// is not an object, `400 unknown_fields` (sorted) for an undeclared key under `reject`; then +/// only the `keep` keys. +fn members(bytes: &[u8], spec: &BodySpec, keep: &[&str]) -> Result, Response> { + let Value::Object(mut body) = json_body(bytes)? else { + let message = "the body must be a JSON object"; + return Err(validation_failed(vec![json!({ + "code": "invalid_type", + "path": [], + "message": message, + })])); + }; + if spec.reject_unknown { + let mut unknown: Vec<&str> = + body.keys().map(String::as_str).filter(|k| !spec.declared.contains(k)).collect(); + if !unknown.is_empty() { + unknown.sort_unstable(); + let fields = json!({ "error": "unknown_fields", "fields": unknown }); + return Err(reply(StatusCode::BAD_REQUEST, fields)); + } + } + body.retain(|k, _| keep.contains(&k.as_str())); + Ok(body) +} + +fn bind(body: Map) -> Result> { + serde_path_to_error::deserialize(Value::Object(body)).map_err(|e| { + let field = e.path().to_string(); + let field = if field == "." { String::new() } else { field }; + let message = e.inner().to_string(); + let code = if message.starts_with("unknown variant") { + "invalid_value" + } else if message.starts_with("missing field") || message.starts_with("invalid type") { + "invalid_type" + } else { + "custom" + }; + let field = match message.strip_prefix("missing field `") { + Some(rest) => rest.split('`').next().unwrap_or("").to_string(), + None => field, + }; + vec![issue(code, &field, &message)] + }) +} + +fn missing(field: &str) -> Value { + issue("invalid_type", field, &format!("'{field}' is required")) +} + +/// A create body as `C`. A required key that is absent or null is an issue, listed together with +/// every rule a present member breaks (checked through the update body `P` and `check`, since a +/// body missing a required member is no `C` to check). +pub fn create_body( + bytes: &[u8], + spec: &BodySpec, + check: impl Fn(&P) -> Vec, +) -> Result +where + C: DeserializeOwned, + P: DeserializeOwned, +{ + let body = members(bytes, spec, spec.create)?; + let absent: Vec<&str> = spec + .create_required + .iter() + .copied() + .filter(|k| body.get(*k).is_none_or(Value::is_null)) + .collect(); + if absent.is_empty() { + return bind(body).map_err(validation_failed); + } + let mut found: Vec = absent.iter().map(|k| missing(k)).collect(); + let mut present = body; + present.retain(|k, v| !v.is_null() && spec.update.contains(&k.as_str())); + if let Ok(partial) = bind::

(present) { + found.extend(issues(&check(&partial))); + } + Err(validation_failed(found)) +} + +/// An update body as `P`. A null on a member that may not be null is an issue, listed together +/// with every rule a present member breaks. +pub fn update_body

( + bytes: &[u8], + spec: &BodySpec, + check: impl Fn(&P) -> Vec, +) -> Result +where + P: DeserializeOwned, +{ + let mut body = members(bytes, spec, spec.update)?; + let nulls: Vec = body + .iter() + .filter(|(k, v)| v.is_null() && spec.update_not_null.contains(&k.as_str())) + .map(|(k, _)| k.clone()) + .collect(); + if nulls.is_empty() { + return bind(body).map_err(validation_failed); + } + let mut found: Vec = nulls.iter().map(|k| missing(k)).collect(); + body.retain(|k, _| !nulls.contains(k)); + if let Ok(partial) = bind::

(body) { + found.extend(issues(&check(&partial))); + } + Err(validation_failed(found)) +} + +/// An operation's input as `I`, from a JSON body (an empty one is `{}`). +pub fn input_body(bytes: &[u8]) -> Result { + let value = if bytes.iter().all(u8::is_ascii_whitespace) { + Value::Object(Map::new()) + } else { + json_body(bytes)? + }; + let Value::Object(body) = value else { + return Err(validation_failed(vec![issue( + "invalid_type", + "", + "the body must be an object", + )])); + }; + bind(body).map_err(validation_failed) +} diff --git a/server/rust/metaobjects-codegen/src/emitted/list_query.rs b/server/rust/metaobjects-codegen/src/emitted/list_query.rs new file mode 100644 index 0000000000..94d53e1d39 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/list_query.rs @@ -0,0 +1,760 @@ +//! How a list route reads its query string: the filter tree (and/or groups to a depth cap), +//! the search, the sort and the page, or the named 400 it refuses with. +//! +//! A port of the TypeScript reference parser, held to it by the shared parse cases of +//! `fixtures/list-query-conformance/`. The parse runs before any store sees the query, and the +//! values it hands on are neutral: a number is a JSON number, a decimal its canonical text, an +//! instant timestamp its UTC spelling, and every other value the text as sent. +//! +//! Faults are found, and the first reported, in this order: bare field parameters; `limit`, then +//! `offset`; the filter, depth-first in the order its keys were sent; the sort; the search. +//! +//! This file is written by the `service-routes` generator into the transport crate +//! (`meta_http`). Nothing here depends on MetaObjects. + +// The crates this lands in are edition 2021, which has no `if let` chains to collapse into. +#![allow(clippy::collapsible_if)] + +use std::collections::HashMap; +use std::fmt; + +use serde_json::{Map, Value}; + +use super::validation::{is_date, is_uuid}; +use super::wire::{Decimal, Duration}; + +/// Five levels of `or`/`and` nesting; the sixth is `filter.nesting_too_deep`. +pub const MAX_NESTING: usize = 5; +/// At most 100 `in` elements; more is `filter.in_too_large`. +pub const MAX_IN_LIST: usize = 100; + +const SORT_EXPECTED: &str = "sort=:asc|desc"; +const PAGINATION_EXPECTED: &str = "a non-negative integer (0 or more)"; +const INTEGER_EXPECTED: &str = "integer (a whole number)"; +const PLUS_OFFSET_HINT: &str = + "a \"+\" in a query string decodes to a space: URL-encode the offset's \"+\" as %2B, or use Z for UTC"; +/// The largest page bound the TypeScript routes accept (`Number.isSafeInteger`). +const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; +const RESERVED: [&str; 6] = ["filter", "sort", "limit", "offset", "search", "withCount"]; + +/// How a filter operand is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// Text or an enum member: kept as sent. + Text, + /// int, long, currency: a JSON number with no fraction. + Integer, + /// double, float: a JSON number. + Number, + Boolean, + Date, + Time, + /// A `field.timestamp` instant: a zoneless bound is UTC, a date alone midnight UTC. + Instant, + /// A `@localTime` timestamp: kept as sent unless it carries a zone. + LocalTimestamp, + Uuid, + Decimal, + Duration, +} + +impl Kind { + /// The `expected` text of a malformed value, for the kinds that check a format. + fn expected(self) -> Option<&'static str> { + Some(match self { + Kind::Date => "date (YYYY-MM-DD)", + Kind::Time => "time (HH:MM[:SS[.fff]])", + Kind::Instant | Kind::LocalTimestamp => { + "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])" + } + Kind::Uuid => "uuid (8-4-4-4-12 hex)", + Kind::Decimal => "decimal number (digits, optional fraction, optional exponent)", + Kind::Duration => "duration (ISO 8601, e.g. PT1H30M; no years or months)", + _ => return None, + }) + } +} + +/// One filterable field: its operators, how its operand is read, and its enum members. +#[derive(Debug, Clone, Copy)] +pub struct FilterRule { + pub field: &'static str, + pub ops: &'static [&'static str], + pub kind: Kind, + /// The members of a `field.enum`; a value that is not one is refused. + pub values: Option<&'static [&'static str]>, +} + +/// One sortable field, and the direction a sort that names no order takes. +#[derive(Debug, Clone, Copy)] +pub struct SortRule { + pub field: &'static str, + pub descending: bool, +} + +/// What one entity's list route accepts. +#[derive(Debug, Clone, Copy)] +pub struct ListSpec { + pub filters: &'static [FilterRule], + pub sorts: &'static [SortRule], + /// Every field of the entity a client reads, so a bare `?notes=x` for a field that is not + /// filterable is refused with a reason rather than ignored. + pub fields: &'static [&'static str], +} + +impl ListSpec { + fn filter(&self, field: &str) -> Option<&FilterRule> { + self.filters.iter().find(|r| r.field == field) + } + + fn allowed(&self) -> Value { + names(self.filters.iter().map(|r| r.field)) + } + + /// The fields `?search` matches: text whose band has `like` (plain text and string-backed + /// enums, never a uuid or an int-backed enum). + pub fn search_fields(&self) -> Vec<&'static str> { + self.filters + .iter() + .filter(|r| r.kind == Kind::Text && r.ops.contains(&"like")) + .map(|r| r.field) + .collect() + } +} + +/// A node of a parsed filter. +#[derive(Debug, Clone, PartialEq)] +pub enum Node { + /// One condition. `in` holds a list; `isNull` a boolean. + Leaf { field: String, op: String, value: Value }, + /// Every branch holds. + And(Vec), + /// At least one branch holds. + Or(Vec), +} + +/// A case-insensitive substring search over `fields`. +#[derive(Debug, Clone, PartialEq)] +pub struct Search { + pub term: String, + pub fields: Vec<&'static str>, +} + +/// One sort key. +#[derive(Debug, Clone, PartialEq)] +pub struct Sort { + pub field: String, + pub descending: bool, +} + +/// A parsed list query. Members a query did not send are `None`. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ListQuery { + pub filter: Option, + pub search: Option, + pub sort: Option, + pub limit: Option, + pub offset: Option, + /// `withCount=true`. + pub with_count: bool, +} + +/// A refused list query: the wire code and the members after it in the 400 body. +#[derive(Debug, Clone, PartialEq)] +pub struct Refusal { + pub code: &'static str, + pub details: Vec<(&'static str, Value)>, +} + +impl Refusal { + fn new(code: &'static str, details: Vec<(&'static str, Value)>) -> Self { + Refusal { code, details } + } + + /// The 400 body: `{ "error": code, ...details }`. + pub fn body(&self) -> Value { + let mut body = Map::new(); + body.insert("error".to_string(), Value::from(self.code)); + for (k, v) in &self.details { + body.insert((*k).to_string(), v.clone()); + } + Value::Object(body) + } +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.body()) + } +} + +impl std::error::Error for Refusal {} + +fn names<'a>(items: impl Iterator) -> Value { + Value::Array(items.map(Value::from).collect()) +} + +/// Parse `raw` (the query string as it arrives, with or without its leading `?`) against `spec`. +pub fn parse(raw: &str, spec: &ListSpec) -> Result { + let q = Params::parse(raw); + reject_bare_fields(&q, spec)?; + let mut out = ListQuery { + limit: page_bound(&q, "limit")?, + offset: page_bound(&q, "offset")?, + ..ListQuery::default() + }; + if let Some(Param::Map(f)) = q.get("filter") { + out.filter = node(f, spec, 0)?; + } + if let Some(Param::Scalar(s)) = q.get("sort") { + out.sort = Some(sort(s, spec)?); + } + if let Some(Param::Scalar(t)) = q.get("search") { + let fields = spec.search_fields(); + if !t.is_empty() && !fields.is_empty() { + out.search = Some(Search { term: t.clone(), fields }); + } + } + out.with_count = + matches!(q.get("withCount"), Some(Param::Scalar(s)) if s == "true" || s == "1"); + Ok(out) +} + +fn reject_bare_fields(q: &Params, spec: &ListSpec) -> Result<(), Refusal> { + for (key, value) in q.entries() { + if RESERVED.contains(&key) { + continue; + } + if spec.filter(key).is_some() { + let shown = match value { + Param::Scalar(s) => s.as_str(), + _ => "", + }; + return Err(Refusal::new( + "filter.bare_field", + vec![ + ("field", Value::from(key)), + ("expected", Value::from(format!("filter[{key}][eq]={shown}"))), + ], + )); + } + if spec.fields.contains(&key) { + return Err(Refusal::new( + "filter.bare_field", + vec![ + ("field", Value::from(key)), + ("filterable", Value::Bool(false)), + ( + "expected", + Value::from(format!("a filterable field — \"{key}\" is not @filterable")), + ), + ("allowed", spec.allowed()), + ], + )); + } + } + Ok(()) +} + +fn page_bound(q: &Params, param: &'static str) -> Result, Refusal> { + let Some(raw) = q.get(param) else { return Ok(None) }; + let s = raw.text(); + if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) { + if let Ok(n) = s.parse::() { + if n <= MAX_SAFE_INTEGER { + return Ok(Some(n)); + } + } + } + Err(Refusal::new( + "pagination.invalid_value", + vec![ + ("param", Value::from(param)), + ("value", Value::from(s)), + ("expected", Value::from(PAGINATION_EXPECTED)), + ], + )) +} + +fn node(map: &Params, spec: &ListSpec, depth: usize) -> Result, Refusal> { + if depth > MAX_NESTING { + return Err(Refusal::new( + "filter.nesting_too_deep", + vec![("limit", Value::from(MAX_NESTING))], + )); + } + let mut parts = Vec::new(); + for (key, value) in map.entries() { + if key == "or" || key == "and" { + let group = || Refusal::new("invalid_filter_value", vec![("field", Value::from(key))]); + let Param::Map(branches) = value else { return Err(group()) }; + let mut subs = Vec::new(); + for (_, branch) in branches.entries() { + let Param::Map(branch) = branch else { return Err(group()) }; + if let Some(sub) = node(branch, spec, depth + 1)? { + subs.push(sub); + } + } + match subs.len() { + 0 => {} + 1 => parts.push(subs.remove(0)), + _ if key == "or" => parts.push(Node::Or(subs)), + _ => parts.push(Node::And(subs)), + } + continue; + } + let Some(rule) = spec.filter(key) else { + return Err(Refusal::new( + "invalid_filter_field", + vec![("field", Value::from(key)), ("allowed", spec.allowed())], + )); + }; + match value { + Param::Map(ops) => { + for (op, operand) in ops.entries() { + parts.push(leaf(rule, op, &operand.text())?); + } + } + other => parts.push(leaf(rule, "eq", &other.text())?), + } + } + Ok(match parts.len() { + 0 => None, + 1 => parts.pop(), + _ => Some(Node::And(parts)), + }) +} + +fn leaf(rule: &FilterRule, op: &str, operand: &str) -> Result { + let field = rule.field; + if !rule.ops.contains(&op) { + return Err(Refusal::new( + "invalid_filter_op", + vec![ + ("field", Value::from(field)), + ("op", Value::from(op)), + ("allowed", names(rule.ops.iter().copied())), + ], + )); + } + let value = match op { + "in" => { + let list = operand + .split(',') + .map(|v| scalar(rule, op, v.trim())) + .collect::, _>>()?; + if list.len() > MAX_IN_LIST { + return Err(Refusal::new( + "filter.in_too_large", + vec![("field", Value::from(field)), ("limit", Value::from(MAX_IN_LIST))], + )); + } + Value::Array(list) + } + "like" => { + if operand.starts_with('%') { + return Err(Refusal::new( + "filter.leading_wildcard_disallowed", + vec![("field", Value::from(field))], + )); + } + Value::from(operand) + } + "isNull" => Value::Bool(boolean(operand, field, op)?), + _ => scalar(rule, op, operand)?, + }; + Ok(Node::Leaf { field: field.to_string(), op: op.to_string(), value }) +} + +fn invalid(field: &str, op: &str, expected: &str, extra: Option<(&'static str, Value)>) -> Refusal { + let mut details = vec![ + ("field", Value::from(field)), + ("op", Value::from(op)), + ("expected", Value::from(expected)), + ]; + details.extend(extra); + Refusal::new("invalid_filter_value", details) +} + +fn scalar(rule: &FilterRule, op: &str, s: &str) -> Result { + let field = rule.field; + if let Some(members) = rule.values { + if !members.contains(&s) { + let expected = format!("one of: {}", members.join(", ")); + let allowed = names(members.iter().copied()); + return Err(invalid(field, op, &expected, Some(("allowed", allowed)))); + } + } + let bad = |extra| invalid(field, op, rule.kind.expected().unwrap_or("number"), extra); + Ok(match rule.kind { + Kind::Text => Value::from(s), + Kind::Boolean => Value::Bool(boolean(s, field, op)?), + Kind::Integer | Kind::Number => number(rule, op, s)?, + Kind::Date if is_date(s) => Value::from(s), + Kind::Time if is_filter_time(s) => Value::from(s), + Kind::Uuid if is_uuid(s) => Value::from(s), + Kind::Decimal => match Decimal::parse(s) { + Ok(d) => Value::from(d.as_str()), + Err(_) => return Err(bad(None)), + }, + Kind::Duration if Duration::parse(s).is_ok() => Value::from(s), + Kind::Instant | Kind::LocalTimestamp => match Stamp::parse(s) { + Some(stamp) => Value::from(stamp.utc(s, rule.kind == Kind::Instant)), + None if unencoded_plus_offset(s) => { + return Err(bad(Some(("hint", Value::from(PLUS_OFFSET_HINT))))); + } + None => return Err(bad(None)), + }, + _ => return Err(bad(None)), + }) +} + +fn number(rule: &FilterRule, op: &str, s: &str) -> Result { + let t = s.trim(); + if rule.kind == Kind::Integer { + if let Ok(whole) = t.parse::() { + return Ok(Value::from(whole)); + } + } + let n = match t.parse::() { + Ok(n) if n.is_finite() && !t.is_empty() => n, + _ => return Err(invalid(rule.field, op, "number", None)), + }; + if rule.kind == Kind::Integer { + if n.fract() != 0.0 { + return Err(invalid(rule.field, op, INTEGER_EXPECTED, None)); + } + if n >= i64::MIN as f64 && n <= i64::MAX as f64 { + return Ok(Value::from(n as i64)); + } + } + Ok(Value::from(n)) +} + +fn boolean(s: &str, field: &str, op: &str) -> Result { + match s { + "true" | "1" => Ok(true), + "false" | "0" => Ok(false), + _ => Err(invalid(field, op, "boolean", None)), + } +} + +fn sort(spec_text: &str, spec: &ListSpec) -> Result { + let (field, order) = match spec_text.split_once(':') { + Some((field, order)) => (field, Some(order)), + None => (spec_text, None), + }; + let refuse = || { + Refusal::new( + "invalid_sort", + vec![ + ("field", Value::from(field)), + ("expected", Value::from(SORT_EXPECTED)), + ("allowed", names(spec.sorts.iter().map(|r| r.field))), + ], + ) + }; + let rule = spec.sorts.iter().find(|r| r.field == field).ok_or_else(refuse)?; + let descending = match order.map(str::to_ascii_lowercase).as_deref() { + None => rule.descending, + Some("asc") => false, + Some("desc") => true, + Some(_) => return Err(refuse()), + }; + Ok(Sort { field: field.to_string(), descending }) +} + +// ---- value formats ------------------------------------------------------------------------ + +fn two_digits(s: &str) -> Option { + (s.len() == 2 && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok())? +} + +/// `HH:MM`, `HH:MM:SS` or `HH:MM:SS.f` with one to nine fraction digits. +fn is_filter_time(s: &str) -> bool { + clock(s).is_some() +} + +/// The hour, minute, second and fraction digits of a time of day. +fn clock(s: &str) -> Option<(u32, u32, u32, &str)> { + let (hm, rest) = (s.get(..5)?, &s[5..]); + let (h, m) = hm.split_once(':')?; + let (h, m) = (two_digits(h)?, two_digits(m)?); + if h > 23 || m > 59 { + return None; + } + if rest.is_empty() { + return Some((h, m, 0, "")); + } + let sec = two_digits(rest.strip_prefix(':')?.get(..2)?)?; + let frac = &rest[3..]; + if sec > 59 { + return None; + } + if frac.is_empty() { + return Some((h, m, sec, "")); + } + let digits = frac.strip_prefix('.')?; + (!digits.is_empty() && digits.len() <= 9 && digits.bytes().all(|b| b.is_ascii_digit())) + .then_some((h, m, sec, digits)) +} + +/// A timestamp bound: a date, then optionally a `T`/space time, then optionally `Z` or a +/// `±HH[:]MM` offset. +struct Stamp<'a> { + date: &'a str, + hour: u32, + minute: u32, + second: u32, + fraction: &'a str, + /// The offset in minutes east of UTC, when the bound names a zone. + offset: Option, +} + +impl<'a> Stamp<'a> { + fn parse(s: &'a str) -> Option> { + let date = s.get(..10)?; + if !is_date(date) { + return None; + } + let mut stamp = Stamp { date, hour: 0, minute: 0, second: 0, fraction: "", offset: None }; + let rest = &s[10..]; + if rest.is_empty() { + return Some(stamp); + } + let rest = rest.strip_prefix(['T', 't', ' '])?; + let zone_at = rest.find(['Z', 'z', '+', '-']).unwrap_or(rest.len()); + let (time, zone) = rest.split_at(zone_at); + (stamp.hour, stamp.minute, stamp.second, stamp.fraction) = clock(time)?; + stamp.offset = match zone { + "" => None, + "Z" | "z" => Some(0), + _ => { + let sign = if zone.starts_with('-') { -1 } else { 1 }; + let digits = zone[1..].replacen(':', "", 1); + if digits.len() != 4 || zone[1..].len() > 5 { + return None; + } + let (h, m) = (two_digits(&digits[..2])?, two_digits(&digits[2..])?); + if h > 23 || m > 59 { + return None; + } + Some(sign * i64::from(h * 60 + m)) + } + }; + Some(stamp) + } + + /// The bound in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`), or `s` itself when it names no zone and + /// `zoneless_is_utc` is false (a wall clock), or is already spelled that way. + fn utc(&self, s: &str, zoneless_is_utc: bool) -> String { + if self.offset.is_none() && !zoneless_is_utc { + return s.to_string(); + } + let b = s.as_bytes(); + if b.get(10) == Some(&b'T') && b.get(16) == Some(&b':') && s.ends_with('Z') { + return s.to_string(); + } + let days = days_of(self.date); + let millis: i64 = + format!("{:0<3}", &self.fraction[..self.fraction.len().min(3)]).parse().unwrap_or(0); + let seconds = days * 86_400 + i64::from(self.hour * 3600 + self.minute * 60 + self.second) + - self.offset.unwrap_or(0) * 60; + let (day, second) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400)); + let (y, mo, d) = civil(day); + let mut text = format!( + "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}", + second / 3600, + second / 60 % 60, + second % 60 + ); + if millis != 0 { + text.push_str(format!(".{millis:03}").trim_end_matches('0')); + } + text.push('Z'); + text + } +} + +/// A timestamp bound that fails only because its `+` offset arrived as a space. +fn unencoded_plus_offset(s: &str) -> bool { + let Some((head, zone)) = s.rsplit_once(' ') else { return false }; + let digits = |z: &str| z.bytes().all(|b| b.is_ascii_digit()); + let zone_ok = match zone.len() { + 2 | 4 => digits(zone), + 5 => zone.as_bytes()[2] == b':' && digits(&zone[..2]) && digits(&zone[3..]), + _ => false, + }; + zone_ok && head.len() >= 16 && Stamp::parse(head).is_some_and(|t| t.offset.is_none()) +} + +/// Days since 1970-01-01 of a valid `YYYY-MM-DD`. +fn days_of(date: &str) -> i64 { + let y: i64 = date[..4].parse().unwrap_or(1970); + let m: i64 = date[5..7].parse().unwrap_or(1); + let d: i64 = date[8..10].parse().unwrap_or(1); + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y.rem_euclid(400); + let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1; + era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468 +} + +/// The calendar date of a day count since 1970-01-01. +fn civil(days: i64) -> (i64, i64, i64) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (yoe + era * 400 + i64::from(m <= 2), m, d) +} + +// ---- the query string --------------------------------------------------------------------- + +/// One parameter of the bracket grammar: `a[b][c]=v` nests, and a repeated key collects its +/// values. +enum Param { + Scalar(String), + Many(Vec), + Map(Params), +} + +impl Param { + /// The value as text; a repeated value is its parts joined by commas. + fn text(&self) -> String { + match self { + Param::Scalar(s) => s.clone(), + Param::Many(v) => v.join(","), + Param::Map(_) => "[object Object]".to_string(), + } + } +} + +/// A map of parameters. Its entries come back with array-index keys first, in numeric order, +/// and every other key in the order it was sent, the way the TypeScript routes read them. +#[derive(Default)] +struct Params { + order: Vec, + values: HashMap, +} + +impl Params { + fn get(&self, key: &str) -> Option<&Param> { + self.values.get(key) + } + + fn entries(&self) -> Vec<(&str, &Param)> { + let mut index: Vec<(u64, &str)> = + self.order.iter().filter_map(|k| array_index(k).map(|i| (i, k.as_str()))).collect(); + index.sort_by_key(|(i, _)| *i); + index + .into_iter() + .map(|(_, k)| k) + .chain(self.order.iter().map(String::as_str).filter(|k| array_index(k).is_none())) + .map(|k| (k, &self.values[k])) + .collect() + } + + fn set(&mut self, path: &[String], value: String) { + let key = &path[0]; + if path.len() == 1 { + match self.values.get_mut(key) { + None => self.add(key, Param::Scalar(value)), + Some(Param::Scalar(first)) => { + let first = std::mem::take(first); + self.values.insert(key.clone(), Param::Many(vec![first, value])); + } + Some(Param::Many(all)) => all.push(value), + // A scalar sent beside a map under the same key: the map keeps its members. + Some(Param::Map(_)) => {} + } + return; + } + if !matches!(self.values.get(key), Some(Param::Map(_))) { + if self.values.contains_key(key) { + self.values.insert(key.clone(), Param::Map(Params::default())); + } else { + self.add(key, Param::Map(Params::default())); + } + } + if let Some(Param::Map(child)) = self.values.get_mut(key) { + child.set(&path[1..], value); + } + } + + fn add(&mut self, key: &str, value: Param) { + self.order.push(key.to_string()); + self.values.insert(key.to_string(), value); + } + + fn parse(raw: &str) -> Params { + let mut root = Params::default(); + let raw = raw.strip_prefix('?').unwrap_or(raw); + for pair in raw.split('&').filter(|p| !p.is_empty()) { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + let path = key_path(&decode(key)); + if path.first().is_some_and(|k| !k.is_empty()) { + root.set(&path, decode(value)); + } + } + root + } +} + +/// A JavaScript array index: a canonical non-negative integer below 2^32 - 1. +fn array_index(k: &str) -> Option { + let canonical = !k.is_empty() + && k.len() <= 10 + && k.bytes().all(|b| b.is_ascii_digit()) + && (k == "0" || !k.starts_with('0')); + canonical.then(|| k.parse().ok()).flatten().filter(|&n: &u64| n < 4_294_967_295) +} + +/// `a[b][c]` is a, b, c. Text after the last balanced bracket pair, or an unclosed `[`, stays +/// part of the last segment. +fn key_path(key: &str) -> Vec { + let Some(open) = key.find('[').filter(|&at| at > 0) else { return vec![key.to_string()] }; + let mut path = vec![key[..open].to_string()]; + let mut i = open; + while key[i..].starts_with('[') { + let Some(close) = key[i + 1..].find(']') else { break }; + path.push(key[i + 1..i + 1 + close].to_string()); + i += close + 2; + } + if i < key.len() { + if let Some(last) = path.last_mut() { + last.push_str(&key[i..]); + } + } + path +} + +/// Percent-decode `s`, with `+` a space. A `%` that does not start a `%XX` escape is kept. +fn decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) { + (Some(hi), Some(lo)) => { + out.push(hi * 16 + lo); + i += 2; + } + _ => out.push(b'%'), + }, + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn hex(b: u8) -> Option { + (b as char).to_digit(16).map(|d| d as u8) +} diff --git a/server/rust/metaobjects-codegen/src/emitted/mod.rs b/server/rust/metaobjects-codegen/src/emitted/mod.rs index 01d37dffc6..be3a9fb511 100644 --- a/server/rust/metaobjects-codegen/src/emitted/mod.rs +++ b/server/rust/metaobjects-codegen/src/emitted/mod.rs @@ -1,14 +1,16 @@ -//! Source the `entity` generator writes verbatim into the generated support crate. +//! Source the generators write verbatim into generated crates. //! //! The three modules are real code here, compiled and tested with the engine (the shared //! `decimal-wire` and `duration-wire` vectors and the validation corpus run against them -//! directly), and the generator emits the same bytes as `meta_support/src/`. The generated +//! directly), and the `entity` generator emits the same bytes as `meta_support/src/`. The generated //! crates therefore carry their wire types and validation checks as their own source and //! depend on nothing from MetaObjects. //! //! They are laid out for the `rustfmt.toml` a generated crate carries, not for this //! workspace's, so `cargo fmt` skips them here and the compile gate checks them there. +#[rustfmt::skip] +pub mod list_query; #[rustfmt::skip] pub mod pattern; #[rustfmt::skip] @@ -16,9 +18,33 @@ pub mod validation; #[rustfmt::skip] pub mod wire; +/// The text of `meta_http/src/list_query.rs`, the list-query parser of the `service-routes` +/// generator's crates. +pub const LIST_QUERY_RS: &str = include_str!("list_query.rs"); /// The text of `src/pattern.rs` in a generated crate. pub const PATTERN_RS: &str = include_str!("pattern.rs"); /// The text of `src/validation.rs` in a generated crate. pub const VALIDATION_RS: &str = include_str!("validation.rs"); /// The text of `src/wire.rs` in a generated crate. pub const WIRE_RS: &str = include_str!("wire.rs"); + +// More files are fixed text a generator writes whole but are not compiled here: they are +// written for the dependencies of the crate they land in (`reqwest` for the transport), which +// this crate does not have. The compile gate builds them in a generated workspace. + +/// The text of `meta_client/src/lib.rs`, the transport the `client` generator's crates share. +pub const CLIENT_TRANSPORT_RS: &str = include_str!("client_transport.rs"); +/// The text of `meta_cli/src/lib.rs`, the helpers the `commands` generator's crates share. +pub const COMMAND_HELPERS_RS: &str = include_str!("command_helpers.rs"); +/// The text of `meta_contract/src/lib.rs`, the wire error contract the `contract-types` +/// generator's crates share. +pub const CONTRACT_RS: &str = include_str!("contract.rs"); +/// The text of `meta_store/src/lib.rs`, the data access the `repository` generator's crates +/// share (written for `sqlx`). +pub const STORE_RS: &str = include_str!("store.rs"); +/// The text of `meta_http/src/lib.rs`, the REST mechanics the `service-routes` generator's +/// crates share (written for `axum`). +pub const HTTP_RS: &str = include_str!("http.rs"); +/// The text of `meta_service/src/lib.rs`, the mechanics the `service` generator's crates share +/// (written for `sqlx`). +pub const SERVICE_RS: &str = include_str!("service.rs"); diff --git a/server/rust/metaobjects-codegen/src/emitted/service.rs b/server/rust/metaobjects-codegen/src/emitted/service.rs new file mode 100644 index 0000000000..da8637aa13 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/service.rs @@ -0,0 +1,410 @@ +//! The service layer's mechanics for the `service` generator's crates (ADR-0067 layer 4): the +//! errors an operation answers with, the store it opens a transaction on, the event a write +//! reports, and the list page. +//! +//! What runs, in which order and against which table is written into each package's service +//! crate; this crate holds only what every one of them shares. It knows the wire codes of +//! ADR-0066 §6 and nothing of HTTP: the status of each is here so a transport maps an error the +//! same way in every app. + +use std::fmt; +use std::future::Future; +use std::ops::DerefMut; + +use meta_store::{Conn, StoreError}; +use meta_support::validation::Violation; +use serde::Serialize; +use serde_json::Value; + +/// The page size a list answers with when the query names no limit, the same in every port. +pub const DEFAULT_LIMIT: u64 = 50; + +/// Why an operation did not complete. Each answers one wire code (ADR-0066 §6). +#[derive(Debug)] +pub enum ServiceError { + /// 404 `not_found`: no row has the key. + NotFound, + /// 403 `forbidden`: the policy refused the permission point. + Forbidden, + /// 409 `invalid_transition`: the row is in no state the move leaves. + InvalidTransition, + /// 409 `transition_condition_failed`: the move's `@condition` does not hold for the row. + TransitionConditionFailed, + /// 409 `state_managed`: a write that is not a transition named another state of a lifecycle. + StateManaged, + /// 400 `validation`: the body breaks the model's rules. Every one is listed. + Validation(Vec), + /// 400 `limit_too_large`: a list asked for more rows than the page allows. + LimitTooLarge { max: u64 }, + /// 409 with the code: a hook, the event hook or a body refused (a declared `@errors` code + /// is answered this way too). + Refused { code: String, message: Option }, + /// The data access failed. + Store(StoreError), +} + +impl ServiceError { + /// A refusal by `code`, as a hook or the event hook returns one. + pub fn refused(code: impl Into) -> Self { + ServiceError::Refused { code: code.into(), message: None } + } + + /// Its wire code. + pub fn code(&self) -> &str { + match self { + ServiceError::NotFound => "not_found", + ServiceError::Forbidden => "forbidden", + ServiceError::InvalidTransition => "invalid_transition", + ServiceError::TransitionConditionFailed => "transition_condition_failed", + ServiceError::StateManaged => "state_managed", + ServiceError::Validation(_) => "validation", + ServiceError::LimitTooLarge { .. } => "limit_too_large", + ServiceError::Refused { code, .. } => code, + ServiceError::Store(StoreError::UnknownField { .. } | StoreError::BadValue { .. }) => { + "validation" + } + ServiceError::Store(_) => "internal", + } + } + + /// Its HTTP status. + pub fn status(&self) -> u16 { + match self { + ServiceError::NotFound => 404, + ServiceError::Forbidden => 403, + ServiceError::InvalidTransition + | ServiceError::TransitionConditionFailed + | ServiceError::StateManaged + | ServiceError::Refused { .. } => 409, + ServiceError::Validation(_) | ServiceError::LimitTooLarge { .. } => 400, + ServiceError::Store(StoreError::UnknownField { .. } | StoreError::BadValue { .. }) => { + 400 + } + ServiceError::Store(_) => 500, + } + } +} + +impl fmt::Display for ServiceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ServiceError::Validation(v) => write!(f, "validation: {} problem(s)", v.len()), + ServiceError::LimitTooLarge { max } => write!(f, "limit_too_large: at most {max}"), + ServiceError::Refused { code, message: Some(m) } => write!(f, "{code}: {m}"), + ServiceError::Store(e) => write!(f, "{e}"), + other => f.write_str(other.code()), + } + } +} + +impl std::error::Error for ServiceError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + ServiceError::Store(e) => Some(e), + _ => None, + } + } +} + +impl From for ServiceError { + fn from(e: StoreError) -> Self { + ServiceError::Store(e) + } +} + +/// What a declared operation's body may fail with: one of the operation's own `@errors` +/// (`B`, its contract's business error type), or any service error. +#[derive(Debug)] +pub enum BodyError { + Business(B), + Service(ServiceError), +} + +impl From for BodyError { + fn from(e: ServiceError) -> Self { + BodyError::Service(e) + } +} + +impl From for BodyError { + fn from(e: StoreError) -> Self { + BodyError::Service(ServiceError::Store(e)) + } +} + +impl BodyError { + /// The service error it answers with: a business error is a refusal by its code. + pub fn into_service(self) -> ServiceError { + match self { + BodyError::Service(e) => e, + BodyError::Business(b) => match serde_json::to_value(&b) { + Ok(Value::String(code)) => ServiceError::refused(code), + _ => ServiceError::refused("internal"), + }, + } + } +} + +/// Refuses a body that breaks a rule of the model. +pub fn validated(violations: Vec) -> Result<(), ServiceError> { + if violations.is_empty() { + Ok(()) + } else { + Err(ServiceError::Validation(violations)) + } +} + +// ---- the store --------------------------------------------------------------------------- + +/// A store a service runs on: a pool it reads from and opens transactions on. Implemented for +/// `sqlx::PgPool` and `sqlx::SqlitePool`. +pub trait Db: Send + Sync { + /// The connection the generated store functions run on. + type Conn: Conn; + /// A transaction: dropped without [`Db::commit`], it is rolled back. + type Tx: DerefMut + Send; + /// A pooled connection for a read. + type Read: DerefMut + Send; + + fn begin(&self) -> impl Future> + Send; + fn commit(tx: Self::Tx) -> impl Future> + Send; + fn rollback(tx: Self::Tx) -> impl Future> + Send; + fn read(&self) -> impl Future> + Send; +} + +#[cfg(feature = "postgres")] +impl Db for sqlx::PgPool { + type Conn = sqlx::PgConnection; + type Tx = sqlx::Transaction<'static, sqlx::Postgres>; + type Read = sqlx::pool::PoolConnection; + + async fn begin(&self) -> Result { + Ok(sqlx::Pool::begin(self).await?) + } + async fn commit(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.commit().await?) + } + async fn rollback(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.rollback().await?) + } + async fn read(&self) -> Result { + Ok(self.acquire().await?) + } +} + +#[cfg(feature = "sqlite")] +impl Db for sqlx::SqlitePool { + type Conn = sqlx::SqliteConnection; + type Tx = sqlx::Transaction<'static, sqlx::Sqlite>; + type Read = sqlx::pool::PoolConnection; + + async fn begin(&self) -> Result { + Ok(sqlx::Pool::begin(self).await?) + } + async fn commit(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.commit().await?) + } + async fn rollback(tx: Self::Tx) -> Result<(), StoreError> { + Ok(tx.rollback().await?) + } + async fn read(&self) -> Result { + Ok(self.acquire().await?) + } +} + +/// Ends the transaction `tx` an operation ran in: committed when `out` is a success, rolled +/// back when it is a refusal, so a refusal anywhere undoes every write before it. +pub async fn finish(tx: D::Tx, out: Result) -> Result { + match out { + Ok(v) => { + D::commit(tx).await?; + Ok(v) + } + Err(e) => { + // The refusal is the answer; a failed rollback is the connection's to report. + let _ = D::rollback(tx).await; + Err(e) + } + } +} + +// ---- what hand-written code is handed ---------------------------------------------------- + +/// What a body or a hook runs with: the operation's connection (inside its transaction for a +/// write) and the actor it runs for. +pub struct Cx<'a, A, C: ?Sized> { + pub conn: &'a mut C, + pub actor: Option<&'a A>, +} + +/// What kind of write an event reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WriteKind { + Create, + Update, + Delete, + /// A lifecycle moved: a transition's derived command, or a declared command that moved it. + Transition, + /// A declared command that made no move. + Command, +} + +impl WriteKind { + /// Its name, as the other ports' events spell it. + pub const fn as_str(self) -> &'static str { + match self { + WriteKind::Create => "create", + WriteKind::Update => "update", + WriteKind::Delete => "delete", + WriteKind::Transition => "transition", + WriteKind::Command => "command", + } + } +} + +/// A write, as the event hook is told of it: last, inside the write's transaction, so a +/// refusal undoes the write. +#[derive(Debug)] +pub struct WriteEvent<'a, A> { + pub kind: WriteKind, + /// The entity written; `None` for a declared command with no target. + pub entity: Option<&'static str>, + /// The key of the row written. + pub key: Option, + /// The operation that wrote: a declared command, or a transition's derived command. + pub operation: Option<&'static str>, + /// For a transition: the lifecycle's field, the transition, and the states. + pub lifecycle: Option<&'static str>, + pub transition: Option<&'static str>, + pub from: Option, + pub to: Option, + /// The row as written (a create or an update), or as it was (a delete). + pub row: Option, + /// The row before an update. + pub previous: Option, + pub actor: Option<&'a A>, +} + +impl<'a, A> WriteEvent<'a, A> { + /// An event of `kind` with nothing else said. + pub fn new(kind: WriteKind, actor: Option<&'a A>) -> Self { + WriteEvent { + kind, + entity: None, + key: None, + operation: None, + lifecycle: None, + transition: None, + from: None, + to: None, + row: None, + previous: None, + actor, + } + } +} + +/// `value` as JSON, for a policy, an event or a key. +pub fn json(value: &T) -> Value { + serde_json::to_value(value).unwrap_or(Value::Null) +} + +/// The instant a write stamps an `@autoSet` timestamp with (ADR-0045): ISO 8601 in UTC, to the +/// millisecond, with its zone, or with none for a `@localTime` field. +pub fn now(local_time: bool) -> String { + let now = chrono::Utc::now(); + if local_time { + now.naive_utc().format("%Y-%m-%dT%H:%M:%S%.3f").to_string() + } else { + now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true) + } +} + +/// The wire spelling of a state. +pub fn state_name(state: &S) -> String { + match json(state) { + Value::String(s) => s, + other => other.to_string(), + } +} + +// ---- lists ------------------------------------------------------------------------------- + +/// A page of a list. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Page { + pub rows: Vec, + /// The number of rows the filter selects, when the list asked for it. + #[serde(skip_serializing_if = "Option::is_none")] + pub total: Option, +} + +/// The page size of a list: the query's limit, else `default`; refused above `max`. +pub fn page_limit(limit: Option, default: u64, max: Option) -> Result { + match (limit, max) { + (Some(l), Some(m)) if l > m => Err(ServiceError::LimitTooLarge { max: m }), + (Some(l), _) => Ok(l), + (None, _) => Ok(default), + } +} + +// ---- lifecycles -------------------------------------------------------------------------- + +/// Whether `state` (a row's lifecycle field, an `Option` of the state or the state) is one of +/// `from`. +pub fn in_state(state: &S, from: &[F]) -> bool { + let state = json(state); + from.iter().any(|f| json(f) == state) +} + +/// One move of a lifecycle, as [`make_move`] makes it: `field` from one of `from` to `to`, under +/// `condition` (the move's `@condition` as JSON) when it has one. +#[derive(Debug, Clone, Copy)] +pub struct Move<'a, S> { + pub field: &'a str, + pub from: &'a [S], + pub to: S, + pub condition: Option<&'a str>, +} + +/// Makes the move `m` on the row `key` names: the guarded update of ADR-0066 §6 step 5. A row +/// another write moved first is `invalid_transition`, and one still in `from` whose condition +/// does not hold is `transition_condition_failed`. +pub async fn make_move( + conn: &mut C, + table: &meta_store::Table, + key: &(impl Serialize + Sync + ?Sized), + m: &Move<'_, S>, +) -> Result<(), ServiceError> +where + S: Serialize + Sync, + C: Conn + ?Sized, +{ + let condition = match m.condition { + Some(text) => { + let value: Value = serde_json::from_str(text).map_err(|e| { + ServiceError::Store(StoreError::BadValue { + field: m.field.to_string(), + message: e.to_string(), + }) + })?; + Some(meta_store::Condition::from_json(&value)?) + } + None => None, + }; + let (from, to) = (m.from, &m.to); + let condition_ref = condition.as_ref(); + if meta_store::transition(&mut *conn, table, key, m.field, from, to, condition_ref).await? { + return Ok(()); + } + let now: Option = meta_store::get(&mut *conn, table, key).await?; + let Some(now) = now else { + return Err(ServiceError::NotFound); + }; + let still = in_state(now.get(m.field).unwrap_or(&Value::Null), from); + Err(if still && condition.is_some() { + ServiceError::TransitionConditionFailed + } else { + ServiceError::InvalidTransition + }) +} diff --git a/server/rust/metaobjects-codegen/src/emitted/store.rs b/server/rust/metaobjects-codegen/src/emitted/store.rs new file mode 100644 index 0000000000..265259184b --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/store.rs @@ -0,0 +1,1654 @@ +//! Data access over sqlx for the `repository` generator's crates: a table described as data, +//! the list query (the nine filter operators, sort and paging), and the reads and writes on +//! Postgres and SQLite. +//! +//! A row is read into the JSON a model type deserializes from, and a body a caller sends is +//! serialized to JSON and bound column by column, so the model types stay free of sqlx and a +//! store crate is a table descriptor and a few typed functions over this one. +//! +//! The wire forms are the ones every port's runtime reads and writes +//! (`fixtures/persistence-conformance/normalization.md`): on SQLite a boolean is `0`/`1`, a +//! duration is its length in microseconds, a JSON value and an array are JSON text, and a +//! timestamp is the text the caller sent. A null sorts after every value (ascending) and +//! before every value (descending) on both engines. + +use std::fmt; +use std::future::Future; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; + +/// How a column holds its value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Text, + Int, + Long, + Double, + Float, + Bool, + Decimal, + Date, + Time, + /// A wall-clock timestamp (`@localTime`): no zone. + Timestamp, + /// An instant, read back in UTC. + TimestampTz, + Uuid, + Inet, + Duration, + /// A value object or a map, stored as one JSON column. + Json, + /// An enum stored as an integer (`@intValueMap`): each member and its stored value. + IntEnum(&'static [(&'static str, i64)]), + /// An enum stored as other text (`@stringValueMap`): each member and its stored text. + StringEnum(&'static [(&'static str, &'static str)]), +} + +/// One column of a table: the model field it holds and how. +#[derive(Debug, Clone, Copy)] +pub struct Column { + /// The field's name in the model, which is its name on the wire. + pub field: &'static str, + /// The column's name in the database. + pub column: &'static str, + pub kind: Kind, + /// An array of `kind`: a native array on Postgres, JSON text on SQLite. An array of + /// value objects is one `Json` column instead. + pub array: bool, + /// The column's own SQL type when the model names one (`@dbColumnType`), as a string held + /// in a `uuid` or `jsonb` column: Postgres casts to it on a write and back on a read. + pub stored_as: Option<&'static str>, +} + +impl Column { + /// A column holding one value of `kind`. + pub const fn new(field: &'static str, column: &'static str, kind: Kind) -> Column { + Column { field, column, kind, array: false, stored_as: None } + } + + /// A column holding a list of `kind`. + pub const fn list(field: &'static str, column: &'static str, kind: Kind) -> Column { + Column { field, column, kind, array: true, stored_as: None } + } + + /// A column holding one value of `kind` in its own SQL type `ty`. + pub const fn typed( + field: &'static str, + column: &'static str, + kind: Kind, + ty: &'static str, + ) -> Column { + Column { field, column, kind, array: false, stored_as: Some(ty) } + } + + /// A column holding a list of `kind` in its own SQL type `ty` (of each element). + pub const fn typed_list( + field: &'static str, + column: &'static str, + kind: Kind, + ty: &'static str, + ) -> Column { + Column { field, column, kind, array: true, stored_as: Some(ty) } + } +} + +/// A table or view a store reads, and writes when it is writable. +#[derive(Debug, Clone, Copy)] +pub struct Table { + /// The object's name in the model, for messages. + pub object: &'static str, + pub schema: Option<&'static str>, + pub name: &'static str, + /// The field of the primary key; `None` for a keyless view. + pub key: Option<&'static str>, + pub columns: &'static [Column], + pub writable: bool, + /// For a subtype of a single-table hierarchy: the discriminator field and this subtype's + /// stored value. Every read and write is scoped to it, and a create sets it. + pub discriminator: Option<(&'static str, &'static str)>, + /// The view the rows are read from, when it is not this table (an entity that writes a + /// table and reads a view, carrying the derived fields the table does not store). Every + /// read goes to it, and a write reads its row back from it. + pub read: Option<&'static Table>, +} + +impl Table { + /// What the rows are read from: the read view, else the table itself. + pub fn reader(&self) -> &Table { + self.read.unwrap_or(self) + } + + /// The column of a model field. + pub fn column(&self, field: &str) -> Result<&Column, StoreError> { + self.columns.iter().find(|c| c.field == field).ok_or_else(|| StoreError::UnknownField { + object: self.object, + field: field.to_string(), + }) + } + + fn key_column(&self) -> Result<&Column, StoreError> { + match self.key { + Some(k) => self.column(k), + None => Err(StoreError::Unsupported(format!("{} has no primary key", self.object))), + } + } + + fn require_writable(&self) -> Result<(), StoreError> { + if self.writable { + Ok(()) + } else { + Err(StoreError::Unsupported(format!("{} is read-only", self.object))) + } + } +} + +/// The junction of a many-to-many relationship: the table and the two columns that hold the +/// keys of the rows it relates. +#[derive(Debug, Clone, Copy)] +pub struct Through { + pub schema: Option<&'static str>, + pub name: &'static str, + /// The column that holds the key of the row the relationship is navigated from. + pub source: Column, + /// The column that holds the key of a related row. + pub target: Column, + /// An undirected self-join: a row relates each of its two sides to the other, so a row + /// `(a, b)` answers from `a` and from `b`. + pub symmetric: bool, +} + +/// A data-access failure. +#[derive(Debug)] +pub enum StoreError { + /// A query or a body names a field the object does not have. + UnknownField { + object: &'static str, + field: String, + }, + /// A value does not fit its column, or a filter does not fit its field. + BadValue { + field: String, + message: String, + }, + /// A stored value the model does not describe. + Decode { + field: String, + message: String, + }, + Unsupported(String), + Database(sqlx::Error), +} + +impl fmt::Display for StoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + StoreError::UnknownField { object, field } => { + write!(f, "{object} has no field `{field}`") + } + StoreError::BadValue { field, message } => write!(f, "`{field}`: {message}"), + StoreError::Decode { field, message } => write!(f, "reading `{field}`: {message}"), + StoreError::Unsupported(m) => f.write_str(m), + StoreError::Database(e) => write!(f, "{e}"), + } + } +} + +impl std::error::Error for StoreError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + StoreError::Database(e) => Some(e), + _ => None, + } + } +} + +impl From for StoreError { + fn from(e: sqlx::Error) -> Self { + StoreError::Database(e) + } +} + +fn bad(field: &str, message: impl Into) -> StoreError { + StoreError::BadValue { field: field.to_string(), message: message.into() } +} + +fn decode_err(field: &str, message: impl fmt::Display) -> StoreError { + StoreError::Decode { field: field.to_string(), message: message.to_string() } +} + +// ---- the list query ------------------------------------------------------------------ + +/// A filter operator. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Op { + Eq, + Ne, + Gt, + Gte, + Lt, + Lte, + In, + Like, + IsNull, +} + +impl Op { + /// The operator of its wire name. + pub fn of(name: &str) -> Option { + Some(match name { + "eq" => Op::Eq, + "ne" => Op::Ne, + "gt" => Op::Gt, + "gte" => Op::Gte, + "lt" => Op::Lt, + "lte" => Op::Lte, + "in" => Op::In, + "like" => Op::Like, + "isNull" => Op::IsNull, + _ => return None, + }) + } + + fn sql(self) -> &'static str { + match self { + Op::Eq => "=", + Op::Ne => "<>", + Op::Gt => ">", + Op::Gte => ">=", + Op::Lt => "<", + Op::Lte => "<=", + Op::Like => "LIKE", + Op::In | Op::IsNull => "", + } + } +} + +/// A condition on a model's fields. +#[derive(Debug, Clone, PartialEq)] +pub enum Filter { + Field { + field: String, + op: Op, + value: Value, + }, + /// Every one holds; none is always true. + And(Vec), + /// At least one holds; none is always false. + Or(Vec), + /// A case-insensitive substring match of `term` on any of `fields` (text), the list + /// route's `?search`. `%` and `_` in the term keep their `LIKE` meaning. + Search { + term: String, + fields: Vec, + }, +} + +impl Filter { + pub fn field(field: impl Into, op: Op, value: impl Into) -> Filter { + Filter::Field { field: field.into(), op, value: value.into() } + } + + /// The filter of its JSON form: `{ "": { "": value }, "and": [ ... ], "or": [ ... ] }`, + /// each key one more condition ANDed with the rest. + pub fn from_json(value: &Value) -> Result { + let Value::Object(map) = value else { + return Err(bad("filter", "a filter is an object")); + }; + let mut all = Vec::new(); + for (key, v) in map { + if key == "and" || key == "or" { + let Value::Array(items) = v else { + return Err(bad(key, format!("`{key}` is a list of filters"))); + }; + let items = items.iter().map(Filter::from_json).collect::, _>>()?; + match key.as_str() { + "and" => all.extend(items), + _ => all.push(Filter::Or(items)), + } + continue; + } + let Value::Object(ops) = v else { + return Err(bad(key, "a field's condition is an object of operators")); + }; + for (op, operand) in ops { + let op = Op::of(op).ok_or_else(|| bad(key, format!("unknown operator `{op}`")))?; + all.push(Filter::field(key.clone(), op, operand.clone())); + } + } + Ok(if all.len() == 1 { all.remove(0) } else { Filter::And(all) }) + } +} + +/// A transition's `@condition` (ADR-0066 §1): attr.expression's CHECK subset, the six +/// comparisons, the null tests, and, or, not and coalesce, over a model's FIELD names. The +/// guarded update ANDs it into the one statement that makes the move. +#[derive(Debug, Clone, PartialEq)] +pub enum Condition { + /// One of `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + Compare { + op: Op, + left: Operand, + right: Operand, + }, + /// `isNull`, or `isNotNull` when `not`. + IsNull { + operand: Operand, + not: bool, + }, + Not(Box), + And(Vec), + Or(Vec), +} + +/// One side of a comparison in a [`Condition`]. +#[derive(Debug, Clone, PartialEq)] +pub enum Operand { + Field(String), + /// A literal: compared with a field, it is written in the form that field's column stores + /// (an int-backed enum's member is its integer), as a filter value is. + Value(Value), + Coalesce(Vec), +} + +impl Condition { + /// The condition of its JSON form, a node of the `@condition` grammar. A node outside the + /// grammar is refused rather than dropped: a guard that loses its condition makes a move the + /// model forbids. + pub fn from_json(node: &Value) -> Result { + let op = node.get("op").and_then(Value::as_str).unwrap_or(""); + let arg = |key: &str| { + node.get(key).ok_or_else(|| bad("condition", format!("`{op}` takes `{key}`"))) + }; + let args = || match node.get("args") { + Some(Value::Array(items)) => items.iter().map(Condition::from_json).collect(), + _ => Err(bad("condition", format!("`{op}` takes a list `args`"))), + }; + Ok(match op { + "and" => Condition::And(args()?), + "or" => Condition::Or(args()?), + "not" => Condition::Not(Box::new(Condition::from_json(arg("arg")?)?)), + "isNull" | "isNotNull" => Condition::IsNull { + operand: Operand::from_json(arg("arg")?)?, + not: op == "isNotNull", + }, + _ => match Op::of(op) { + Some(o @ (Op::Eq | Op::Ne | Op::Gt | Op::Gte | Op::Lt | Op::Lte)) => { + Condition::Compare { + op: o, + left: Operand::from_json(arg("left")?)?, + right: Operand::from_json(arg("right")?)?, + } + } + _ => { + return Err(bad( + "condition", + format!("{node} is not a condition the guarded update can apply"), + )) + } + }, + }) + } +} + +impl Operand { + /// The operand of its JSON form: `{ "field": name }`, `{ "value": literal }` or + /// `{ "fn": "coalesce", "args": [ ... ] }`. + pub fn from_json(node: &Value) -> Result { + if let Some(field) = node.get("field").and_then(Value::as_str) { + return Ok(Operand::Field(field.to_string())); + } + if let Some(v) = node.get("value") { + return Ok(Operand::Value(v.clone())); + } + if let (Some("coalesce"), Some(Value::Array(items))) = + (node.get("fn").and_then(Value::as_str), node.get("args")) + { + return Ok(Operand::Coalesce( + items.iter().map(Operand::from_json).collect::>()?, + )); + } + Err(bad("condition", format!("{node} is not an operand the guarded update can apply"))) + } + + /// The field whose stored form a literal compared with this operand takes: the field + /// itself, or a coalesce's first field. + fn stored_field(&self) -> Option<&str> { + match self { + Operand::Field(f) => Some(f), + Operand::Value(_) => None, + Operand::Coalesce(items) => items.iter().find_map(Operand::stored_field), + } + } +} + +/// An order on one field. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sort { + pub field: String, + pub descending: bool, +} + +/// What a list reads: a filter, an order, and a page. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Query { + pub filter: Option, + pub sort: Vec, + pub limit: Option, + pub offset: Option, +} + +// ---- connections --------------------------------------------------------------------- + +/// The engine a connection talks to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Engine { + Postgres, + Sqlite, +} + +/// A value bound to a placeholder. +#[derive(Debug, Clone, PartialEq)] +pub enum Bind { + Null, + Bool(bool), + Int(i64), + Real(f64), + Text(String), + Ints(Vec), + Texts(Vec), +} + +/// A database connection a store runs on: a Postgres or a SQLite connection, or a +/// transaction on one (`&mut *tx`). +pub trait Conn: Send { + fn engine(&self) -> Engine; + + /// Runs `sql` and reads every row, each column decoded as `columns` says, in order. + fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> impl Future>, StoreError>> + Send + 'a; + + /// Runs `sql` and reads the one integer its one row holds. + fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> impl Future> + Send + 'a; + + /// Runs `sql` and answers the number of rows it changed. + fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> impl Future> + Send + 'a; +} + +/// A statement as it is built: its text and its binds, numbered for the engine. +struct Sql { + engine: Engine, + text: String, + binds: Vec, +} + +impl Sql { + fn new(engine: Engine) -> Self { + Sql { engine, text: String::new(), binds: Vec::new() } + } + + fn push(&mut self, s: &str) { + self.text.push_str(s); + } + + /// A placeholder for `bind`, cast to the column's type on Postgres. + fn param(&mut self, bind: Bind, column: &Column) { + self.binds.push(bind); + match self.engine { + Engine::Postgres => { + let n = self.binds.len(); + let ty = pg_type(column); + self.text.push_str(&format!("CAST(${n} AS {ty})")); + } + Engine::Sqlite => self.text.push('?'), + } + } + + /// A placeholder for a literal with no column to take its type from. + fn raw_param(&mut self, bind: Bind) { + self.binds.push(bind); + match self.engine { + Engine::Postgres => self.text.push_str(&format!("${}", self.binds.len())), + Engine::Sqlite => self.text.push('?'), + } + } +} + +fn quote(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn table_ref(table: &Table) -> String { + match table.schema { + Some(s) => format!("{}.{}", quote(s), quote(table.name)), + None => quote(table.name), + } +} + +fn pg_type(c: &Column) -> String { + if let Some(ty) = c.stored_as { + return if c.array { format!("{ty}[]") } else { ty.to_string() }; + } + logical_pg_type(c) +} + +/// The Postgres type the model's `kind` reads as. +fn logical_pg_type(c: &Column) -> String { + let base = match c.kind { + Kind::Text | Kind::StringEnum(_) => "text", + Kind::Int | Kind::IntEnum(_) => "integer", + Kind::Long => "bigint", + Kind::Double => "double precision", + Kind::Float => "real", + Kind::Bool => "boolean", + Kind::Decimal => "numeric", + Kind::Date => "date", + Kind::Time => "time", + Kind::Timestamp => "timestamp", + Kind::TimestampTz => "timestamptz", + Kind::Uuid => "uuid", + Kind::Inet => "inet", + Kind::Duration => "interval", + Kind::Json => return "jsonb".to_string(), + }; + if c.array { + format!("{base}[]") + } else { + base.to_string() + } +} + +/// What a SELECT reads for a column: on Postgres an exact decimal and a uuid as text, an +/// address without its netmask, and a column of its own SQL type as the type of its kind. A +/// view's number is read as the type of its kind too, because the view's SQL decides its +/// column's type (`AVG` of an integer is `NUMERIC` on Postgres). +fn read_expr(engine: Engine, table: &Table, c: &Column) -> String { + let col = quote(c.column); + let view_number = !table.writable + && !c.array + && matches!(c.kind, Kind::Int | Kind::Long | Kind::Double | Kind::Float); + if engine == Engine::Postgres && (c.stored_as.is_some() || view_number) { + return format!("CAST({col} AS {})", logical_pg_type(c)); + } + match (engine, c.kind, c.array) { + (Engine::Postgres, Kind::Decimal | Kind::Uuid, false) => format!("{col}::text"), + (Engine::Postgres, Kind::Decimal | Kind::Uuid, true) => format!("{col}::text[]"), + (Engine::Postgres, Kind::Inet, false) => format!("host({col})"), + _ => col, + } +} + +fn select_list(engine: Engine, table: &Table) -> String { + table.columns.iter().map(|c| read_expr(engine, table, c)).collect::>().join(", ") +} + +// ---- binding a JSON value ---------------------------------------------------------------- + +fn text_of<'v>(field: &str, v: &'v Value, what: &str) -> Result<&'v str, StoreError> { + v.as_str().ok_or_else(|| bad(field, format!("{what} is a string"))) +} + +fn int_of(field: &str, v: &Value) -> Result { + if let Some(i) = v.as_i64() { + return Ok(i); + } + // A 64-bit value may arrive as its base-10 text, so it survives a JSON number. + if let Some(i) = v.as_str().and_then(|s| s.parse::().ok()) { + return Ok(i); + } + Err(bad(field, "an integer is a number or its base-10 text")) +} + +/// The bind of one value of a column of `kind`. +fn scalar_bind(engine: Engine, field: &str, kind: Kind, v: &Value) -> Result { + if v.is_null() { + return Ok(Bind::Null); + } + Ok(match kind { + Kind::Text | Kind::Date | Kind::Time | Kind::Timestamp | Kind::TimestampTz | Kind::Inet => { + Bind::Text(text_of(field, v, "the value")?.to_string()) + } + // A UUID's canonical text is lower case, which is what Postgres reads back too. + Kind::Uuid => Bind::Text(text_of(field, v, "a UUID")?.to_ascii_lowercase()), + Kind::Int | Kind::Long => Bind::Int(int_of(field, v)?), + Kind::Double | Kind::Float => { + Bind::Real(v.as_f64().ok_or_else(|| bad(field, "a number is a JSON number"))?) + } + Kind::Bool => { + let b = v.as_bool().ok_or_else(|| bad(field, "a boolean is true or false"))?; + match engine { + Engine::Postgres => Bind::Bool(b), + Engine::Sqlite => Bind::Int(i64::from(b)), + } + } + Kind::Decimal => match v { + Value::String(s) => { + let d = + meta_support::wire::Decimal::parse(s).map_err(|e| bad(field, e.to_string()))?; + Bind::Text(d.as_str().to_string()) + } + Value::Number(n) => Bind::Text(n.to_string()), + _ => return Err(bad(field, "a decimal is a string or a number")), + }, + Kind::Duration => { + let text = text_of(field, v, "a duration")?; + let d = + meta_support::wire::Duration::parse(text).map_err(|e| bad(field, e.to_string()))?; + match engine { + // In microseconds, the interval's own resolution: Postgres reads no sign on an + // ISO duration. + Engine::Postgres => Bind::Text(format!("{} microseconds", d.nanos() / 1000)), + Engine::Sqlite => Bind::Int( + i64::try_from(d.nanos() / 1000) + .map_err(|_| bad(field, "the duration is too long"))?, + ), + } + } + Kind::Json => Bind::Text(v.to_string()), + Kind::StringEnum(map) => { + let symbol = text_of(field, v, "an enum member")?; + let stored = map + .iter() + .find(|(m, _)| *m == symbol) + .map(|(_, t)| *t) + .ok_or_else(|| bad(field, format!("`{symbol}` is not a member")))?; + Bind::Text(stored.to_string()) + } + Kind::IntEnum(map) => { + let symbol = text_of(field, v, "an enum member")?; + let stored = map + .iter() + .find(|(m, _)| *m == symbol) + .map(|(_, i)| *i) + .ok_or_else(|| bad(field, format!("`{symbol}` is not a member")))?; + Bind::Int(stored) + } + }) +} + +/// The bind of a column's value: an array is bound whole. +fn bind_of(engine: Engine, c: &Column, v: &Value) -> Result { + if !c.array || v.is_null() { + return scalar_bind(engine, c.field, c.kind, v); + } + let Value::Array(items) = v else { + return Err(bad(c.field, "the value is a list")); + }; + let binds = items + .iter() + .map(|item| scalar_bind(engine, c.field, c.kind, item)) + .collect::, _>>()?; + match engine { + Engine::Sqlite => { + let stored: Vec = binds + .into_iter() + .map(|b| match b { + Bind::Null => Value::Null, + Bind::Bool(b) => Value::Bool(b), + Bind::Int(i) => Value::from(i), + Bind::Real(r) => Value::from(r), + Bind::Text(t) => Value::String(t), + Bind::Ints(_) | Bind::Texts(_) => Value::Null, + }) + .collect(); + Ok(Bind::Text(Value::Array(stored).to_string())) + } + Engine::Postgres => { + if binds.iter().all(|b| matches!(b, Bind::Int(_))) { + Ok(Bind::Ints( + binds.into_iter().map(|b| if let Bind::Int(i) = b { i } else { 0 }).collect(), + )) + } else if binds.iter().all(|b| matches!(b, Bind::Text(_))) { + Ok(Bind::Texts( + binds + .into_iter() + .map(|b| if let Bind::Text(t) = b { t } else { String::new() }) + .collect(), + )) + } else { + Err(StoreError::Unsupported(format!("`{}`: an array of this type", c.field))) + } + } + } +} + +// ---- decoding a stored value --------------------------------------------------------------- + +fn int_enum_member(field: &str, map: &[(&str, i64)], stored: i64) -> Result { + map.iter() + .find(|(_, i)| *i == stored) + .map(|(m, _)| Value::String((*m).to_string())) + .ok_or_else(|| decode_err(field, format!("the stored value {stored} is no member"))) +} + +fn string_enum_member( + field: &str, + map: &[(&str, &str)], + stored: &str, +) -> Result { + map.iter() + .find(|(_, t)| *t == stored) + .map(|(m, _)| Value::String((*m).to_string())) + .ok_or_else(|| decode_err(field, format!("the stored value `{stored}` is no member"))) +} + +fn decimal_text(field: &str, text: &str) -> Result { + meta_support::wire::Decimal::parse(text) + .map(|d| Value::String(d.as_str().to_string())) + .map_err(|e| decode_err(field, e)) +} + +fn decimal_real(field: &str, r: f64) -> Result { + meta_support::wire::Decimal::from_f64(r) + .map(|d| Value::String(d.as_str().to_string())) + .ok_or_else(|| decode_err(field, "a decimal must be finite")) +} + +fn duration_nanos(nanos: i128) -> Value { + Value::String(meta_support::wire::Duration::from_nanos(nanos).to_string()) +} + +fn number(field: &str, r: f64) -> Result { + serde_json::Number::from_f64(r) + .map(Value::Number) + .ok_or_else(|| decode_err(field, "a number must be finite")) +} + +#[cfg(feature = "postgres")] +mod pg { + use super::*; + use chrono::Timelike; + use sqlx::postgres::types::PgInterval; + use sqlx::postgres::{PgArguments, PgRow}; + use sqlx::{Arguments, Row}; + + fn args(binds: Vec) -> Result { + let mut a = PgArguments::default(); + for b in binds { + let r = match b { + Bind::Null => a.add(Option::::None), + Bind::Bool(v) => a.add(v), + Bind::Int(v) => a.add(v), + Bind::Real(v) => a.add(v), + Bind::Text(v) => a.add(v), + Bind::Ints(v) => a.add(v), + Bind::Texts(v) => a.add(v), + }; + r.map_err(|e| StoreError::Database(sqlx::Error::Encode(e)))?; + } + Ok(a) + } + + /// The fractional seconds of a time: `.` and the digits without trailing zeros, or nothing + /// for a whole second. + /// The fraction of a second on the wire: milliseconds, truncated, with no trailing zeros + /// and no dot when there are none (normalization.md). + fn fraction(nanos: u32) -> String { + let millis = nanos / 1_000_000; + if millis == 0 { + return String::new(); + } + let digits = format!("{millis:03}"); + format!(".{}", digits.trim_end_matches('0')) + } + + fn get<'r, T: sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type>( + row: &'r PgRow, + i: usize, + field: &str, + ) -> Result, StoreError> { + row.try_get::, _>(i).map_err(|e| decode_err(field, e)) + } + + fn scalar(row: &PgRow, i: usize, c: &Column) -> Result { + let f = c.field; + let v = match c.kind { + Kind::Text | Kind::Decimal | Kind::Uuid | Kind::Inet | Kind::StringEnum(_) => { + match (get::(row, i, f)?, c.kind) { + (None, _) => Value::Null, + (Some(s), Kind::Decimal) => decimal_text(f, &s)?, + (Some(s), Kind::StringEnum(map)) => string_enum_member(f, map, &s)?, + (Some(s), _) => Value::String(s), + } + } + Kind::Int => get::(row, i, f)?.map_or(Value::Null, Value::from), + Kind::IntEnum(map) => match get::(row, i, f)? { + None => Value::Null, + Some(s) => int_enum_member(f, map, i64::from(s))?, + }, + Kind::Long => get::(row, i, f)?.map_or(Value::Null, Value::from), + Kind::Double => match get::(row, i, f)? { + None => Value::Null, + Some(r) => number(f, r)?, + }, + Kind::Float => match get::(row, i, f)? { + None => Value::Null, + // The shortest text of the f32, so 0.1 reads back as 0.1 and not its f64 widening. + Some(r) => number(f, r.to_string().parse::().unwrap_or(f64::from(r)))?, + }, + Kind::Bool => get::(row, i, f)?.map_or(Value::Null, Value::Bool), + Kind::Date => get::(row, i, f)? + .map_or(Value::Null, |d| Value::String(d.format("%Y-%m-%d").to_string())), + Kind::Time => get::(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!("{}{}", t.format("%H:%M:%S"), fraction(t.nanosecond()))) + }), + Kind::Timestamp => get::(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!( + "{}{}", + t.format("%Y-%m-%dT%H:%M:%S"), + fraction(t.nanosecond()) + )) + }), + Kind::TimestampTz => { + get::>(row, i, f)?.map_or(Value::Null, |t| { + Value::String(format!( + "{}{}Z", + t.format("%Y-%m-%dT%H:%M:%S"), + fraction(t.nanosecond()) + )) + }) + } + Kind::Duration => match get::(row, i, f)? { + None => Value::Null, + Some(iv) if iv.months != 0 => { + return Err(decode_err(f, "an interval with months has no fixed length")); + } + Some(iv) => duration_nanos( + i128::from(iv.days) * 86_400_000_000_000 + i128::from(iv.microseconds) * 1000, + ), + }, + Kind::Json => get::(row, i, f)?.unwrap_or(Value::Null), + }; + Ok(v) + } + + fn array(row: &PgRow, i: usize, c: &Column) -> Result { + let f = c.field; + let items: Option> = match c.kind { + Kind::Int => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::from).collect()) + } + Kind::IntEnum(map) => match get::>(row, i, f)? { + None => None, + Some(v) => Some( + v.into_iter() + .map(|s| int_enum_member(f, map, i64::from(s))) + .collect::>()?, + ), + }, + Kind::Long => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::from).collect()) + } + Kind::Text | Kind::Uuid => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::String).collect()) + } + Kind::Decimal => match get::>(row, i, f)? { + None => None, + Some(v) => Some(v.iter().map(|s| decimal_text(f, s)).collect::>()?), + }, + Kind::StringEnum(map) => match get::>(row, i, f)? { + None => None, + Some(v) => Some( + v.iter().map(|s| string_enum_member(f, map, s)).collect::>()?, + ), + }, + Kind::Bool => { + get::>(row, i, f)?.map(|v| v.into_iter().map(Value::Bool).collect()) + } + _ => return Err(StoreError::Unsupported(format!("`{f}`: an array of this type"))), + }; + Ok(items.map_or(Value::Null, Value::Array)) + } + + fn decode(row: &PgRow, columns: &[Column]) -> Result, StoreError> { + let mut out = Map::new(); + for (i, c) in columns.iter().enumerate() { + let v = if c.array { array(row, i, c)? } else { scalar(row, i, c)? }; + out.insert(c.field.to_string(), v); + } + Ok(out) + } + + impl Conn for sqlx::PgConnection { + fn engine(&self) -> Engine { + Engine::Postgres + } + + async fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> Result>, StoreError> { + let rows = sqlx::query_with(sql, args(binds)?).fetch_all(&mut *self).await?; + rows.iter().map(|r| decode(r, columns)).collect() + } + + async fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let row = sqlx::query_with(sql, args(binds)?).fetch_one(&mut *self).await?; + Ok(row.try_get::(0)?) + } + + async fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let done = sqlx::query_with(sql, args(binds)?).execute(&mut *self).await?; + Ok(done.rows_affected()) + } + } +} + +#[cfg(feature = "sqlite")] +mod sqlite { + use super::*; + use sqlx::sqlite::{SqliteArguments, SqliteRow}; + use sqlx::{Arguments, Row, TypeInfo, ValueRef}; + + fn args(binds: Vec) -> Result, StoreError> { + let mut a = SqliteArguments::default(); + for b in binds { + let r = match b { + Bind::Null => a.add(Option::::None), + Bind::Bool(v) => a.add(i64::from(v)), + Bind::Int(v) => a.add(v), + Bind::Real(v) => a.add(v), + Bind::Text(v) => a.add(v), + Bind::Ints(v) => a.add(Value::from(v).to_string()), + Bind::Texts(v) => a.add(Value::from(v).to_string()), + }; + r.map_err(|e| StoreError::Database(sqlx::Error::Encode(e)))?; + } + Ok(a) + } + + /// One stored value, by the storage class SQLite gave it. + enum Stored { + Null, + Int(i64), + Real(f64), + Text(String), + } + + fn stored(row: &SqliteRow, i: usize, field: &str) -> Result { + let raw = row.try_get_raw(i).map_err(|e| decode_err(field, e))?; + if raw.is_null() { + return Ok(Stored::Null); + } + let class = raw.type_info().name().to_string(); + Ok(match class.as_str() { + "INTEGER" | "BOOLEAN" => { + Stored::Int(row.try_get::(i).map_err(|e| decode_err(field, e))?) + } + "REAL" => Stored::Real(row.try_get::(i).map_err(|e| decode_err(field, e))?), + _ => Stored::Text(row.try_get::(i).map_err(|e| decode_err(field, e))?), + }) + } + + fn from_stored(field: &str, kind: Kind, s: Stored) -> Result { + Ok(match (kind, s) { + (_, Stored::Null) => Value::Null, + (Kind::Bool, Stored::Int(i)) => Value::Bool(i != 0), + (Kind::IntEnum(map), Stored::Int(i)) => int_enum_member(field, map, i)?, + (Kind::StringEnum(map), Stored::Text(t)) => string_enum_member(field, map, &t)?, + (Kind::Decimal, Stored::Int(i)) => Value::String(i.to_string()), + (Kind::Decimal, Stored::Real(r)) => decimal_real(field, r)?, + (Kind::Decimal, Stored::Text(t)) => decimal_text(field, &t)?, + (Kind::Duration, Stored::Int(micros)) => duration_nanos(i128::from(micros) * 1000), + (Kind::Json, Stored::Text(t)) => { + serde_json::from_str(&t).map_err(|e| decode_err(field, e))? + } + (Kind::Int | Kind::Long, Stored::Int(i)) => Value::from(i), + (Kind::Double | Kind::Float, Stored::Int(i)) => Value::from(i as f64), + (Kind::Double | Kind::Float, Stored::Real(r)) => number(field, r)?, + (_, Stored::Text(t)) => Value::String(t), + (_, Stored::Int(i)) => Value::from(i), + (_, Stored::Real(r)) => number(field, r)?, + }) + } + + /// An element of an array column, which is JSON text. + fn element(field: &str, kind: Kind, v: Value) -> Result { + let s = match v { + Value::Null => Stored::Null, + Value::Bool(b) => Stored::Int(i64::from(b)), + Value::Number(n) => match n.as_i64() { + Some(i) => Stored::Int(i), + None => Stored::Real(n.as_f64().unwrap_or(f64::NAN)), + }, + Value::String(t) => Stored::Text(t), + other => return Ok(other), + }; + from_stored(field, kind, s) + } + + fn decode(row: &SqliteRow, columns: &[Column]) -> Result, StoreError> { + let mut out = Map::new(); + for (i, c) in columns.iter().enumerate() { + let s = stored(row, i, c.field)?; + let v = if c.array { + match s { + Stored::Null => Value::Null, + Stored::Text(t) => match serde_json::from_str::(&t) + .map_err(|e| decode_err(c.field, e))? + { + Value::Array(items) => Value::Array( + items + .into_iter() + .map(|v| element(c.field, c.kind, v)) + .collect::>()?, + ), + _ => return Err(decode_err(c.field, "an array column holds a JSON list")), + }, + _ => return Err(decode_err(c.field, "an array column holds JSON text")), + } + } else { + from_stored(c.field, c.kind, s)? + }; + out.insert(c.field.to_string(), v); + } + Ok(out) + } + + impl Conn for sqlx::SqliteConnection { + fn engine(&self) -> Engine { + Engine::Sqlite + } + + async fn rows<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + columns: &'a [Column], + ) -> Result>, StoreError> { + let rows = sqlx::query_with(sql, args(binds)?).fetch_all(&mut *self).await?; + rows.iter().map(|r| decode(r, columns)).collect() + } + + async fn scalar<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let row = sqlx::query_with(sql, args(binds)?).fetch_one(&mut *self).await?; + Ok(row.try_get::(0)?) + } + + async fn execute<'a>( + &'a mut self, + sql: &'a str, + binds: Vec, + ) -> Result { + let done = sqlx::query_with(sql, args(binds)?).execute(&mut *self).await?; + Ok(done.rows_affected()) + } + } +} + +// ---- statements ---------------------------------------------------------------------------- + +fn where_filter(sql: &mut Sql, table: &Table, f: &Filter) -> Result<(), StoreError> { + match f { + Filter::And(all) if all.is_empty() => sql.push("1 = 1"), + Filter::Or(any) if any.is_empty() => sql.push("1 = 0"), + Filter::And(all) | Filter::Or(all) => { + let joiner = if matches!(f, Filter::And(_)) { " AND " } else { " OR " }; + sql.push("("); + for (i, f) in all.iter().enumerate() { + if i > 0 { + sql.push(joiner); + } + where_filter(sql, table, f)?; + } + sql.push(")"); + } + Filter::Search { fields, .. } if fields.is_empty() => sql.push("1 = 0"), + Filter::Search { term, fields } => { + // Postgres' ILIKE ignores case; SQLite's LIKE already does, for ASCII. + let like = match sql.engine { + Engine::Postgres => "ILIKE", + Engine::Sqlite => "LIKE", + }; + sql.push("("); + for (i, field) in fields.iter().enumerate() { + let c = *table.column(field)?; + if c.kind != Kind::Text || c.array { + return Err(bad(field, "a search matches text")); + } + if i > 0 { + sql.push(" OR "); + } + sql.push(&format!("{} {like} ", quote(c.column))); + sql.param(Bind::Text(format!("%{term}%")), &c); + } + sql.push(")"); + } + Filter::Field { field, op, value } => { + let c = *table.column(field)?; + if (c.array || c.kind == Kind::Json) && *op != Op::IsNull { + return Err(bad(field, "a list or a JSON value takes only `isNull`")); + } + let col = quote(c.column); + match op { + Op::IsNull => { + let yes = value + .as_bool() + .ok_or_else(|| bad(field, "`isNull` takes true or false"))?; + sql.push(&format!("{col} IS {}NULL", if yes { "" } else { "NOT " })); + } + Op::Eq | Op::Ne if value.is_null() => { + sql.push(&format!("{col} IS {}NULL", if *op == Op::Ne { "NOT " } else { "" })); + } + Op::In => { + let Value::Array(items) = value else { + return Err(bad(field, "`in` takes a list")); + }; + if items.is_empty() { + sql.push("1 = 0"); + return Ok(()); + } + sql.push(&format!("{col} IN (")); + for (i, item) in items.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + let b = scalar_bind(sql.engine, field, c.kind, item)?; + sql.param(b, &c); + } + sql.push(")"); + } + Op::Like => { + if c.kind != Kind::Text { + return Err(bad(field, "`like` applies to text")); + } + // `like` is case-sensitive (ADR-0049). SQLite's LIKE ignores ASCII case, + // so there the pattern runs as the GLOB it means. + match (sql.engine, scalar_bind(sql.engine, field, c.kind, value)?) { + (Engine::Sqlite, Bind::Text(pattern)) => { + sql.push(&format!("{col} GLOB ")); + sql.param(Bind::Text(like_to_glob(&pattern)), &c); + } + (_, b) => { + sql.push(&format!("{col} LIKE ")); + sql.param(b, &c); + } + } + } + _ => { + let b = scalar_bind(sql.engine, field, c.kind, value)?; + sql.push(&format!("{col} {} ", op.sql())); + sql.param(b, &c); + } + } + } + } + Ok(()) +} + +/// A `LIKE` pattern as the GLOB that matches the same text, case-sensitively. +fn like_to_glob(pattern: &str) -> String { + let mut out = String::with_capacity(pattern.len()); + for ch in pattern.chars() { + match ch { + '%' => out.push('*'), + '_' => out.push('?'), + '*' => out.push_str("[*]"), + '?' => out.push_str("[?]"), + '[' => out.push_str("[[]"), + c => out.push(c), + } + } + out +} + +fn where_condition(sql: &mut Sql, table: &Table, cond: &Condition) -> Result<(), StoreError> { + match cond { + Condition::Compare { op, left, right } => { + sql.push("("); + operand_sql(sql, table, left, right.stored_field())?; + sql.push(&format!(" {} ", op.sql())); + operand_sql(sql, table, right, left.stored_field())?; + sql.push(")"); + } + Condition::IsNull { operand, not } => { + sql.push("("); + operand_sql(sql, table, operand, None)?; + sql.push(&format!(" IS {}NULL)", if *not { "NOT " } else { "" })); + } + Condition::Not(inner) => { + sql.push("(NOT "); + where_condition(sql, table, inner)?; + sql.push(")"); + } + Condition::And(all) | Condition::Or(all) => { + let (join, empty) = if matches!(cond, Condition::And(_)) { + (" AND ", "1 = 1") + } else { + (" OR ", "1 = 0") + }; + if all.is_empty() { + sql.push(empty); + return Ok(()); + } + sql.push("("); + for (i, c) in all.iter().enumerate() { + if i > 0 { + sql.push(join); + } + where_condition(sql, table, c)?; + } + sql.push(")"); + } + } + Ok(()) +} + +/// One operand; a literal takes the stored form of `partner`, the field it is compared with. +fn operand_sql( + sql: &mut Sql, + table: &Table, + operand: &Operand, + partner: Option<&str>, +) -> Result<(), StoreError> { + match operand { + Operand::Field(f) => { + let c = *table.column(f)?; + if c.array || c.kind == Kind::Json { + return Err(bad(f, "a condition compares no list or JSON value")); + } + sql.push("e(c.column)); + } + Operand::Value(v) => match partner { + Some(f) => { + let c = *table.column(f)?; + let b = scalar_bind(sql.engine, f, c.kind, v)?; + sql.param(b, &c); + } + None => { + let b = match v { + Value::Null => Bind::Null, + Value::Bool(b) => Bind::Bool(*b), + Value::String(s) => Bind::Text(s.clone()), + Value::Number(n) => match n.as_i64() { + Some(i) => Bind::Int(i), + None => Bind::Real(n.as_f64().unwrap_or_default()), + }, + _ => return Err(bad("condition", "a literal is a scalar")), + }; + sql.raw_param(b); + } + }, + Operand::Coalesce(items) => { + // The arguments of a coalesce share its type, so a literal among them takes the + // first field's form. + let own = operand.stored_field().or(partner); + sql.push("COALESCE("); + for (i, item) in items.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + operand_sql(sql, table, item, own)?; + } + sql.push(")"); + } + } + Ok(()) +} + +/// ` AND "" = ` (or ` WHERE ...` when `first`), for a subtype. +fn scope(sql: &mut Sql, table: &Table, first: bool) -> Result<(), StoreError> { + if let Some((field, value)) = table.discriminator { + let c = *table.column(field)?; + sql.push(&format!(" {} {} = ", if first { "WHERE" } else { "AND" }, quote(c.column))); + sql.param(Bind::Text(value.to_string()), &c); + } + Ok(()) +} + +fn select(engine: Engine, table: &Table) -> Sql { + let mut sql = Sql::new(engine); + sql.push(&format!("SELECT {} FROM {}", select_list(engine, table), table_ref(table))); + sql +} + +fn key_where(sql: &mut Sql, table: &Table, key: &Value) -> Result<(), StoreError> { + let c = *table.key_column()?; + let b = scalar_bind(sql.engine, c.field, c.kind, key)?; + sql.push(&format!(" WHERE {} = ", quote(c.column))); + sql.param(b, &c); + scope(sql, table, false) +} + +fn rows_into( + table: &Table, + rows: Vec>, +) -> Result, StoreError> { + rows.into_iter() + .map(|r| serde_json::from_value(Value::Object(r)).map_err(|e| decode_err(table.object, e))) + .collect() +} + +fn body_of(table: &Table, body: &B) -> Result, StoreError> { + match serde_json::to_value(body) { + Ok(Value::Object(m)) => Ok(m), + Ok(_) => Err(bad(table.object, "a body is an object")), + Err(e) => Err(bad(table.object, e.to_string())), + } +} + +/// The row with key `key`, or `None`. +pub async fn get( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + get_value(c, table.reader(), &key).await +} + +async fn get_value( + c: &mut C, + table: &Table, + key: &Value, +) -> Result, StoreError> { + let mut sql = select(c.engine(), table); + key_where(&mut sql, table, key)?; + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + Ok(rows_into(table, rows)?.into_iter().next()) +} + +/// The row with key `key`, or `None`, read to be written in the same transaction: on Postgres +/// under a row lock (`FOR UPDATE`), held until the transaction ends, so a second writer waits +/// for the first. SQLite locks the whole database for a writer, so it reads the row as `get` +/// does. +pub async fn get_for_update( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let mut sql = select(c.engine(), table); + key_where(&mut sql, table, &key)?; + if sql.engine == Engine::Postgres { + sql.push(" FOR UPDATE"); + } + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + let row = rows_into(table, rows)?.into_iter().next(); + match table.read { + // Locked through the table; read, with what it derives, through the view. + Some(read) if row.is_some() => get_value(c, read, &key).await, + _ => Ok(row), + } +} + +/// The `target` rows related through `through` to the row whose key is `key`, in no order (a +/// relationship is a set). A subtype target answers only its own rows. +pub async fn related( + c: &mut C, + target: &Table, + through: &Through, + key: impl Serialize, +) -> Result, StoreError> { + let key = serde_json::to_value(key).map_err(|e| bad(target.object, e.to_string()))?; + let target = target.reader(); + let engine = c.engine(); + let (s, t) = (&through.source, &through.target); + let junction = match through.schema { + Some(schema) => format!("{}.{}", quote(schema), quote(through.name)), + None => quote(through.name), + }; + let mut sql = select(engine, target); + sql.push(&format!(" WHERE {} IN (SELECT ", quote(target.key_column()?.column))); + let param = |sql: &mut Sql| -> Result<(), StoreError> { + let b = scalar_bind(engine, s.field, s.kind, &key)?; + sql.param(b, s); + Ok(()) + }; + if through.symmetric { + // The side of each row that is not the source; a row relating a row to itself is + // that row. + sql.push(&format!("CASE WHEN {} = ", quote(s.column))); + param(&mut sql)?; + sql.push(&format!( + " THEN {} ELSE {} END FROM {junction} WHERE {} = ", + quote(t.column), + quote(s.column), + quote(s.column) + )); + param(&mut sql)?; + sql.push(&format!(" OR {} = ", quote(t.column))); + param(&mut sql)?; + } else { + sql.push(&format!("{} FROM {junction} WHERE {} = ", quote(t.column), quote(s.column))); + param(&mut sql)?; + } + sql.push(")"); + scope(&mut sql, target, false)?; + let rows = c.rows(&sql.text, sql.binds, target.columns).await?; + rows_into(target, rows) +} + +/// The rows a query selects, in its order and page. +pub async fn list( + c: &mut C, + table: &Table, + query: &Query, +) -> Result, StoreError> { + let table = table.reader(); + let mut sql = select(c.engine(), table); + scope(&mut sql, table, true)?; + if let Some(f) = &query.filter { + sql.push(if table.discriminator.is_some() { " AND " } else { " WHERE " }); + where_filter(&mut sql, table, f)?; + } + if !query.sort.is_empty() { + let mut order = Vec::new(); + for s in &query.sort { + let col = table.column(&s.field)?; + // A null sorts as larger than any value. + order.push(if s.descending { + format!("{} DESC NULLS FIRST", quote(col.column)) + } else { + format!("{} ASC NULLS LAST", quote(col.column)) + }); + } + sql.push(&format!(" ORDER BY {}", order.join(", "))); + } + match (query.limit, query.offset) { + (Some(l), Some(o)) => sql.push(&format!(" LIMIT {l} OFFSET {o}")), + (Some(l), None) => sql.push(&format!(" LIMIT {l}")), + (None, Some(o)) => sql.push(&match sql.engine { + Engine::Postgres => format!(" OFFSET {o}"), + Engine::Sqlite => format!(" LIMIT -1 OFFSET {o}"), + }), + (None, None) => {} + } + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + rows_into(table, rows) +} + +/// The number of rows a filter selects. +pub async fn count( + c: &mut C, + table: &Table, + filter: Option<&Filter>, +) -> Result { + let table = table.reader(); + let mut sql = Sql::new(c.engine()); + sql.push(&format!("SELECT COUNT(*) FROM {}", table_ref(table))); + scope(&mut sql, table, true)?; + if let Some(f) = filter { + sql.push(if table.discriminator.is_some() { " AND " } else { " WHERE " }); + where_filter(&mut sql, table, f)?; + } + let n = c.scalar(&sql.text, sql.binds).await?; + Ok(u64::try_from(n).unwrap_or(0)) +} + +/// Inserts the members `body` carries and reads the row back. +pub async fn create( + c: &mut C, + table: &Table, + body: &B, +) -> Result { + table.require_writable()?; + let mut body = body_of(table, body)?; + if let Some((field, value)) = table.discriminator { + match body.get(field) { + None | Some(Value::Null) => { + body.insert(field.to_string(), Value::String(value.to_string())); + } + Some(Value::String(v)) if v == value => {} + Some(_) => return Err(bad(field, format!("a {} is always `{value}`", table.object))), + } + } + let engine = c.engine(); + let mut sql = Sql::new(engine); + let mut names = Vec::new(); + let mut values = Sql::new(engine); + for (field, v) in &body { + let col = *table.column(field)?; + names.push(quote(col.column)); + if !values.text.is_empty() { + values.push(", "); + } + let b = bind_of(engine, &col, v)?; + values.param(b, &col); + } + if names.is_empty() { + sql.push(&format!("INSERT INTO {} DEFAULT VALUES", table_ref(table))); + } else { + // The values were numbered from 1, as they are the statement's only binds. + sql.push(&format!( + "INSERT INTO {} ({}) VALUES ({})", + table_ref(table), + names.join(", "), + values.text + )); + sql.binds = values.binds; + } + sql.push(&format!(" RETURNING {}", select_list(engine, table))); + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + let none = || StoreError::Unsupported(format!("{}: the insert returned no row", table.object)); + let row = rows.into_iter().next().ok_or_else(none)?; + match table.read { + Some(read) => { + let key = row.get(table.key_column()?.field).cloned().unwrap_or(Value::Null); + get_value(c, read, &key).await?.ok_or_else(none) + } + None => rows_into(table, vec![row])?.into_iter().next().ok_or_else(none), + } +} + +/// Sets the members `patch` carries on the row with key `key` and reads it back; `None` when +/// there is no such row. +pub async fn update( + c: &mut C, + table: &Table, + key: impl Serialize, + patch: &B, +) -> Result, StoreError> { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let body = body_of(table, patch)?; + if let Some((field, value)) = table.discriminator { + if body.get(field).is_some_and(|v| v.as_str() != Some(value)) { + return Err(bad(field, "the discriminator never changes")); + } + } + if body.is_empty() { + return get_value(c, table.reader(), &key).await; + } + let engine = c.engine(); + let mut sql = Sql::new(engine); + sql.push(&format!("UPDATE {} SET ", table_ref(table))); + for (i, (field, v)) in body.iter().enumerate() { + let col = *table.column(field)?; + if i > 0 { + sql.push(", "); + } + sql.push(&format!("{} = ", quote(col.column))); + let b = bind_of(engine, &col, v)?; + sql.param(b, &col); + } + key_where(&mut sql, table, &key)?; + sql.push(&format!(" RETURNING {}", select_list(engine, table))); + let rows = c.rows(&sql.text, sql.binds, table.columns).await?; + match table.read { + Some(read) if !rows.is_empty() => get_value(c, read, &key).await, + _ => Ok(rows_into(table, rows)?.into_iter().next()), + } +} + +/// Deletes the row with key `key`; `false` when there was none. +pub async fn delete( + c: &mut C, + table: &Table, + key: impl Serialize, +) -> Result { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let mut sql = Sql::new(c.engine()); + sql.push(&format!("DELETE FROM {}", table_ref(table))); + key_where(&mut sql, table, &key)?; + Ok(c.execute(&sql.text, sql.binds).await? > 0) +} + +/// The guarded update of a lifecycle (ADR-0066 §6 step 5): sets `state` to `to` on the row +/// with key `key` only while its state is one of `from` and `condition` (a transition's +/// `@condition`, when it has one) holds, in one statement. `false` when no row matched: the +/// row is gone, its condition fails, or another writer moved it first. The caller re-reads to +/// tell which. +pub async fn transition( + c: &mut C, + table: &Table, + key: impl Serialize, + state: &str, + from: &[S], + to: &S, + condition: Option<&Condition>, +) -> Result { + table.require_writable()?; + let key = serde_json::to_value(key).map_err(|e| bad(table.object, e.to_string()))?; + let value = |s: &S| serde_json::to_value(s).map_err(|e| bad(state, e.to_string())); + let col = *table.column(state)?; + let engine = c.engine(); + let mut sql = Sql::new(engine); + sql.push(&format!("UPDATE {} SET {} = ", table_ref(table), quote(col.column))); + sql.param(scalar_bind(engine, state, col.kind, &value(to)?)?, &col); + key_where(&mut sql, table, &key)?; + if from.is_empty() { + return Ok(false); + } + sql.push(&format!(" AND {} IN (", quote(col.column))); + for (i, f) in from.iter().enumerate() { + if i > 0 { + sql.push(", "); + } + sql.param(scalar_bind(engine, state, col.kind, &value(f)?)?, &col); + } + sql.push(")"); + if let Some(cond) = condition { + sql.push(" AND "); + where_condition(&mut sql, table, cond)?; + } + Ok(c.execute(&sql.text, sql.binds).await? == 1) +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index f517681ed0..db01261e30 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -512,6 +512,24 @@ fn toml_key_string(line: &str, key: &str) -> Option { None } +/// A generator the run applies: one the host offered, or the one an entry's options +/// constructed in its place. +enum Selected<'g> { + Offered(&'g dyn Generator), + Configured(Box), +} + +impl<'g> std::ops::Deref for Selected<'g> { + type Target = dyn Generator + 'g; + + fn deref(&self) -> &Self::Target { + match self { + Selected::Offered(g) => *g, + Selected::Configured(g) => g.as_ref(), + } + } +} + /// Everything a run knows before it renders: the loaded model, where the files go, the /// manifest and the skip key. struct Prepared<'g> { @@ -521,7 +539,7 @@ struct Prepared<'g> { out_rel: String, gen_state: PathBuf, manifest: HashManifest, - selected: Vec<&'g dyn Generator>, + selected: Vec>, cacheable: bool, key: String, stored: Option, @@ -582,7 +600,8 @@ fn prepare<'g>( let start = Instant::now(); // 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)?; + let entries = generator_list::read(&project_root).map_err(RunError::GeneratorList)?; + let listed = entries.as_deref().map(generator_list::names); 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)?; @@ -596,20 +615,47 @@ fn prepare<'g>( 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(); + // With no list, an opt-in generator never runs, and a flag naming it says so. + if listed.is_none() + && let Some(flagged) = &opts.generators + && let Some(out) = flagged.iter().find(|n| !generator_list::runs_unlisted(n)) + { + return Err(RunError::GeneratorList(format!( + "the generator {out} is opt-in and runs only when the project's {} lists it; add it \ + there (`cargo meta init --transport` writes a list with it)", + generator_list::GENERATOR_LIST_FILE, + ))); + } + // An entry with options constructs its generator from them, and that one runs in the + // offered generator's place; a generator refuses an option it does not take. + let mut selected: Vec> = Vec::with_capacity(generators.len()); + for g in generators { + let in_list = match &listed { + Some(l) => l.iter().any(|n| n == g.name()), + None => generator_list::runs_unlisted(g.name()), + }; + let flagged = opts + .generators + .as_ref() + .is_none_or(|names| names.iter().any(|n| n == g.name())); + if !in_list { + continue; + } + let options = entries + .as_deref() + .and_then(|es| es.iter().find(|e| e.name == g.name())) + .map(|e| &e.options) + .filter(|o| !o.is_empty()); + // Every listed entry's options are checked, even on a run `--generators` narrows, so + // a misspelt option fails the first run rather than the first one that includes it. + let chosen = match options { + Some(o) => Selected::Configured(g.configure(o).map_err(RunError::Generator)?), + None => Selected::Offered(g.as_ref()), + }; + if flagged { + selected.push(chosen); + } + } let out_dir = normalize(&if opts.out_dir.is_absolute() { opts.out_dir.clone() } else { diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 98b16ddb47..08ab6a2e61 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -56,7 +56,9 @@ use metaobjects_codegen::plan::{ Class, CmpOp, Cond, CratePlan, CrossKind, CrossRule, EnumPlan, FieldPlan, Format, Kind, Literal, NullMembers, Operand, Plan, Presence, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, Piece, RUSTFMT_TOML, file, item, list}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, Piece, RUSTFMT_TOML, file, fixed, item, list, sibling_dep, toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 2; @@ -64,7 +66,7 @@ const FORMAT: u32 = 2; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`."; const VALIDATION: &str = "meta_support::validation"; const WIRE: &str = "meta_support::wire"; @@ -85,46 +87,147 @@ impl Generator for EntityGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = support_crate(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - model_crate(&plan, cname, c, &mut files)?; + self.render(ctx) + } +} + +impl EntityParts for EntityGenerator {} + +/// The pieces of the entity generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece, so a generator of your own implements this, overrides the +/// piece it wants changed, and keeps taking every other change the shipped generator gets: +/// +/// ```ignore +/// struct MyEntity; +/// +/// impl EntityParts for MyEntity { +/// fn enum_item(&self, w: &mut CodeWriter, e: &EnumPlan) { +/// w.line("#[non_exhaustive]"); +/// entity::enum_item(w, e); +/// } +/// } +/// +/// impl Generator for MyEntity { +/// fn name(&self) -> &str { +/// "entity" +/// } +/// fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { +/// self.render(ctx) +/// } +/// } +/// ``` +/// +/// An override can call the shipped piece, a public function of this module with the same +/// name, and add to it. These methods are not a stability contract: they may be renamed, split +/// or change signature in a minor release, and the CHANGELOG says when. Eject for a contract. +pub trait EntityParts { + /// Every file: the support crate, then one model crate per package the run selects. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) + } + + /// The support crate's files. + fn support_crate(&self) -> Vec { + support_crate() + } + + /// A model crate's `Cargo.toml`. + fn manifest(&self, name: &str, c: &CratePlan) -> String { + cargo_toml(name, c) + } + + /// A model crate's `src/lib.rs`: each module and what it exports. + fn lib_file(&self, package: &str, items: &[(String, Vec)]) -> String { + lib_file(package, items) + } + + /// One object's file: its struct, its create and patch bodies with their `validate()` + /// (or, for a value object, its own `validate()`), and its enums. + fn struct_file( + &self, + plan: &Plan, + s: &StructPlan, + current: &str, + q: &Qualifier<'_>, + ) -> Result { + struct_file(self, plan, s, current, q) + } + + /// One of an object's structs: the read type, the create body or the patch body. + fn struct_item( + &self, + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + current: &str, + q: &Qualifier<'_>, + ) { + struct_item(w, plan, s, shape, current, q); + } + + /// The `validate()` of one of an object's structs. + fn validate_item( + &self, + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + q: &Qualifier<'_>, + ) { + validate_item(w, plan, s, shape, q); + } + + /// One enum. + fn enum_item(&self, w: &mut CodeWriter, e: &EnumPlan) { + enum_item(w, e); + } +} + +/// The shipped [`EntityParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = parts.support_crate(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; } - Ok(files) + model_crate(parts, &plan, cname, c, &mut files)?; } + Ok(files) } // ---- crates ---------------------------------------------------------------------------- /// The crate of wire types and checks the model crates share. It is generated, so the /// output depends on nothing from MetaObjects. -fn support_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"Wire types and validation checks for the generated MetaObjects model crates.\"\n\ - \n\ - [dependencies]\n\ - serde = \"1\"\n", - literal(SUPPORT_CRATE) - ); - let lib = format!( - "{BANNER}\n\ - \n\ - //! What every generated model crate uses: the exact `Decimal` and the ISO-8601\n\ - //! `Duration` of the wire form, and the checks `validate()` is written in.\n\ - \n\ - pub mod pattern;\n\ - pub mod validation;\n\ - pub mod wire;\n" +pub fn support_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, SUPPORT_CRATE); + m.entry( + "description", + &toml_string( + "Wire types and validation checks for the generated MetaObjects model crates.", + ), ); + m.blank() + .table("dependencies") + .entry("serde", &toml_string("1")); + let manifest = m.finish(); + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); + w.line("//! What every generated model crate uses: the exact `Decimal` and the ISO-8601"); + w.line("//! `Duration` of the wire form, and the checks `validate()` is written in."); + w.blank(); + for module in ["pattern", "validation", "wire"] { + w.line(format!("pub mod {module};")); + } + let lib = w + .finish() + .expect("the support crate's lib.rs opens no block"); let file = |name: &str, text: &str| { EmittedFile::new(format!("{SUPPORT_CRATE}/{name}"), text.to_string()) }; @@ -132,13 +235,14 @@ fn support_crate() -> Vec { file("Cargo.toml", &manifest), file("rustfmt.toml", RUSTFMT_TOML), file("src/lib.rs", &lib), - file("src/pattern.rs", &format!("{BANNER}\n\n{PATTERN_RS}")), - file("src/validation.rs", &format!("{BANNER}\n\n{VALIDATION_RS}")), - file("src/wire.rs", &format!("{BANNER}\n\n{WIRE_RS}")), + file("src/pattern.rs", &fixed(BANNER, PATTERN_RS)), + file("src/validation.rs", &fixed(BANNER, VALIDATION_RS)), + file("src/wire.rs", &fixed(BANNER, WIRE_RS)), ] } -fn model_crate( +fn model_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -146,24 +250,13 @@ fn model_crate( ) -> Result<(), GenError> { files.push(EmittedFile::new( format!("{cname}/Cargo.toml"), - cargo_toml(cname, c), + parts.manifest(cname, c), )); files.push(EmittedFile::new( format!("{cname}/rustfmt.toml"), RUSTFMT_TOML.to_string(), )); - let shadowed: HashSet<&str> = c - .structs - .iter() - .flat_map(|&i| { - let s = &plan.structs[i]; - std::iter::once(s.type_name.as_str()) - .chain(s.enums.iter().map(|e| e.type_name.as_str())) - }) - .chain(c.shared_enums.iter().map(|(_, e)| e.type_name.as_str())) - .filter(|n| PRELUDE_TYPES.contains(n)) - .collect(); - let q = Qualifier { shadowed }; + let q = Qualifier::of(plan, c); let mut lib_items: Vec<(String, Vec)> = Vec::new(); for &i in &c.structs { @@ -175,7 +268,7 @@ fn model_crate( } exports.extend(s.enums.iter().map(|e| e.type_name.clone())); lib_items.push((s.module(), exports)); - let text = struct_file(plan, s, cname, &q)?; + let text = parts.struct_file(plan, s, cname, &q)?; files.push(EmittedFile::new( format!("{cname}/src/{}.rs", s.module()), text, @@ -184,64 +277,60 @@ fn model_crate( for (_, e) in &c.shared_enums { let module = module_name(&e.type_name); lib_items.push((module.clone(), vec![e.type_name.clone()])); - let text = file(BANNER, &[item(|w| enum_item(w, e))?]); + let text = file(BANNER, &[item(|w| parts.enum_item(w, e))?]); files.push(EmittedFile::new(format!("{cname}/src/{module}.rs"), text)); } lib_items.sort(); files.push(EmittedFile::new( format!("{cname}/src/lib.rs"), - lib_file(&c.package, &lib_items), + parts.lib_file(&c.package, &lib_items), )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`EntityParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); if !c.package.is_empty() { - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "Generated from the MetaObjects package {}.", c.package - )) - )); + )), + ); } - out.push_str("\n[dependencies]\n"); - out.push_str("serde = { version = \"1\", features = [\"derive\"] }\n"); - out.push_str(&format!( - "{SUPPORT_CRATE} = {{ path = \"../{SUPPORT_CRATE}\" }}\n" - )); + m.blank().table("dependencies"); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + m.entry(SUPPORT_CRATE, &sibling_dep(SUPPORT_CRATE)); for dep in &c.deps { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } -fn lib_file(package: &str, items: &[(String, Vec)]) -> String { - let mut out = format!("{BANNER}\n\n"); +/// The shipped [`EntityParts::lib_file`]. +pub fn lib_file(package: &str, items: &[(String, Vec)]) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); if package.is_empty() { - out.push_str("//! Generated from the MetaObjects model that declares no package.\n"); + w.line("//! Generated from the MetaObjects model that declares no package."); } else { - out.push_str(&format!( - "//! Generated from the MetaObjects package `{package}`.\n" + w.line(format!( + "//! Generated from the MetaObjects package `{package}`." )); } - out.push('\n'); + w.blank(); for (module, _) in items { - out.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - out.push('\n'); + w.blank(); for (module, exports) in items { for e in exports { - out.push_str(&format!("pub use {module}::{e};\n")); + w.line(format!("pub use {module}::{e};")); } } - out + w.finish().expect("a lib.rs opens no block") } // ---- text ------------------------------------------------------------------------------ @@ -252,12 +341,29 @@ fn text(s: impl Into) -> Piece { /// Spells a std type by its short name, or by its full path in a crate that declares a type /// with the same name (an object called `Option` must not capture the field types). -struct Qualifier<'a> { +pub struct Qualifier<'a> { shadowed: HashSet<&'a str>, } -impl Qualifier<'_> { - fn std(&self, short: &'static str, full: &'static str) -> &'static str { +impl<'a> Qualifier<'a> { + /// The qualifier of the crate `c`: the std types its own types shadow. + pub fn of(plan: &'a Plan, c: &'a CratePlan) -> Self { + let shadowed = c + .structs + .iter() + .flat_map(|&i| { + let s = &plan.structs[i]; + std::iter::once(s.type_name.as_str()) + .chain(s.enums.iter().map(|e| e.type_name.as_str())) + }) + .chain(c.shared_enums.iter().map(|(_, e)| e.type_name.as_str())) + .filter(|n| PRELUDE_TYPES.contains(n)) + .collect(); + Qualifier { shadowed } + } + + /// `short`, or `full` when the crate declares a type named `short`. + pub fn std(&self, short: &'static str, full: &'static str) -> &'static str { if self.shadowed.contains(short) { full } else { @@ -265,11 +371,11 @@ impl Qualifier<'_> { } } - fn vec(&self) -> &'static str { + pub fn vec(&self) -> &'static str { self.std("Vec", "std::vec::Vec") } - fn option(&self) -> &'static str { + pub fn option(&self) -> &'static str { self.std("Option", "std::option::Option") } } @@ -292,8 +398,8 @@ fn render_ty(ty: &Ty, current: &str, q: &Qualifier<'_>) -> String { } /// Which of an object's three types a member belongs to. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Shape { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shape { Read, Create, Patch, @@ -345,7 +451,8 @@ fn member_type(f: &FieldPlan, shape: Shape, current: &str, q: &Qualifier<'_>) -> } } -fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { +/// The shipped [`EntityParts::enum_item`]. +pub fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { if let Some(doc) = &e.doc { w.doc(doc); } @@ -378,7 +485,8 @@ fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { }); } -fn struct_item( +/// The shipped [`EntityParts::struct_item`]. +pub fn struct_item( w: &mut CodeWriter, plan: &Plan, s: &StructPlan, @@ -405,9 +513,10 @@ fn struct_item( } Shape::Patch => { w.doc(&format!( - "A change to one `{}`: a member left `None` is not touched. A member the model lets be\nnull is `Some(None)` to set it to null.", + "A change to one `{}`: a member left `None` is not touched. A member the model lets be", s.type_name )); + w.doc("null is `Some(None)` to set it to null."); } } let default = if derive_default { "Default, " } else { "" }; @@ -1014,7 +1123,14 @@ fn cross_check(s: &StructPlan, rule: &CrossRule, n: &mut usize, out: &mut Vec) { +/// The shipped [`EntityParts::validate_item`]. +pub fn validate_item( + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + q: &Qualifier<'_>, +) { let name = match shape { Shape::Read => s.type_name.clone(), Shape::Create => s.create_name(), @@ -1049,23 +1165,27 @@ fn validate_item(w: &mut CodeWriter, plan: &Plan, s: &StructPlan, shape: Shape, }); } -fn struct_file( +/// The shipped [`EntityParts::struct_file`], through `parts`. +pub fn struct_file( + parts: &P, plan: &Plan, s: &StructPlan, current: &str, q: &Qualifier<'_>, ) -> Result { - let mut items = vec![item(|w| struct_item(w, plan, s, Shape::Read, current, q))?]; + let mut items = vec![item(|w| { + parts.struct_item(w, plan, s, Shape::Read, current, q) + })?]; if s.is_entity { for shape in [Shape::Create, Shape::Patch] { - items.push(item(|w| struct_item(w, plan, s, shape, current, q))?); - items.push(item(|w| validate_item(w, plan, s, shape, q))?); + items.push(item(|w| parts.struct_item(w, plan, s, shape, current, q))?); + items.push(item(|w| parts.validate_item(w, plan, s, shape, q))?); } } else { - items.push(item(|w| validate_item(w, plan, s, Shape::Read, q))?); + items.push(item(|w| parts.validate_item(w, plan, s, Shape::Read, q))?); } for e in &s.enums { - items.push(item(|w| enum_item(w, e))?); + items.push(item(|w| parts.enum_item(w, e))?); } Ok(file(BANNER, &items)) } diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index 3ffd047c6d..d2338d2c71 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -84,6 +84,34 @@ pub const ERR_UNSUPPORTED: &str = "ERR_RUST_UNSUPPORTED"; pub const ERR_CRATE_CYCLE: &str = "ERR_CRATE_CYCLE"; /// The output directory is not inside the project. pub const ERR_OUT_DIR: &str = "ERR_OUT_DIR_OUTSIDE_PROJECT"; +/// A project gave a generator an option it does not take. +pub const ERR_UNKNOWN_OPTION: &str = "ERR_UNKNOWN_GENERATOR_OPTION"; + +/// The options a project wrote for one generator in `metaobjects.config.json`. +pub type Options = serde_json::Map; + +/// The refusal for options `generator` does not take, naming each one and what it takes +/// (`known`, empty for a generator that takes none). A generator's +/// [`Generator::configure`] returns it for any key outside `known`. +pub fn unknown_options(generator: &str, options: &Options, known: &[&str]) -> GenError { + let unknown: Vec = options + .keys() + .filter(|k| !known.contains(&k.as_str())) + .map(|k| format!("\"{k}\"")) + .collect(); + let takes = if known.is_empty() { + "it takes no options".to_string() + } else { + format!("it takes: {}", known.join(", ")) + }; + GenError::new( + ERR_UNKNOWN_OPTION, + format!( + "the generator {generator} has no option {}; {takes}", + unknown.join(", ") + ), + ) +} /// A code generator the run engine can drive. pub trait Generator { @@ -110,6 +138,18 @@ pub trait Generator { Vec::new() } + /// This generator built with the options a project wrote for it in + /// `metaobjects.config.json` (`{"name": "client", "options": {...}}`). Options go through a + /// generator's constructor: a generator that takes options overrides this to construct + /// itself from them, and refuses any key it does not know with [`unknown_options`]. The + /// default takes none and refuses every key, so a misspelt option fails the run instead + /// of being ignored. The engine calls it only for an entry that has options, and the + /// generator it returns runs in this one's place (its [`Generator::identity`] should + /// carry the options, since they can change what it emits). + fn configure(&self, options: &Options) -> Result, GenError> { + Err(unknown_options(self.name(), options, &[])) + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 1bfe090efa..42638257fb 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -5,12 +5,16 @@ //! the other ports, so changing the list never needs an eject: //! //! ```json -//! { "generators": ["entity", "client", "commands"] } +//! { "generators": ["entity", "rules-names", "contract-types", "repository", "service", "client", "commands", "render-helper", "output-parser", "output-prompt"] } //! ``` //! -//! 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 +//! An entry is a generator's name, or `{"name": "...", "options": {...}}` to construct it with +//! options: they reach the generator through [`crate::Generator::configure`], and a generator +//! refuses an option it does not take, so a misspelt one fails the run instead of being +//! ignored. The shipped generators take none yet. The list 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 but the opt-in ones (the `service-routes` transport, which brings a web framework into +//! the build), 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). //! @@ -20,16 +24,43 @@ use std::path::Path; use crate::eject; +use crate::generator::Options; /// 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 keys an entry written as an object takes. +const ENTRY_NAME: &str = "name"; +const ENTRY_OPTIONS: &str = "options"; + +/// One entry of the list: a generator, and the options the project constructs it with +/// (empty for an entry written as a bare name). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Entry { + pub name: String, + pub options: Options, +} + +impl Entry { + /// An entry with no options. + pub fn named(name: impl Into) -> Self { + Self { + name: name.into(), + options: Options::new(), + } + } +} + +/// The generator names of `entries`, in order. +pub fn names(entries: &[Entry]) -> Vec { + entries.iter().map(|e| e.name.clone()).collect() +} /// 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> { +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, @@ -40,7 +71,7 @@ pub fn read(project_root: &Path) -> Result>, String> { } /// The list in `text`, the contents of [`GENERATOR_LIST_FILE`]. -pub fn parse(text: &str) -> Result, String> { +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 { @@ -51,7 +82,7 @@ pub fn parse(text: &str) -> Result, String> { 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" + the generators to run, each a name or {{\"{ENTRY_NAME}\": ..., \"{ENTRY_OPTIONS}\": {{...}}}}. A layer is just a generator" )); } let Some(list) = object.get(KEY).and_then(|v| v.as_array()) else { @@ -61,21 +92,60 @@ pub fn parse(text: &str) -> Result, String> { example() )); }; - let mut names: Vec = Vec::with_capacity(list.len()); + let mut entries: Vec = Vec::with_capacity(list.len()); for item in list { - let Some(name) = item.as_str() else { + let entry = entry(item)?; + if entries.iter().any(|e| e.name == entry.name) { return Err(format!( - "{GENERATOR_LIST_FILE}: every entry of \"{KEY}\" is a generator name (a string), got {item}" + "{GENERATOR_LIST_FILE}: \"{}\" is listed twice; a generator runs once", + entry.name )); - }; - if names.iter().any(|n| n == name) { + } + entries.push(entry); + } + Ok(entries) +} + +/// One entry: a name, or an object with a `name` and optional `options`. +fn entry(item: &serde_json::Value) -> Result { + let shape = || { + format!( + "{GENERATOR_LIST_FILE}: every entry of \"{KEY}\" is a generator name (a string) or \ + {{\"{ENTRY_NAME}\": \"...\", \"{ENTRY_OPTIONS}\": {{...}}}}, got {item}" + ) + }; + if let Some(name) = item.as_str() { + return Ok(Entry::named(name)); + } + let Some(object) = item.as_object() else { + return Err(shape()); + }; + let Some(name) = object.get(ENTRY_NAME).and_then(|v| v.as_str()) else { + return Err(shape()); + }; + if let Some(unknown) = object + .keys() + .find(|k| k.as_str() != ENTRY_NAME && k.as_str() != ENTRY_OPTIONS) + { + return Err(format!( + "{GENERATOR_LIST_FILE}: the entry for \"{name}\" has an unknown key \"{unknown}\"; \ + an entry takes \"{ENTRY_NAME}\" and \"{ENTRY_OPTIONS}\" (the generator's own options)" + )); + } + let options = match object.get(ENTRY_OPTIONS) { + None => Options::new(), + Some(serde_json::Value::Object(o)) => o.clone(), + Some(other) => { return Err(format!( - "{GENERATOR_LIST_FILE}: \"{name}\" is listed twice; a generator runs once" + "{GENERATOR_LIST_FILE}: the \"{ENTRY_OPTIONS}\" of \"{name}\" must be an object of \ + option names to values, got {other}" )); } - names.push(name.to_string()); - } - Ok(names) + }; + Ok(Entry { + name: name.to_string(), + options, + }) } /// Check a list against the generators a host offers: each name is one of them, and a shipped @@ -106,12 +176,16 @@ pub fn check(names: &[String], available: &[&str]) -> Result<(), String> { Ok(()) } -/// Every shipped generator's name, in the order a run applies them: the list `cargo meta init` -/// writes. +/// Every shipped generator's name, in the order a run applies them. pub fn shipped_names() -> Vec<&'static str> { eject::REFERENCES.iter().map(|r| r.name).collect() } +/// Whether a project with no list runs the generator `name`: every one but a shipped opt-in. +pub fn runs_unlisted(name: &str) -> bool { + !eject::reference(name).is_some_and(|r| r.opt_in) +} + fn example() -> String { format!( "{{ \"{KEY}\": [{}] }}", @@ -123,12 +197,14 @@ fn example() -> String { ) } -/// 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() +/// The text `cargo meta init` writes: every shipped generator but the opt-in ones, and those +/// too with `opt_in`, so a new project generates what it always has and removes one by deleting +/// a line. +pub fn scaffold(opt_in: bool) -> String { + let items = eject::REFERENCES .iter() - .map(|n| format!(" \"{n}\"")) + .filter(|r| opt_in || !r.opt_in) + .map(|r| format!(" \"{}\"", r.name)) .collect::>() .join(",\n"); format!("{{\n \"{KEY}\": [\n{items}\n ]\n}}\n") @@ -145,10 +221,25 @@ mod tests { #[test] fn the_scaffold_parses_and_names_every_shipped_generator_in_run_order() { assert_eq!( - parse(&scaffold()).unwrap(), - s(&["entity", "client", "commands"]) + names(&parse(&scaffold(false)).unwrap()), + s(&[ + "entity", + "rules-names", + "contract-types", + "repository", + "service", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt" + ]) ); - assert!(check(&parse(&scaffold()).unwrap(), &shipped_names()).is_ok()); + assert!(check(&names(&parse(&scaffold(false)).unwrap()), &shipped_names()).is_ok()); + let all = names(&parse(&scaffold(true)).unwrap()); + assert_eq!(all, s(&shipped_names())); + assert!(check(&all, &shipped_names()).is_ok()); + assert!(!runs_unlisted("service-routes") && runs_unlisted("entity")); } #[test] @@ -162,6 +253,22 @@ mod tests { "needs a \"generators\" list", ), ("{\"generators\": [1]}", "generator name (a string)"), + ( + "{\"generators\": [{\"options\": {}}]}", + "generator name (a string)", + ), + ( + "{\"generators\": [{\"name\": \"entity\", \"packages\": []}]}", + "the entry for \"entity\" has an unknown key \"packages\"", + ), + ( + "{\"generators\": [{\"name\": \"entity\", \"options\": []}]}", + "must be an object of option names", + ), + ( + "{\"generators\": [\"entity\", {\"name\": \"entity\"}]}", + "listed twice", + ), ("{\"generators\": [\"entity\", \"entity\"]}", "listed twice"), ( "{\"generators\": [], \"layers\": {}}", @@ -172,7 +279,20 @@ mod tests { assert!(e.contains(wants), "{text}: {e}"); assert!(e.contains(GENERATOR_LIST_FILE), "{e}"); } - assert_eq!(parse("{\"generators\": []}").unwrap(), Vec::::new()); + assert_eq!(parse("{\"generators\": []}").unwrap(), Vec::::new()); + } + + #[test] + fn an_entry_is_a_name_or_a_name_with_its_options() { + let entries = + parse(r#"{"generators": ["entity", {"name": "client", "options": {"pageSize": 25}}, {"name": "commands"}]}"#) + .unwrap(); + assert_eq!(names(&entries), s(&["entity", "client", "commands"])); + assert!(entries[0].options.is_empty() && entries[2].options.is_empty()); + assert_eq!( + entries[1].options.get("pageSize"), + Some(&serde_json::json!(25)) + ); } #[test] @@ -180,7 +300,8 @@ mod tests { let available = shipped_names(); let e = check(&s(&["entity", "nope"]), &available).unwrap_err(); assert!( - e.contains("\"nope\"") && e.contains("available: entity, client, commands"), + e.contains("\"nope\"") + && e.contains("available: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt"), "{e}" ); let e = check(&s(&["client"]), &available).unwrap_err(); diff --git a/server/rust/metaobjects-codegen/src/inbound.rs b/server/rust/metaobjects-codegen/src/inbound.rs new file mode 100644 index 0000000000..cdab72b247 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/inbound.rs @@ -0,0 +1,348 @@ +//! The inbound half of a prompt, read from the model once for every generator that needs it +//! (ADR-0052, ADR-0053). +//! +//! A template subtype's axis is direction: a `template.output` renders outbound and parses +//! nothing; a `template.prompt` that declares `@responseRef` names the value object its reply +//! is read into. [`inbound_templates`] is that rule, in one place, so no generator re-derives +//! "which templates have a response". The reply's syntax is `@responseFormat` (`json`, the +//! default, or `xml`), never `@format`, which is the syntax of the prompt's own body. +//! +//! [`extract_schema`] and [`output_format_spec`] derive, from the response value object, +//! the descriptors the reply parser and the output-format fragment run on, as the +//! `metaobjects-render` crate's own types: the derivation the other ports' runtime extract +//! makes, so a generated parser reads a reply as every port reads it. + +use std::collections::{HashMap, HashSet}; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_render::extract::{ExtractSchema, FieldKind, FieldSpec, Format, normalize}; +use metaobjects_render::prompt::{OutputFormatSpec, PromptField, PromptStyle}; +use serde_json::Value; + +const TYPE_TEMPLATE: &str = "template"; +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_VALIDATOR: &str = "validator"; +const TEMPLATE_PROMPT: &str = "prompt"; +const VALIDATOR_NUMERIC: &str = "numeric"; +const VALIDATOR_ARRAY: &str = "array"; +const ATTR_RESPONSE_REF: &str = "responseRef"; +const ATTR_RESPONSE_FORMAT: &str = "responseFormat"; +const ATTR_PROMPT_STYLE: &str = "promptStyle"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_REQUIRED: &str = "required"; +const ATTR_VALUES: &str = "values"; +const ATTR_ENUM_ALIAS: &str = "enumAlias"; +const ATTR_ENUM_DOC: &str = "enumDoc"; +const ATTR_COERCE_DEFAULT: &str = "coerceDefault"; +const ATTR_DEFAULT: &str = "default"; +const ATTR_NORMALIZE: &str = "normalize"; +const ATTR_XML_TEXT: &str = "xmlText"; +const ATTR_EXAMPLE: &str = "example"; +const ATTR_INSTRUCTION: &str = "instruction"; +const ATTR_MIN: &str = "min"; +const ATTR_MAX: &str = "max"; +const FORMAT_XML: &str = "xml"; + +/// How deep a reply's nested objects are read; past it a member is opaque text. Every port +/// stops at the same depth. +pub const MAX_NEST_DEPTH: usize = 8; + +/// Every concrete `template.prompt` at the root that declares a response shape, by name. +/// The gate is `@responseRef` being there (resolved through `extends`), never a format. +#[must_use] +pub fn inbound_templates(tree: &Tree, root: NodeId) -> Vec { + // ADR-0039 own: the root's top-level nodes are its declared children; a root extends + // nothing, so own and effective agree. + let mut out: Vec = tree + .own_children(root) + .iter() + .copied() + .filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_TEMPLATE + && n.sub_type == TEMPLATE_PROMPT + && !n.is_abstract + && str_attr(tree, c, ATTR_RESPONSE_REF).is_some() + }) + .collect(); + out.sort_by(|a, b| tree.node(*a).name.cmp(&tree.node(*b).name)); + out +} + +/// The object a prompt's reply is read into: its `@responseRef`, resolved on its exact +/// package-qualified name (ADR-0041). `None` when it names no object. +#[must_use] +pub fn response_object(tree: &Tree, index: &ObjectIndex, template: NodeId) -> Option { + index + .ref_target(tree, template, ATTR_RESPONSE_REF) + .filter(|&o| tree.node(o).type_name == TYPE_OBJECT) +} + +/// The reply's syntax (ADR-0053): `@responseFormat`, `json` unless it says `xml`. +#[must_use] +pub fn reply_format(tree: &Tree, template: NodeId) -> Format { + match str_attr(tree, template, ATTR_RESPONSE_FORMAT) { + Some(f) if f.eq_ignore_ascii_case(FORMAT_XML) => Format::Xml, + _ => Format::Json, + } +} + +/// The fragment's style: `@promptStyle`, `guide` unless it says otherwise. +#[must_use] +pub fn prompt_style(tree: &Tree, template: NodeId) -> PromptStyle { + PromptStyle::from_attr(str_attr(tree, template, ATTR_PROMPT_STYLE)) +} + +/// The extract descriptor of `object`: every effective field, nested value objects read +/// through their `@objectRef` to [`MAX_NEST_DEPTH`], a cycle or an unresolved reference +/// read as opaque text. +#[must_use] +pub fn extract_schema( + tree: &Tree, + index: &ObjectIndex, + object: NodeId, + format: Format, +) -> ExtractSchema { + schema_at(tree, index, object, format, &mut HashSet::new(), 0) +} + +fn schema_at( + tree: &Tree, + index: &ObjectIndex, + object: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> ExtractSchema { + visited.insert(object); + let fields = fields_of(tree, object) + .into_iter() + .map(|f| field_spec(tree, index, f, object, format, visited, depth)) + .collect(); + visited.remove(&object); + ExtractSchema { + format, + root_name: tree.node(object).name.clone(), + fields, + } +} + +fn field_spec( + tree: &Tree, + index: &ObjectIndex, + field: NodeId, + owner: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> FieldSpec { + let spec = field_shape(tree, index, field, owner, format, visited, depth); + if !spec.array { + return spec; + } + // Element-count bounds: the field's array validator is the one source of them. + match validator(tree, field, VALIDATOR_ARRAY) { + Some(v) => FieldSpec { + min_items: own_u64(tree, v, ATTR_MIN).and_then(|n| usize::try_from(n).ok()), + max_items: own_u64(tree, v, ATTR_MAX).and_then(|n| usize::try_from(n).ok()), + ..spec + }, + None => spec, + } +} + +fn field_shape( + tree: &Tree, + index: &ObjectIndex, + field: NodeId, + owner: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> FieldSpec { + let n = tree.node(field); + let name = n.name.as_str(); + let required = is_true(tree, field, ATTR_REQUIRED); + let array = tree.resolved_is_array(field); + let listed = |spec: FieldSpec| FieldSpec { array, ..spec }; + if n.sub_type == "enum" { + let mode = str_attr(tree, field, ATTR_NORMALIZE) + .or_else(|| str_attr(tree, owner, ATTR_NORMALIZE)) + .unwrap_or(normalize::DEFAULT); + return listed(FieldSpec { + enum_alias: string_map(tree, field, ATTR_ENUM_ALIAS), + coerce_default: str_attr(tree, field, ATTR_COERCE_DEFAULT).map(str::to_string), + default_value: str_attr(tree, field, ATTR_DEFAULT).map(str::to_string), + normalize: mode.to_string(), + ..FieldSpec::enumeration(name, required, strings(tree, field, ATTR_VALUES)) + }); + } + if n.sub_type == "object" || tree.attr(field, ATTR_OBJECT_REF).is_some() { + return match index.ref_target(tree, field, ATTR_OBJECT_REF) { + Some(target) + if tree.node(target).type_name == TYPE_OBJECT + && !visited.contains(&target) + && depth + 1 < MAX_NEST_DEPTH => + { + let nested = schema_at(tree, index, target, format, visited, depth + 1); + listed(FieldSpec::object(name, required, nested)) + } + // An unresolved reference, a cycle or the depth bound: an opaque leaf. + _ => FieldSpec::scalar(name, FieldKind::String, required), + }; + } + let kind = scalar_kind(&n.sub_type); + if array { + return FieldSpec::scalar(name, kind, required).array(); + } + if is_true(tree, field, ATTR_XML_TEXT) { + return FieldSpec::scalar(name, kind, required).text_content(); + } + let spec = FieldSpec::scalar(name, kind, required); + if matches!(kind, FieldKind::Int | FieldKind::Long | FieldKind::Double) + && let Some(v) = validator(tree, field, VALIDATOR_NUMERIC) + { + let (min, max) = (own_f64(tree, v, ATTR_MIN), own_f64(tree, v, ATTR_MAX)); + if min.is_some() || max.is_some() { + return spec.range(min, max); + } + } + spec.default_value(str_attr(tree, field, ATTR_DEFAULT).map(str::to_string)) +} + +/// The output-format fragment's descriptor for `object`, the reply's root. A nested object +/// is named with its kind and taught no deeper, as in every port. +#[must_use] +pub fn output_format_spec( + tree: &Tree, + object: NodeId, + format: Format, + style: PromptStyle, +) -> OutputFormatSpec { + let fields = fields_of(tree, object) + .into_iter() + .map(|f| prompt_field(tree, f)) + .collect(); + OutputFormatSpec { + format, + root_name: tree.node(object).name.clone(), + style, + fields, + } +} + +fn prompt_field(tree: &Tree, field: NodeId) -> PromptField { + let n = tree.node(field); + let required = is_true(tree, field, ATTR_REQUIRED); + let array = tree.resolved_is_array(field); + if n.sub_type == "object" { + return PromptField { + array, + ..PromptField::new(&n.name, FieldKind::Object, required) + }; + } + let example = str_attr(tree, field, ATTR_EXAMPLE).map(str::to_string); + let instruction = str_attr(tree, field, ATTR_INSTRUCTION).map(str::to_string); + if n.sub_type == "enum" { + let doc = string_map(tree, field, ATTR_ENUM_DOC); + return PromptField { + array, + enum_values: Some(strings(tree, field, ATTR_VALUES)), + enum_doc: (!doc.is_empty()).then(|| doc.into_iter().collect::>()), + example, + instruction, + ..PromptField::new(&n.name, FieldKind::Enum, required) + }; + } + PromptField { + array, + example, + instruction, + ..PromptField::new(&n.name, scalar_kind(&n.sub_type), required) + } +} + +/// The extract kind of a scalar field subtype; anything not numeric or boolean is text. +#[must_use] +pub fn scalar_kind(sub_type: &str) -> FieldKind { + match sub_type { + "int" => FieldKind::Int, + "long" | "currency" => FieldKind::Long, + "double" | "float" | "decimal" => FieldKind::Double, + "boolean" => FieldKind::Boolean, + _ => FieldKind::String, + } +} + +// ---- model reads ----------------------------------------------------------------------- + +/// The effective fields of `object`, inherited ones included, in declaration order. +fn fields_of(tree: &Tree, object: NodeId) -> Vec { + tree.children(object) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_FIELD) + .collect() +} + +fn validator(tree: &Tree, field: NodeId, sub_type: &str) -> Option { + tree.children(field).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == TYPE_VALIDATOR && n.sub_type == sub_type + }) +} + +fn str_attr<'t>(tree: &'t Tree, id: NodeId, name: &str) -> Option<&'t str> { + tree.attr(id, name) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) +} + +fn is_true(tree: &Tree, id: NodeId, name: &str) -> bool { + match tree.attr(id, name) { + Some(Value::Bool(b)) => *b, + Some(Value::String(s)) => s.eq_ignore_ascii_case("true"), + _ => false, + } +} + +fn strings(tree: &Tree, id: NodeId, name: &str) -> Vec { + tree.attr(id, name) + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +/// A string-to-string map attribute, in declaration order; a null value is dropped. +fn string_map(tree: &Tree, id: NodeId, name: &str) -> Vec<(String, String)> { + tree.attr(id, name) + .and_then(Value::as_object) + .map(|m| { + m.iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| { + let v = v.as_str().map_or_else(|| v.to_string(), str::to_string); + (k.clone(), v) + }) + .collect() + }) + .unwrap_or_default() +} + +// ADR-0039 own: a validator's `@min`/`@max` are its own declared bounds. +fn own_f64(tree: &Tree, id: NodeId, name: &str) -> Option { + tree.own_attr(id, name) + .filter(|a| !a.value.is_boolean()) + .and_then(|a| a.value.as_f64()) +} + +// ADR-0039 own: a validator's `@min`/`@max` are its own declared bounds. +fn own_u64(tree: &Tree, id: NodeId, name: &str) -> Option { + tree.own_attr(id, name).and_then(|a| a.value.as_u64()) +} diff --git a/server/rust/metaobjects-codegen/src/layers/mod.rs b/server/rust/metaobjects-codegen/src/layers/mod.rs new file mode 100644 index 0000000000..648fc344f5 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/layers/mod.rs @@ -0,0 +1,8 @@ +//! The walks the ADR-0067 layer generators share: the rules names a package declares, the +//! entities a store crate reads and writes, and the operations a service crate holds. They are +//! engine, not a generator's own module, so a generator owned through `cargo meta eject` calls +//! the same walk the shipped one does. + +pub mod rules; +pub mod service; +pub mod store; diff --git a/server/rust/metaobjects-codegen/src/layers/rules.rs b/server/rust/metaobjects-codegen/src/layers/rules.rs new file mode 100644 index 0000000000..3308c43a51 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/layers/rules.rs @@ -0,0 +1,233 @@ +//! The rules-names walk in Rust names: each package's lifecycles, states, operations, +//! permissions and business errors, as the `rules-names` generator writes them and the +//! `service` generator calls them. + +use std::collections::{BTreeMap, BTreeSet}; + +use metaobjects::rules_names::{ + RulesNamesEntity, RulesNamesLifecycle, RulesNamesOperation, RulesNamesPackage, +}; + +use crate::generator::{ERR_NAME_COLLISION, ERR_UNSUPPORTED, GenError}; +use crate::names::{module_name, pascal, type_ident}; +use crate::plan::{EnumPlan, Plan, Ty}; + +/// The suffix of the rules crate of a package: `shop`'s names are in `shop_rules`. +pub const RULES_SUFFIX: &str = "_rules"; + +/// One lifecycle, with the Rust names of its state type and states. +pub struct LifecycleNames { + pub names: RulesNamesLifecycle, + /// The lifecycle's module in its entity's: the field in snake case. + pub module: String, + /// The model's enum for the field: `acme_shop::OrderStatus`. + pub state_type: String, + /// Each state's variant, by the state's wire symbol. + pub variants: BTreeMap, + /// Each transition's variant, in model order. + pub transitions: Vec, +} + +/// One entity of a rules crate. +pub struct EntityNames { + pub names: RulesNamesEntity, + /// The entity's module: its name in snake case. + pub module: String, + pub lifecycles: Vec, + /// Each command's variant, in model order. + pub commands: Vec, +} + +/// One package's rules crate. +pub struct RulesCrate { + /// The package (`acme::shop`), or `""` for a model with none. + pub package: String, + /// The model crate that holds the state enums, when an entity has a lifecycle. + pub model_crate: Option, + pub entities: Vec, + pub operations: Vec, + /// Each operation's variant, in model order. + pub operation_variants: Vec, + /// Each permission's dotted name with its variant, sorted by name. + pub permissions: Vec<(String, String)>, + /// Each business error's code with its variant, sorted by code. + pub errors: Vec<(String, String)>, +} + +impl RulesCrate { + /// The variant of the permission `name`. + pub fn permission(&self, name: &str) -> &str { + self.permissions + .iter() + .find(|(n, _)| n == name) + .map(|(_, v)| v.as_str()) + .expect("every permission a point asks about is in the package's list") + } + + /// The variant of the business error `code`. + pub fn error(&self, code: &str) -> &str { + self.errors + .iter() + .find(|(c, _)| c == code) + .map(|(_, v)| v.as_str()) + .expect("every business error a command declares is in the package's list") + } +} + +/// `acme.shop.Order.submit` becomes `AcmeShopOrderSubmit`: each dotted (or `::`) segment in +/// pascal case. +pub fn permission_variant(name: &str) -> String { + let joined: String = name + .split(|c: char| !c.is_alphanumeric() && c != '_') + .filter(|s| !s.is_empty()) + .map(pascal) + .collect(); + type_ident(&joined) +} + +/// Each name's variant, refusing two names that would take one. +fn variants<'a>( + what: &str, + names: impl IntoIterator, + to_variant: impl Fn(&str) -> String, +) -> Result, GenError> { + let mut seen: BTreeMap = BTreeMap::new(); + let mut out = Vec::new(); + for name in names { + let v = to_variant(name); + if let Some(other) = seen.insert(v.clone(), name.to_string()) { + if other != name { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!("{what} {other:?} and {name:?} would both be the Rust variant {v}"), + )); + } + continue; + } + out.push((name.to_string(), v)); + } + Ok(out) +} + +fn variant_list<'a>( + what: &str, + names: impl IntoIterator, +) -> Result, GenError> { + Ok(variants(what, names, type_ident)? + .into_iter() + .map(|(_, v)| v) + .collect()) +} + +/// The model's enum for the lifecycle field `field` of the planned entity `entity`. +fn state_enum<'p>( + plan: &'p Plan, + entity: &RulesNamesEntity, + field: &str, +) -> Result<(String, &'p str, &'p EnumPlan), GenError> { + let what = format!("{}.{field}", entity.name); + let s = plan + .structs + .iter() + .find(|s| s.node == entity.node) + .ok_or_else(|| GenError::new(ERR_UNSUPPORTED, format!("{what}: no planned entity")))?; + let Some(Ty::Ref(r)) = s.fields.iter().find(|f| f.wire == field).map(|f| &f.ty) else { + return Err(GenError::new( + ERR_UNSUPPORTED, + format!("{what} is a lifecycle the entity generator does not plan as an enum"), + )); + }; + let owner = plan.crates.get(&r.crate_name); + let found = s + .enums + .iter() + .find(|e| e.type_name == r.type_name) + .or_else(|| { + owner.and_then(|c| { + c.shared_enums + .iter() + .map(|(_, e)| e) + .find(|e| e.type_name == r.type_name) + }) + }); + match found { + Some(e) => Ok((r.crate_name.clone(), r.type_name.as_str(), e)), + None => Err(GenError::new( + ERR_UNSUPPORTED, + format!("{what}: the enum {} is not planned", r.type_name), + )), + } +} + +pub fn crate_of(plan: &Plan, pkg: RulesNamesPackage) -> Result { + let mut model_crate = None; + let mut entities = Vec::new(); + let mut modules: BTreeSet = BTreeSet::new(); + for e in pkg.entities { + // An abstract entity has no type of its own; its concrete descendants carry its + // lifecycles. + if !plan.structs.iter().any(|s| s.node == e.node) { + continue; + } + let module = module_name(&e.name); + if !modules.insert(module.clone()) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "two entities of {:?} would both be the module {module}", + pkg.package + ), + )); + } + let mut lifecycles = Vec::new(); + for l in &e.lifecycles { + let (krate, type_name, plan_enum) = state_enum(plan, &e, &l.field)?; + model_crate = Some(krate.clone()); + let variants = plan_enum + .members + .iter() + .map(|m| (m.wire.clone(), m.variant.clone())) + .collect(); + lifecycles.push(LifecycleNames { + module: module_name(&l.field), + state_type: format!("{krate}::{type_name}"), + variants, + transitions: variant_list( + "the transitions", + l.transitions.iter().map(|t| t.name.as_str()), + )?, + names: l.clone(), + }); + } + let commands = variant_list("the commands", e.commands.iter().map(|c| c.name.as_str()))?; + entities.push(EntityNames { + module, + lifecycles, + commands, + names: e, + }); + } + let operation_variants = variant_list( + "the operations", + pkg.operations.iter().map(|o| o.name.as_str()), + )?; + let permissions = variants( + "the permissions", + pkg.permissions.iter().map(String::as_str), + permission_variant, + )?; + let errors = variants( + "the business errors", + pkg.errors.iter().map(String::as_str), + type_ident, + )?; + Ok(RulesCrate { + package: pkg.package, + model_crate, + entities, + operations: pkg.operations, + operation_variants, + permissions, + errors, + }) +} diff --git a/server/rust/metaobjects-codegen/src/layers/service.rs b/server/rust/metaobjects-codegen/src/layers/service.rs new file mode 100644 index 0000000000..c39236d05f --- /dev/null +++ b/server/rust/metaobjects-codegen/src/layers/service.rs @@ -0,0 +1,515 @@ +//! The service walk: the operations a package's service crate holds (each stored entity's +//! derived operations, its lifecycle commands, the package's declared operations) with their +//! permission points, moves and stamps. The `service` generator renders it, and the +//! `service-routes` transport mounts the same walk, so the two agree by construction and an +//! owned copy of either keeps calling it. + +use std::collections::{BTreeMap, BTreeSet}; + +use metaobjects::config::{RulesLifecycleCreate, RulesPermissionNames}; +use metaobjects::node::{NodeId, Tree}; +use metaobjects::rules_names::{OperationKind, RulesNamesOperation, rules_names_of}; +use metaobjects::validate::util::ObjectIndex; + +use crate::generator::{ERR_NAME_COLLISION, ERR_UNSUPPORTED, GenContext, GenError}; +use crate::layers::rules::{EntityNames, RULES_SUFFIX, RulesCrate, crate_of}; +use crate::layers::store::{StoredCrate, StoredEntity, stored_crates_in}; +use crate::names::{crate_name, pascal, snake, type_ident}; +use crate::plan::{Plan, Presence, StructPlan}; + +pub use crate::plan::{CONTRACT_SUFFIX, SERVICE_CRATE, SERVICE_SUFFIX}; + +const ATTR_INPUT_REF: &str = "inputRef"; +const ATTR_OUTPUT_REF: &str = "outputRef"; +const ATTR_MANY: &str = "many"; +const ATTR_PUBLIC: &str = "public"; +const ATTR_PERMISSION: &str = "permission"; +const ATTR_AUTO_SET: &str = "autoSet"; +const AUTO_SET_ON_UPDATE: &str = "onUpdate"; + +// ---- the walk -------------------------------------------------------------------------------- + +/// A transition's derived command on an entity. +pub struct ServiceCommand { + /// The method: `_`. + pub function: String, + /// The operation name events carry: ``. + pub operation: String, + pub transition: ServiceMove, + /// The permission variant it asks about; `None` when the transition is `@public`. + pub permission: Option, +} + +/// One move of a lifecycle, by the rules crate's names. +pub struct ServiceMove { + pub name: String, + /// The lifecycle field's wire name and its member on the row. + pub field: String, + pub ident: String, + /// `::::::Transition::`. + pub path: String, + /// The `@condition`, as JSON text, when the move has one. + pub condition: Option, +} + +/// One lifecycle of an entity, for the create and update checks. +pub struct ServiceLifecycle { + pub field: String, + pub ident: String, + /// `::::`, the module holding `INITIAL`. + pub module: String, + /// How the create body carries the field. + pub create: Presence, + /// Whether the patch carries it. + pub patch: bool, +} + +/// An `@autoSet` timestamp the service stamps (ADR-0045). +pub struct ServiceStamp { + pub ident: String, + /// `onUpdate`: stamped by an update as well as a create. + pub on_update: bool, + pub local_time: bool, + /// Whether the create body carries it as an `Option`, and the patch as an `Option