From a5d44ab1242a6fd69755969fe529b70f077b2a47 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 21:59:16 +0800 Subject: [PATCH 1/2] conformance: a generator-agnostic harness, and no generator dependency comline-conformance dev-depended on comline-codegen-rust and comline-codegen-typescript, which depend on comline-codegen here, so every core bump went round the cycle twice. The three suites that need a generator (the protocol round trip, the golden comparison, the support proofs) move into the crate as comline_conformance::harness, parameterised by a Generator, and each generator repository runs them over its own output against goldens it holds. generation now depends on core only; the [patch] that folded the two copies of comline-codegen into one goes with the dev-deps. The goldens and the combined FEATURES.md/features.json leave with the generators: each generator's repository holds its own goldens and its own report. --- Cargo.toml | 10 +- FEATURES.md | 37 - README.md | 10 +- conformance/Cargo.toml | 16 +- conformance/README.md | 59 +- conformance/src/harness.rs | 656 ++++++++++++ conformance/src/lib.rs | 9 +- conformance/tests/conformance.rs | 555 ----------- .../tests/golden/bounds/rust/conformance.rs | 188 ---- .../golden/bounds/typescript/conformance.ts | 35 - .../tests/golden/chars/rust/conformance.rs | 9 - .../golden/chars/typescript/conformance.ts | 11 - .../golden/connections/rust/conformance.rs | 250 ----- .../golden/connections/rust/connection.rs | 76 -- .../connections/typescript/conformance.ts | 184 ---- .../connections/typescript/connection.ts | 77 -- .../golden/connections/typescript/wire.ts | 14 - .../connections_async/rust/conformance.rs | 216 ---- .../connections_async/rust/connection.rs | 76 -- .../typescript/conformance.ts | 184 ---- .../typescript/connection.ts | 77 -- .../connections_async/typescript/wire.ts | 14 - .../connections_default/rust/conformance.rs | 261 ----- .../connections_default/rust/connection.rs | 209 ---- .../typescript/conformance.ts | 188 ---- .../typescript/connection.ts | 137 --- .../connections_default/typescript/wire.ts | 14 - .../connections_jsonrpc/rust/conformance.rs | 250 ----- .../connections_jsonrpc/rust/connection.rs | 79 -- .../typescript/conformance.ts | 184 ---- .../typescript/connection.ts | 79 -- .../connections_jsonrpc/typescript/wire.ts | 14 - .../tests/golden/constant/rust/conformance.rs | 5 - .../golden/constant/typescript/conformance.ts | 5 - .../tests/golden/cross_schema/rust/api.rs | 11 - .../tests/golden/cross_schema/rust/shared.rs | 9 - .../golden/cross_schema/typescript/api.ts | 16 - .../golden/cross_schema/typescript/shared.ts | 11 - .../dependency_and_own_protocols/rust/api.rs | 137 --- .../rust/connection.rs | 189 ---- .../rust/localdeps/greeting.rs | 135 --- .../typescript/api.ts | 106 -- .../typescript/connection.ts | 119 --- .../typescript/localdeps/greeting.ts | 100 -- .../typescript/wire.ts | 14 - .../golden/dependency_protocol/rust/api.rs | 9 - .../rust/localdeps/greeting.rs | 140 --- .../dependency_protocol/typescript/api.ts | 14 - .../typescript/localdeps/greeting.ts | 109 -- .../golden/enum_basic/rust/conformance.rs | 11 - .../enum_basic/typescript/conformance.ts | 14 - .../golden/error_shapes/rust/conformance.rs | 326 ------ .../golden/error_shapes/rust/connection.rs | 61 -- .../error_shapes/typescript/conformance.ts | 217 ---- .../error_shapes/typescript/connection.ts | 64 -- .../golden/error_shapes/typescript/wire.ts | 14 - .../tests/golden/external_std/rust/Cargo.toml | 15 - .../tests/golden/external_std/rust/src/api.rs | 9 - .../tests/golden/external_std/rust/src/lib.rs | 5 - .../external_std/typescript/package.json | 33 - .../golden/external_std/typescript/src/api.ts | 14 - .../external_std/typescript/src/index.ts | 3 - .../external_std/typescript/tsconfig.json | 16 - .../golden/format_json/rust/conformance.rs | 237 ----- .../golden/format_json/rust/connection.rs | 59 -- .../format_json/typescript/conformance.ts | 161 --- .../format_json/typescript/connection.ts | 62 -- .../golden/format_json/typescript/wire.ts | 14 - .../golden/format_msgpack/rust/conformance.rs | 237 ----- .../golden/format_msgpack/rust/connection.rs | 59 -- .../framing_datagram3/rust/conformance.rs | 144 --- .../framing_datagram3/rust/connection.rs | 62 -- .../typescript/conformance.ts | 108 -- .../typescript/connection.ts | 63 -- .../framing_datagram3/typescript/wire.ts | 14 - .../framing_jsonrpc/rust/conformance.rs | 121 --- .../framing_jsonrpc/typescript/conformance.ts | 88 -- .../handshake_comline2/rust/conformance.rs | 146 --- .../handshake_comline2/rust/connection.rs | 189 ---- .../typescript/conformance.ts | 111 --- .../typescript/connection.ts | 119 --- .../handshake_comline2/typescript/wire.ts | 14 - .../golden/handshake_none/rust/conformance.rs | 131 --- .../golden/handshake_none/rust/connection.rs | 59 -- .../handshake_none/typescript/conformance.ts | 104 -- .../handshake_none/typescript/connection.ts | 63 -- .../golden/handshake_none/typescript/wire.ts | 14 - .../tests/golden/import_alias/rust/api.rs | 9 - .../tests/golden/import_alias/rust/shared.rs | 9 - .../golden/import_alias/typescript/api.ts | 14 - .../golden/import_alias/typescript/shared.ts | 11 - .../tests/golden/import_glob/rust/api.rs | 9 - .../tests/golden/import_glob/rust/shared.rs | 14 - .../golden/import_glob/typescript/api.ts | 14 - .../golden/import_glob/typescript/shared.ts | 17 - .../typescript/conformance.ts | 12 - .../tests/golden/lockstep/rust/conformance.rs | 211 ---- .../golden/lockstep/typescript/conformance.ts | 136 --- .../golden/nested_namespace/rust/Cargo.toml | 14 - .../golden/nested_namespace/rust/src/group.rs | 4 - .../nested_namespace/rust/src/group/first.rs | 9 - .../nested_namespace/rust/src/group/second.rs | 9 - .../golden/nested_namespace/rust/src/lib.rs | 6 - .../golden/nested_namespace/rust/src/top.rs | 9 - .../nested_namespace/typescript/package.json | 30 - .../typescript/src/group/first.ts | 14 - .../typescript/src/group/index.ts | 4 - .../typescript/src/group/second.ts | 14 - .../nested_namespace/typescript/src/index.ts | 4 - .../nested_namespace/typescript/src/top.ts | 11 - .../nested_namespace/typescript/tsconfig.json | 16 - .../golden/nested_protocol/rust/chat/admin.rs | 137 --- .../golden/nested_protocol/rust/connection.rs | 189 ---- .../nested_protocol/typescript/chat/admin.ts | 103 -- .../nested_protocol/typescript/connection.ts | 119 --- .../golden/nested_protocol/typescript/wire.ts | 14 - .../optional_and_arrays/rust/conformance.rs | 12 - .../typescript/conformance.ts | 14 - .../golden/primitives/rust/conformance.rs | 16 - .../primitives/typescript/conformance.ts | 18 - .../tests/golden/protocol/rust/conformance.rs | 237 ----- .../tests/golden/protocol/rust/connection.rs | 59 -- .../golden/protocol/typescript/conformance.ts | 161 --- .../golden/protocol/typescript/connection.ts | 62 -- .../tests/golden/protocol/typescript/wire.ts | 14 - .../tests/golden/shapes/rust/conformance.rs | 19 - .../golden/shapes/typescript/conformance.ts | 18 - .../golden/type_refs/rust/conformance.rs | 16 - .../type_refs/typescript/conformance.ts | 19 - .../golden/unions/typescript/conformance.ts | 15 - .../golden/validators/rust/conformance.rs | 301 ------ .../golden/validators/rust/connection.rs | 59 -- .../golden/validators/rust/std/validators.rs | 3 - .../validators/typescript/conformance.ts | 117 --- .../validators/typescript/connection.ts | 62 -- .../validators/typescript/std/validators.ts | 3 - .../golden/validators/typescript/wire.ts | 14 - .../validators_on_decode/rust/conformance.rs | 355 ------- .../validators_on_decode/rust/connection.rs | 59 -- .../rust/std/validators.rs | 3 - .../typescript/conformance.ts | 117 --- .../typescript/connection.ts | 62 -- .../typescript/std/validators.ts | 3 - .../validators_on_decode/typescript/wire.ts | 14 - features.json | 930 ------------------ 145 files changed, 727 insertions(+), 11705 deletions(-) delete mode 100644 FEATURES.md create mode 100644 conformance/src/harness.rs delete mode 100644 conformance/tests/conformance.rs delete mode 100644 conformance/tests/golden/bounds/rust/conformance.rs delete mode 100644 conformance/tests/golden/bounds/typescript/conformance.ts delete mode 100644 conformance/tests/golden/chars/rust/conformance.rs delete mode 100644 conformance/tests/golden/chars/typescript/conformance.ts delete mode 100644 conformance/tests/golden/connections/rust/conformance.rs delete mode 100644 conformance/tests/golden/connections/rust/connection.rs delete mode 100644 conformance/tests/golden/connections/typescript/conformance.ts delete mode 100644 conformance/tests/golden/connections/typescript/connection.ts delete mode 100644 conformance/tests/golden/connections/typescript/wire.ts delete mode 100644 conformance/tests/golden/connections_async/rust/conformance.rs delete mode 100644 conformance/tests/golden/connections_async/rust/connection.rs delete mode 100644 conformance/tests/golden/connections_async/typescript/conformance.ts delete mode 100644 conformance/tests/golden/connections_async/typescript/connection.ts delete mode 100644 conformance/tests/golden/connections_async/typescript/wire.ts delete mode 100644 conformance/tests/golden/connections_default/rust/conformance.rs delete mode 100644 conformance/tests/golden/connections_default/rust/connection.rs delete mode 100644 conformance/tests/golden/connections_default/typescript/conformance.ts delete mode 100644 conformance/tests/golden/connections_default/typescript/connection.ts delete mode 100644 conformance/tests/golden/connections_default/typescript/wire.ts delete mode 100644 conformance/tests/golden/connections_jsonrpc/rust/conformance.rs delete mode 100644 conformance/tests/golden/connections_jsonrpc/rust/connection.rs delete mode 100644 conformance/tests/golden/connections_jsonrpc/typescript/conformance.ts delete mode 100644 conformance/tests/golden/connections_jsonrpc/typescript/connection.ts delete mode 100644 conformance/tests/golden/connections_jsonrpc/typescript/wire.ts delete mode 100644 conformance/tests/golden/constant/rust/conformance.rs delete mode 100644 conformance/tests/golden/constant/typescript/conformance.ts delete mode 100644 conformance/tests/golden/cross_schema/rust/api.rs delete mode 100644 conformance/tests/golden/cross_schema/rust/shared.rs delete mode 100644 conformance/tests/golden/cross_schema/typescript/api.ts delete mode 100644 conformance/tests/golden/cross_schema/typescript/shared.ts delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/rust/api.rs delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/rust/connection.rs delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/typescript/api.ts delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/typescript/connection.ts delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/typescript/localdeps/greeting.ts delete mode 100644 conformance/tests/golden/dependency_and_own_protocols/typescript/wire.ts delete mode 100644 conformance/tests/golden/dependency_protocol/rust/api.rs delete mode 100644 conformance/tests/golden/dependency_protocol/rust/localdeps/greeting.rs delete mode 100644 conformance/tests/golden/dependency_protocol/typescript/api.ts delete mode 100644 conformance/tests/golden/dependency_protocol/typescript/localdeps/greeting.ts delete mode 100644 conformance/tests/golden/enum_basic/rust/conformance.rs delete mode 100644 conformance/tests/golden/enum_basic/typescript/conformance.ts delete mode 100644 conformance/tests/golden/error_shapes/rust/conformance.rs delete mode 100644 conformance/tests/golden/error_shapes/rust/connection.rs delete mode 100644 conformance/tests/golden/error_shapes/typescript/conformance.ts delete mode 100644 conformance/tests/golden/error_shapes/typescript/connection.ts delete mode 100644 conformance/tests/golden/error_shapes/typescript/wire.ts delete mode 100644 conformance/tests/golden/external_std/rust/Cargo.toml delete mode 100644 conformance/tests/golden/external_std/rust/src/api.rs delete mode 100644 conformance/tests/golden/external_std/rust/src/lib.rs delete mode 100644 conformance/tests/golden/external_std/typescript/package.json delete mode 100644 conformance/tests/golden/external_std/typescript/src/api.ts delete mode 100644 conformance/tests/golden/external_std/typescript/src/index.ts delete mode 100644 conformance/tests/golden/external_std/typescript/tsconfig.json delete mode 100644 conformance/tests/golden/format_json/rust/conformance.rs delete mode 100644 conformance/tests/golden/format_json/rust/connection.rs delete mode 100644 conformance/tests/golden/format_json/typescript/conformance.ts delete mode 100644 conformance/tests/golden/format_json/typescript/connection.ts delete mode 100644 conformance/tests/golden/format_json/typescript/wire.ts delete mode 100644 conformance/tests/golden/format_msgpack/rust/conformance.rs delete mode 100644 conformance/tests/golden/format_msgpack/rust/connection.rs delete mode 100644 conformance/tests/golden/framing_datagram3/rust/conformance.rs delete mode 100644 conformance/tests/golden/framing_datagram3/rust/connection.rs delete mode 100644 conformance/tests/golden/framing_datagram3/typescript/conformance.ts delete mode 100644 conformance/tests/golden/framing_datagram3/typescript/connection.ts delete mode 100644 conformance/tests/golden/framing_datagram3/typescript/wire.ts delete mode 100644 conformance/tests/golden/framing_jsonrpc/rust/conformance.rs delete mode 100644 conformance/tests/golden/framing_jsonrpc/typescript/conformance.ts delete mode 100644 conformance/tests/golden/handshake_comline2/rust/conformance.rs delete mode 100644 conformance/tests/golden/handshake_comline2/rust/connection.rs delete mode 100644 conformance/tests/golden/handshake_comline2/typescript/conformance.ts delete mode 100644 conformance/tests/golden/handshake_comline2/typescript/connection.ts delete mode 100644 conformance/tests/golden/handshake_comline2/typescript/wire.ts delete mode 100644 conformance/tests/golden/handshake_none/rust/conformance.rs delete mode 100644 conformance/tests/golden/handshake_none/rust/connection.rs delete mode 100644 conformance/tests/golden/handshake_none/typescript/conformance.ts delete mode 100644 conformance/tests/golden/handshake_none/typescript/connection.ts delete mode 100644 conformance/tests/golden/handshake_none/typescript/wire.ts delete mode 100644 conformance/tests/golden/import_alias/rust/api.rs delete mode 100644 conformance/tests/golden/import_alias/rust/shared.rs delete mode 100644 conformance/tests/golden/import_alias/typescript/api.ts delete mode 100644 conformance/tests/golden/import_alias/typescript/shared.ts delete mode 100644 conformance/tests/golden/import_glob/rust/api.rs delete mode 100644 conformance/tests/golden/import_glob/rust/shared.rs delete mode 100644 conformance/tests/golden/import_glob/typescript/api.ts delete mode 100644 conformance/tests/golden/import_glob/typescript/shared.ts delete mode 100644 conformance/tests/golden/large_fixed_arrays_nested/typescript/conformance.ts delete mode 100644 conformance/tests/golden/lockstep/rust/conformance.rs delete mode 100644 conformance/tests/golden/lockstep/typescript/conformance.ts delete mode 100644 conformance/tests/golden/nested_namespace/rust/Cargo.toml delete mode 100644 conformance/tests/golden/nested_namespace/rust/src/group.rs delete mode 100644 conformance/tests/golden/nested_namespace/rust/src/group/first.rs delete mode 100644 conformance/tests/golden/nested_namespace/rust/src/group/second.rs delete mode 100644 conformance/tests/golden/nested_namespace/rust/src/lib.rs delete mode 100644 conformance/tests/golden/nested_namespace/rust/src/top.rs delete mode 100644 conformance/tests/golden/nested_namespace/typescript/package.json delete mode 100644 conformance/tests/golden/nested_namespace/typescript/src/group/first.ts delete mode 100644 conformance/tests/golden/nested_namespace/typescript/src/group/index.ts delete mode 100644 conformance/tests/golden/nested_namespace/typescript/src/group/second.ts delete mode 100644 conformance/tests/golden/nested_namespace/typescript/src/index.ts delete mode 100644 conformance/tests/golden/nested_namespace/typescript/src/top.ts delete mode 100644 conformance/tests/golden/nested_namespace/typescript/tsconfig.json delete mode 100644 conformance/tests/golden/nested_protocol/rust/chat/admin.rs delete mode 100644 conformance/tests/golden/nested_protocol/rust/connection.rs delete mode 100644 conformance/tests/golden/nested_protocol/typescript/chat/admin.ts delete mode 100644 conformance/tests/golden/nested_protocol/typescript/connection.ts delete mode 100644 conformance/tests/golden/nested_protocol/typescript/wire.ts delete mode 100644 conformance/tests/golden/optional_and_arrays/rust/conformance.rs delete mode 100644 conformance/tests/golden/optional_and_arrays/typescript/conformance.ts delete mode 100644 conformance/tests/golden/primitives/rust/conformance.rs delete mode 100644 conformance/tests/golden/primitives/typescript/conformance.ts delete mode 100644 conformance/tests/golden/protocol/rust/conformance.rs delete mode 100644 conformance/tests/golden/protocol/rust/connection.rs delete mode 100644 conformance/tests/golden/protocol/typescript/conformance.ts delete mode 100644 conformance/tests/golden/protocol/typescript/connection.ts delete mode 100644 conformance/tests/golden/protocol/typescript/wire.ts delete mode 100644 conformance/tests/golden/shapes/rust/conformance.rs delete mode 100644 conformance/tests/golden/shapes/typescript/conformance.ts delete mode 100644 conformance/tests/golden/type_refs/rust/conformance.rs delete mode 100644 conformance/tests/golden/type_refs/typescript/conformance.ts delete mode 100644 conformance/tests/golden/unions/typescript/conformance.ts delete mode 100644 conformance/tests/golden/validators/rust/conformance.rs delete mode 100644 conformance/tests/golden/validators/rust/connection.rs delete mode 100644 conformance/tests/golden/validators/rust/std/validators.rs delete mode 100644 conformance/tests/golden/validators/typescript/conformance.ts delete mode 100644 conformance/tests/golden/validators/typescript/connection.ts delete mode 100644 conformance/tests/golden/validators/typescript/std/validators.ts delete mode 100644 conformance/tests/golden/validators/typescript/wire.ts delete mode 100644 conformance/tests/golden/validators_on_decode/rust/conformance.rs delete mode 100644 conformance/tests/golden/validators_on_decode/rust/connection.rs delete mode 100644 conformance/tests/golden/validators_on_decode/rust/std/validators.rs delete mode 100644 conformance/tests/golden/validators_on_decode/typescript/conformance.ts delete mode 100644 conformance/tests/golden/validators_on_decode/typescript/connection.ts delete mode 100644 conformance/tests/golden/validators_on_decode/typescript/std/validators.ts delete mode 100644 conformance/tests/golden/validators_on_decode/typescript/wire.ts delete mode 100644 features.json diff --git a/Cargo.toml b/Cargo.toml index 12d515a..fdc6697 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,17 +9,13 @@ members = [ # The per-language generators graduated to their own repos (rollout steps 4–5): # `codegen-typescript` → ComlineProject/comline-typescript, # `codegen-rust` → ComlineProject/comline-rust. +# They depend on this workspace (`comline-codegen`, and `comline-conformance`'s +# corpus and harness, with the goldens they check kept in their own repos), +# and this workspace depends on neither. # The `lib-gen/{lua,luau,c,python}` stubs still use the old `comline::…` crate # path and are unwired — each becomes its own `comline-` repo when it # lands. See design/generation.md. -# `comline-conformance` dev-deps the generator crates from their own repos, -# which in turn git-dep `comline-codegen` from *this* repo. Point that back at -# the in-repo crate so the build has one `comline-codegen`, not several. -# (Same-repo path — CI-safe.) -[patch."https://github.com/ComlineProject/generation"] -comline-codegen = { path = "codegen" } - # Local iteration against a sibling `core` checkout — uncomment to build # `comline-core` from the working tree instead of the pinned git rev. Re-comment # before pushing; CI has no sibling checkout. diff --git a/FEATURES.md b/FEATURES.md deleted file mode 100644 index e513b76..0000000 --- a/FEATURES.md +++ /dev/null @@ -1,37 +0,0 @@ -# Generator features - - - -What each generator implements, and the conformance fixtures that prove it. A claim is checked, not trusted: a supported feature has a fixture that generates and matches its golden, an ignored one generates exactly what it would without the feature, and an unsupported one is refused with an error naming every use. - -| Feature | rust ≥ 1.85.0 | typescript ≥ 5.0 | -|---|---|---| -| structs
`structs` | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +17 more | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +18 more | -| enums
`enums` | ✅ supported
proven by `enum_basic` | ✅ supported
proven by `enum_basic` | -| optional fields
`optional-fields` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +4 more | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | -| arrays
`arrays` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +6 more | -| fixed-length arrays
`fixed-arrays` | ✅ supported
proven by `shapes` | 🟡 partial: rendered as `T[]`: the length isn't part of the type
proven by `shapes`, `large_fixed_arrays_nested` | -| fixed arrays over 32 elements, nested
`large-fixed-arrays-nested` | ❌ unsupported: a fixed array over 32 elements renders only as a struct or error field's own, non-optional type (serde's derive stops at 32)
proven by `large_fixed_arrays_nested` | 🟡 partial: rendered as `T[]`: the length isn't part of the type
proven by `large_fixed_arrays_nested` | -| unions
`unions` | ❌ unsupported: Rust has no anonymous sum type to render one as
proven by `unions` | ✅ supported
proven by `unions` | -| type aliases
`type-aliases` | ✅ supported
proven by `validators`, `validators_on_decode`, `bounds` | ✅ supported
proven by `validators`, `validators_on_decode`, `unions` +1 more | -| constants
`constants` | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | -| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +15 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +14 more | -| errors
`errors` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | -| functions that throw
`throws` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | -| validators
`validators` | ✅ supported
proven by `validators`, `validators_on_decode` | ⚪ ignored: the types are generated; the checks aren't run yet (core#96)
proven by `validators`, `validators_on_decode` | -| imports between schemas
`imports` | ✅ supported
proven by `cross_schema`, `import_alias`, `import_glob` +6 more | ✅ supported
proven by `cross_schema`, `import_alias`, `import_glob` +6 more | -| nested namespaces
`nested-namespaces` | ✅ supported
proven by `nested_namespace`, `external_std`, `validators` +4 more | ✅ supported
proven by `nested_namespace`, `external_std`, `validators` +4 more | -| `lib` mode
`lib-mode` | ✅ supported
proven by `nested_namespace`, `external_std` | ✅ supported
proven by `nested_namespace`, `external_std` | -| `external_std`
`external-std` | ✅ supported
proven by `external_std` | ✅ supported
proven by `external_std` | -| `validate_on_decode`
`validate-on-decode` | ✅ supported
proven by `validators_on_decode` | ⚪ ignored: no checks are generated to run on decode yet (core#96)
proven by `validators_on_decode` | -| JSON-RPC framing
`framing-jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | -| no handshake
`handshake-none` | ✅ supported
proven by `handshake_none` | ✅ supported
proven by `handshake_none` | -| `datagram@3` framing
`framing-datagram3` | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +3 more | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +3 more | -| `comline@2` handshake
`handshake-comline2` | ✅ supported
proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +2 more | ✅ supported
proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +2 more | -| connections
`connections` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +13 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +12 more | -| `async`
`async` | ✅ supported
proven by `connections_async` | ⚪ ignored: handlers and senders always return Promises: the output is async either way
proven by `connections_async` | -| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | -| the `json@1` format
`format-json` | ✅ supported
proven by `format_json` | ✅ supported
proven by `format_json` | -| the `msgpack@1` format
`format-msgpack` | ✅ supported
proven by `format_msgpack` | ❌ unsupported: `@comline/runtime` has no MessagePack codec yet
proven by `format_msgpack` | -| bounds
`bounds` | ✅ supported
proven by `bounds` | ✅ supported
proven by `bounds` | -| single characters
`chars` | ✅ supported
proven by `chars` | ✅ supported
proven by `chars` | diff --git a/README.md b/README.md index be25927..53fdcb3 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,12 @@ ## Feature support -What each generator implements, and the conformance fixtures that prove it: -[`FEATURES.md`](FEATURES.md) (also as [`features.json`](features.json)). Both -are generated by the conformance suite; see -[`conformance/README.md`](conformance/README.md#feature-support). +What each generator implements, and the conformance fixtures that prove it, is +in the generator's own repository, which checks it with the corpus and harness +here: `FEATURES.md` (also as `features.json`) in +[`comline-rust`](https://github.com/ComlineProject/comline-rust) and +[`comline-typescript`](https://github.com/ComlineProject/comline-typescript). +See [`conformance/README.md`](conformance/README.md). ## `comline.toml` diff --git a/conformance/Cargo.toml b/conformance/Cargo.toml index d729dfa..c560879 100644 --- a/conformance/Cargo.toml +++ b/conformance/Cargo.toml @@ -5,19 +5,19 @@ edition = "2021" license = "GPL-3.0-only" publish = false -# The codegen conformance corpus: canonical `FrozenUnit` fixtures + golden -# generated output per target language. Catches generator drift and -# cross-language inconsistency, especially as the per-language generators move -# to their own repos. See design/runtime-repo-structure.md (rollout step 3). +# The codegen conformance corpus: canonical `FrozenUnit` fixtures, and the +# generator-agnostic harness that runs a generator over them and checks its +# golden output. The per-language generators live in their own repos and +# depend on this crate - never the other way, so a core change is pinned here +# first and then in each generator, with no round back. See +# design/runtime-repo-structure.md (rollout step 3). [dependencies] comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922" } # Not dev-only: a `Fixture` states the `Mode` it exercises, so the contract # types are part of the corpus's own public shape. comline-codegen = { path = "../codegen" } - -[dev-dependencies] +# The harness's own: a generator's entry point returns `eyre::Result`, and the +# feature report is JSON. eyre = "0.6.8" serde_json = "1.0" -comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "9aaf1079d743315de784745d616cded42648b840" } -comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "82fec7191722e6680fead8d180b49fea480ee2a0" } diff --git a/conformance/README.md b/conformance/README.md index 7c09c8f..64990ec 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -1,22 +1,59 @@ # comline-conformance -The codegen conformance corpus. Rollout step 3 of -`design/runtime-repo-structure.md`. +The codegen conformance corpus and the harness that runs a generator over it. +Rollout step 3 of `design/runtime-repo-structure.md`. -Each fixture in `src/lib.rs` is one schema as a hand-built `Vec` -(not parsed — the corpus pins IR shape, not parser behaviour). `tests/` runs -every registered generator over every fixture and diffs the output against the -checked-in goldens under `tests/golden//.`. +Each fixture in `src/lib.rs` is one package as hand-built `Vec`s +(not parsed - the corpus pins IR shape, not parser behaviour). `src/harness.rs` +is the generator-agnostic half: given a `Generator` (its entry point, its +`SUPPORT` table, its `VERSIONS`) it runs the generator over every fixture, at +each of its version boundaries, and diffs the output against golden files. + +## Where the generators and their goldens live + +Not here. A generator is a repository of its own +([`comline-rust`](https://github.com/ComlineProject/comline-rust), +[`comline-typescript`](https://github.com/ComlineProject/comline-typescript)) +that depends on this crate and runs the harness in its own test suite, against +goldens it holds under `codegen/tests/golden//[@]/`. +The dependency goes one way: a generator depends on generation, generation +depends on core, and nothing here depends on a generator. So a change to core +is pinned in generation, then in each generator, and nowhere does it come back. + +What stays here is what needs no generator: the corpus itself, the harness, and +the tests of what every generator shares on the requests they get +(`tests/dependency_protocols.rs`, `tests/nested_protocols.rs`). + +A generator wires the harness up like this (see either repo's +`codegen/tests/conformance.rs`): + +```rust +const GENERATOR: Generator = Generator { + language: "rust", + generate: comline_codegen_rust::generate_rust, + register: comline_codegen_rust::register, + support: comline_codegen_rust::SUPPORT, + versions: comline_codegen_rust::VERSIONS, +}; +``` + +and calls `harness::corpus_matches_golden`, `harness::support_is_proven` and +`harness::the_protocol_generates_what_the_generator_does`. In the generator's +repository: ```sh -cargo test -p comline-conformance # check -CONFORMANCE_BLESS=1 cargo test -p comline-conformance # regenerate goldens +cargo test -p comline-codegen-rust --test conformance # check +CONFORMANCE_BLESS=1 cargo test -p comline-codegen-rust --test conformance # regenerate goldens ``` A blessed golden is **a snapshot of what the generator does now**, not a statement of what it *should* do. When a generator changes, the diff shows up in that change's PR and the golden is re-blessed deliberately. +A change to a fixture here changes every generator's output for it, and shows +up as drift in each generator's suite when it pins the new revision: the +generator's PR carries the new goldens. + ## Feature support Each generator states what it implements in its `SUPPORT` table @@ -29,8 +66,8 @@ against this corpus: - an **unsupported** one is refused, with an error naming the feature. A claim no fixture can back fails the suite, so a new feature comes with a -fixture. The result is written to [`FEATURES.md`](../FEATURES.md) and -[`features.json`](../features.json) at the repository root, regenerated by the -same `CONFORMANCE_BLESS=1` run as the goldens. +fixture. The result is written to the generator's own `FEATURES.md` and +`features.json` at its repository root, regenerated by the same +`CONFORMANCE_BLESS=1` run as its goldens. See `ComlineProject/docs` → Design → *The `core` ↔ target contract*. diff --git a/conformance/src/harness.rs b/conformance/src/harness.rs new file mode 100644 index 0000000..2af373a --- /dev/null +++ b/conformance/src/harness.rs @@ -0,0 +1,656 @@ +//! The generator-agnostic half of the conformance suite: what runs a +//! generator over the [`corpus`](crate::corpus) and checks it. +//! +//! The corpus and this harness live here, in `ComlineProject/generation`, +//! because they need only `comline-codegen` and core. A generator does not +//! live here: it is a repository of its own that depends on this crate and +//! runs the harness over its own output, against goldens it holds itself. +//! That keeps the dependency one way - a generator depends on generation, +//! never the other - so a change to core is pinned in generation, then in +//! each generator, and nowhere does it come back. +//! +//! A generator describes itself as a [`Generator`], and its conformance test +//! is three calls: +//! +//! ```ignore +//! use comline_conformance::harness::{self, Generator}; +//! +//! const GENERATOR: Generator = Generator { +//! language: "rust", +//! generate: comline_codegen_rust::generate_rust, +//! register: comline_codegen_rust::register, +//! support: comline_codegen_rust::SUPPORT, +//! versions: comline_codegen_rust::VERSIONS, +//! }; +//! +//! #[test] +//! fn corpus_matches_golden() { +//! harness::corpus_matches_golden(&GENERATOR, &golden_root); +//! } +//! ``` +//! +//! `CONFORMANCE_BLESS=1` regenerates what these check: the goldens, and the +//! generator's `FEATURES.md` and `features.json`. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use comline_codegen::connections; +use comline_codegen::features::{self, Column, Feature, Options, State, SupportTable}; +use comline_codegen::versions::{LangVersion, Versions}; +use comline_codegen::{protocol, GenerateRequest, GeneratedFile, Registry}; +use comline_core::schema::idl::annotations::DEFAULT_FORMAT; +use comline_core::schema::ir::frozen::cas::blob::schema_ir_hash; +use comline_core::schema::ir::frozen::unit::FrozenUnit; + +use crate::{corpus, Fixture}; + +/// One generator, as the harness sees it: what it generates, what it claims +/// and which versions of its language it handles. +#[derive(Clone, Copy)] +pub struct Generator { + /// `rust`, `typescript`: the language a request targets, and the name of + /// the generator's goldens directories. + pub language: &'static str, + /// The generator's entry point. + pub generate: fn(&GenerateRequest) -> eyre::Result>, + /// Registers the generator with a [`Registry`], as its binary does. + pub register: fn(&mut Registry), + /// What the generator claims to support. + pub support: SupportTable, + /// Which versions of its language it handles. + pub versions: Versions, +} + +impl Generator { + /// Every version the generator's output or support can change at, the + /// floor first: testing at each covers every version. + fn boundaries(&self) -> Vec<&'static str> { + self.versions.boundaries() + } + + fn floor(&self, version: &str) -> bool { + version == self.versions.floor + } +} + +fn parsed(version: &str) -> LangVersion { + LangVersion::parse(version).unwrap_or_else(|| panic!("`{version}` isn't a version")) +} + +fn blessing() -> bool { + std::env::var_os("CONFORMANCE_BLESS").is_some() +} + +/// The request knobs `fx` sets, as the features detector reads them. +fn options(fx: &Fixture) -> Options { + Options { + mode: Some(fx.mode), + external_std: fx.external_std, + validate_on_decode: fx.validate_on_decode, + wire_format: fx.wire_format.map(str::to_string), + async_api: fx.async_api, + ..Default::default() + } +} + +/// Whether `fx` uses a feature `g` claims not to support at `version` - in +/// which case it must refuse, and has no golden there. +fn refused(g: &Generator, fx: &Fixture, version: &str) -> bool { + let uses = features::used(&fx.schemas, &options(fx)); + !features::unsupported_uses(&uses, g.support, &parsed(version)).is_empty() +} + +/// `///` for the floor, and +/// `/@/` for a later boundary whose output differs +/// from the one before it - one directory per (fixture, language, version), +/// holding the generated files at the paths the generator itself chose. +fn golden_dir(root: &Path, g: &Generator, fixture: &str, version: &str) -> PathBuf { + let name = if g.floor(version) { + g.language.to_string() + } else { + format!("{}@{version}", g.language) + }; + root.join(fixture).join(name) +} + +fn request(g: &Generator, fx: &Fixture, version: &str) -> GenerateRequest { + request_for(g, &fx.schemas, &fx.dependencies, &options(fx), version) +} + +/// A request for `schemas` under `options` at `version` - a fixture's own, +/// or the same with a feature stripped out. `dependencies` are the names the +/// package gives its dependencies, whose schemas are among `schemas`. +fn request_for( + g: &Generator, + schemas: &[(String, Vec)], + dependencies: &[&str], + options: &Options, + version: &str, +) -> GenerateRequest { + let wire_format = options + .wire_format + .clone() + .unwrap_or_else(|| DEFAULT_FORMAT.to_string()); + let mut request = GenerateRequest { + mode: options.mode.expect("a fixture states its mode"), + schemas: schemas.to_vec(), + package: comline_codegen::PackageMeta { + name: "conformance".to_string(), + version: "0.0.0".to_string(), + }, + // One of the generator's own boundaries: what a target declaring it + // gets, and every version up to the next boundary gets the same. + target: comline_codegen::TargetLanguage { + language: g.language.to_string(), + version: version.to_string(), + }, + wire_format: wire_format.clone(), + external_std: options.external_std, + validate_on_decode: options.validate_on_decode, + async_api: options.async_api, + encodings: comline_codegen::encodings::official_for(g.language), + facts: None, + dependencies: dependencies.iter().map(|d| d.to_string()).collect(), + }; + // Only a package that needs them gets facts, as from `comline generation`: + // the package's own, a dependency's protocols having their own package's. + if comline_codegen::facts::needed_in(&request) { + let own: Vec<_> = schemas + .iter() + .filter(|(namespace, _)| !connections::is_dependency(&request.dependencies, namespace)) + .cloned() + .collect(); + request.facts = Some(crate::facts_for(&own, &wire_format)); + } + request +} + +/// Every file under `dir`, as paths relative to it — so a golden that no +/// longer corresponds to anything the generator emits is reported instead of +/// lingering. Blessing would otherwise leave orphans behind forever. +fn existing_goldens(dir: &Path) -> Vec { + fn walk(dir: &Path, base: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, base, out); + } else if let Ok(rel) = path.strip_prefix(base) { + out.push(rel.to_path_buf()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +/// The generator protocol in process: for every fixture, at every boundary, +/// a `Generate` request through [`protocol::handle`] answers exactly the +/// files the generator returns when called directly, and a refusal comes +/// back as an error. +pub fn the_protocol_generates_what_the_generator_does(g: &Generator) { + let mut registry = Registry::new(); + (g.register)(&mut registry); + for fx in corpus() { + for version in g.boundaries() { + let req = request(g, &fx, version); + let bytes = protocol::encode(&protocol::Request::generate(req.clone())).unwrap(); + let response: protocol::Response = + protocol::decode(&protocol::handle(®istry, &bytes)).unwrap(); + let at = format!("{} / {}#{version}", fx.name, g.language); + match ((g.generate)(&req), response) { + (Ok(files), protocol::Response::Generate(generated)) => { + let direct: Vec = + files.into_iter().map(Into::into).collect(); + assert_eq!(generated.files, direct, "{at}"); + } + (Err(e), protocol::Response::Error { message }) => { + assert_eq!(message, format!("{e:#}"), "{at}") + } + (direct, response) => panic!( + "{at}: directly {:?}, through the protocol {response:?}", + direct.map(|f| f.len()) + ), + } + } + } +} + +/// Runs `g` over every fixture, at each of its version boundaries, and diffs +/// against the checked-in golden output under `root` +/// (`//[@]/`). `CONFORMANCE_BLESS=1` +/// regenerates them. +pub fn corpus_matches_golden(g: &Generator, root: &Path) { + let bless = blessing(); + let mut drift = Vec::new(); + + for fx in corpus() { + // What the boundary before generated, which a boundary whose + // output is the same doesn't store again. + let mut previous: Option> = None; + for version in g.boundaries() { + let at = format!("{} / {}#{version}", fx.name, g.language); + let dir = golden_dir(root, g, fx.name, version); + let floor = g.floor(version); + + // A fixture using a feature this generator claims not to + // support here must be refused - and so has nothing to + // compare. + if refused(g, &fx, version) { + if bless { + let _ = fs::remove_dir_all(&dir); + } else if !existing_goldens(&dir).is_empty() { + drift.push(format!( + "{at}: refused, but has goldens - run with CONFORMANCE_BLESS=1" + )); + } + previous = None; + continue; + } + + let files = (g.generate)(&request(g, &fx, version)) + .unwrap_or_else(|e| panic!("{at}: the generator failed: {e}")); + // A later boundary stores its own goldens only where its + // output differs from the boundary before. + let carried = !floor + && previous + .as_ref() + .is_some_and(|p| same_files(p, &files, &[])); + + if bless { + // Clear first: a file the generator no longer emits must + // not survive as a golden. + let _ = fs::remove_dir_all(&dir); + if !carried { + for file in &files { + let path = dir.join(&file.path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, &file.contents).unwrap(); + } + } + previous = Some(files); + continue; + } + + if carried { + if !existing_goldens(&dir).is_empty() { + drift.push(format!( + "{at}: generates the same as the boundary before, but has goldens of its own - \ + run with CONFORMANCE_BLESS=1" + )); + } + previous = Some(files); + continue; + } + + for file in &files { + let path = dir.join(&file.path); + match fs::read_to_string(&path) { + Ok(want) if file.contents == want => {} + Ok(want) => drift.push(format!( + "--- {at} / {} ---\n{}", + file.path.display(), + line_diff(&want, &file.contents) + )), + Err(_) => drift.push(format!( + "{at}: no golden at {} — run with CONFORMANCE_BLESS=1", + path.display() + )), + } + } + + let emitted: Vec = files.iter().map(|f| f.path.clone()).collect(); + for stale in existing_goldens(&dir) { + if !emitted.contains(&stale) { + drift.push(format!( + "{at}: golden `{}` is no longer emitted — run with CONFORMANCE_BLESS=1", + stale.display() + )); + } + } + previous = Some(files); + } + } + + // A golden *outside* any (language, boundary) directory. The sweep above + // can't see these: when fixtures were one schema the layout was + // `golden//.`, and moving to `/` left the + // old files tracked and invisible; a boundary a generator dropped leaves + // `@/` behind. Anything at the wrong level is reported + // rather than ignored. + let known: Vec = g + .boundaries() + .into_iter() + .map(|v| { + if g.floor(v) { + g.language.to_string() + } else { + format!("{}@{v}", g.language) + } + }) + .collect(); + for fx in corpus() { + let dir = root.join(fx.name); + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default() + .to_string(); + if !path.is_dir() || !known.contains(&name) { + drift.push(format!( + "{}: `{name}` is not a (language, boundary) directory — a stale golden from an \ + older layout, or a boundary that's gone?", + fx.name, + )); + } + } + } + + assert!( + drift.is_empty(), + "conformance drift ({} case(s)):\n\n{}", + drift.len(), + drift.join("\n\n") + ); +} + +/// A minimal line-oriented diff for the failure message. +fn line_diff(want: &str, got: &str) -> String { + let mut out = String::new(); + let (w, g): (Vec<_>, Vec<_>) = (want.lines().collect(), got.lines().collect()); + for i in 0..w.len().max(g.len()) { + match (w.get(i), g.get(i)) { + (Some(a), Some(b)) if a == b => {} + (a, b) => { + if let Some(a) = a { + out.push_str(&format!("- {a}\n")); + } + if let Some(b) = b { + out.push_str(&format!("+ {b}\n")); + } + } + } + } + out +} + +/// The proof behind `g`'s `SUPPORT` claims, against the corpus. +/// For each feature: +/// - the table states it, once; +/// - **supported / partial**: some fixture uses it and generates (its golden +/// is checked by [`corpus_matches_golden`]); partial says what's missing; +/// - **ignored**: some fixture uses it and generates, and every fixture +/// using it generates exactly what it would with the feature stripped; +/// - **unsupported**: some fixture uses it, and every fixture using it is +/// refused with an error naming the feature. +/// +/// It also writes the report - `FEATURES.md` and `features.json` in +/// `reports` - from what it proved; `CONFORMANCE_BLESS=1` regenerates them, +/// and a stale one fails here like a stale golden. +pub fn support_is_proven(g: &Generator, reports: &Path) { + let corpus = corpus(); + let mut failures = Vec::new(); + let mut evidence: BTreeMap<(String, Feature), Vec> = BTreeMap::new(); + + let lang = g.language; + let table = g.support; + for problem in g.versions.problems(table) { + failures.push(format!("{lang}: {problem}")); + } + + for &feature in Feature::ALL { + let entries = table.iter().filter(|(f, _)| *f == feature).count(); + if entries != 1 { + failures.push(format!( + "{lang}: `{}` is stated {entries} times, not once", + feature.id() + )); + continue; + } + } + + for &feature in Feature::ALL { + let claim = features::support_for(table, feature); + let using: Vec<&Fixture> = corpus + .iter() + .filter(|fx| { + features::used(&fx.schemas, &options(fx)) + .iter() + .any(|u| u.feature == feature) + }) + .collect(); + if using.is_empty() { + failures.push(format!( + "{lang}: `{}` is claimed {}, but no fixture uses it", + feature.id(), + claim.state.id() + )); + continue; + } + + let mut all_proven: Vec = Vec::new(); + for version in g.boundaries() { + let mut proven = Vec::new(); + let claim = features::support_at(table, feature, &parsed(version)); + let failed_before = failures.len(); + match claim.state { + State::Supported | State::Partial => { + if claim.state == State::Partial && claim.note.is_none() { + failures.push(format!( + "{lang}#{version}: `{}` is partial without saying what's missing", + feature.id() + )); + } + // A feature that can be taken out must make a difference + // somewhere: generating the same without it is ignoring it. + let mut differs = false; + for fx in &using { + if refused(g, fx, version) { + continue; + } + match (g.generate)(&request(g, fx, version)) { + Ok(with) => { + proven.push(fx.name.to_string()); + if let Some((schemas, stripped)) = + features::strip(feature, &fx.schemas, &options(fx)) + { + let hashes = ir_hashes(&fx.schemas, &schemas); + match (g.generate)(&request_for( + g, + &schemas, + &fx.dependencies, + &stripped, + version, + )) { + Ok(without) => { + differs |= !same_files(&with, &without, &hashes) + } + Err(_) => differs = true, + } + } else { + differs = true; + } + } + Err(e) => failures.push(format!( + "{lang}#{version}: `{}` fails `{}`: {e}", + fx.name, + feature.id() + )), + } + } + if !proven.is_empty() && !differs { + failures.push(format!( + "{lang}#{version}: `{}` is claimed {}, but every fixture using it generates the same without it \ + - it's ignored", + feature.id(), + claim.state.id() + )); + } + } + State::Ignored => { + for fx in &using { + if refused(g, fx, version) { + continue; + } + let Some((schemas, stripped)) = + features::strip(feature, &fx.schemas, &options(fx)) + else { + failures.push(format!( + "{lang}#{version}: `{}` is claimed ignored, but it can't be stripped to prove it", + feature.id() + )); + break; + }; + let with = (g.generate)(&request(g, fx, version)); + let without = (g.generate)(&request_for( + g, + &schemas, + &fx.dependencies, + &stripped, + version, + )); + // The IR hash names the schema itself, so it differs + // with the feature taken out - rightly: a peer that + // does check must not handshake as the same schema. + // Everything else must be identical. + let hashes = ir_hashes(&fx.schemas, &schemas); + match (with, without) { + (Ok(with), Ok(without)) if same_files(&with, &without, &hashes) => { + proven.push(fx.name.to_string()) + } + (Ok(_), Ok(_)) => failures.push(format!( + "{lang}#{version}: `{}` is claimed ignored, but `{}` generates differently without it", + feature.id(), + fx.name + )), + (Err(e), _) | (_, Err(e)) => { + failures.push(format!("{lang}#{version}: `{}` fails `{}`: {e}", fx.name, feature.id())) + } + } + } + } + State::Unsupported => { + for fx in &using { + match (g.generate)(&request(g, fx, version)) { + Err(e) if e.to_string().contains(&format!("({})", feature.id())) => { + proven.push(fx.name.to_string()) + } + Err(e) => failures.push(format!( + "{lang}#{version}: `{}` is refused without naming `{}`: {e}", + fx.name, + feature.id() + )), + Ok(_) => failures.push(format!( + "{lang}#{version}: `{}` is claimed unsupported, but `{}` generates anyway", + feature.id(), + fx.name + )), + } + } + } + } + if proven.is_empty() && failures.len() == failed_before { + failures.push(format!( + "{lang}#{version}: `{}` is claimed {}, but every fixture using it is refused for another feature", + feature.id(), + claim.state.id() + )); + } + for name in proven { + if !all_proven.contains(&name) { + all_proven.push(name); + } + } + } + evidence.insert((lang.to_string(), feature), all_proven); + } + + // The report, from what was proven. + let columns = [Column { + generator: g.language, + versions: g.versions, + support: g.support, + }]; + let files = [ + ( + reports.join("FEATURES.md"), + format!( + "# Generator features\n\n\ + \n\n\ + What the {lang} generator implements, and the conformance fixtures that prove it. \ + A claim is checked, not trusted: a supported feature has a fixture that generates \ + and matches its golden, an ignored one generates exactly what it would without the \ + feature, and an unsupported one is refused with an error naming every use.\n\n{}", + features::markdown(&columns, &evidence) + ), + ), + ( + reports.join("features.json"), + serde_json::to_string_pretty(&features::json(&columns, &evidence)).unwrap() + "\n", + ), + ]; + for (path, contents) in &files { + if blessing() { + fs::write(path, contents).unwrap(); + } else if fs::read_to_string(path).ok().as_deref() != Some(contents.as_str()) { + failures.push(format!( + "`{}` is out of date - run with CONFORMANCE_BLESS=1", + path.display() + )); + } + } + + assert!( + failures.is_empty(), + "unproven feature support ({}):\n {}", + failures.len(), + failures.join("\n ") + ); +} + +/// Every schema's IR hash in `a` and `b`, and each package's connection +/// hash, to mask when comparing their output. +fn ir_hashes(a: &[(String, Vec)], b: &[(String, Vec)]) -> Vec { + let mut hashes: Vec = a + .iter() + .chain(b) + .map(|(_, units)| schema_ir_hash(units)) + .collect(); + hashes.extend([ + connections::connection_ir_hash(a), + connections::connection_ir_hash(b), + ]); + hashes +} + +/// The same files with the same contents, in any order, once each of +/// `hashes` is masked out. +fn same_files(a: &[GeneratedFile], b: &[GeneratedFile], hashes: &[u64]) -> bool { + let mask = |contents: &str| { + hashes.iter().fold(contents.to_string(), |text, h| { + text.replace(&format!("{h:016x}"), "") + .replace(&format!("{h:x}"), "") + }) + }; + let key = |files: &[GeneratedFile]| { + let mut v: Vec<(PathBuf, String)> = files + .iter() + .map(|f| (f.path.clone(), mask(&f.contents))) + .collect(); + v.sort(); + v + }; + key(a) == key(b) +} diff --git a/conformance/src/lib.rs b/conformance/src/lib.rs index 19805f7..b3a2e3d 100644 --- a/conformance/src/lib.rs +++ b/conformance/src/lib.rs @@ -3,9 +3,10 @@ //! Each [`Fixture`] is a whole *package* — one or more schemas, as //! `Vec` built here rather than parsed, so the corpus pins exactly //! what IR shape every generator must handle, independent of the parser. -//! `tests/conformance.rs` runs every generator over every fixture and compares -//! to the checked-in golden output; run it with `CONFORMANCE_BLESS=1` to -//! (re)generate the goldens. +//! The [`harness`] runs a generator over every fixture and compares to its +//! checked-in golden output. The generators are not here: each is a repository +//! of its own that depends on this crate and keeps its own goldens (see the +//! harness's docs), so this crate depends on core and `comline-codegen` only. //! //! **Why a package and not a schema.** Until this was a package, every fixture //! had exactly one namespace, so the corpus could not express a reference that @@ -14,6 +15,8 @@ //! under a green suite. A corpus that cannot state the bug cannot guard //! against it. See Proposals → How generators are built. +pub mod harness; + use comline_codegen::validation::ValidateOnDecode; use comline_codegen::Mode; use comline_core::schema::ir::frozen::types::{Literal, PrimitiveType, TypeRef}; diff --git a/conformance/tests/conformance.rs b/conformance/tests/conformance.rs deleted file mode 100644 index 13ad0ae..0000000 --- a/conformance/tests/conformance.rs +++ /dev/null @@ -1,555 +0,0 @@ -//! Runs every generator over every fixture, at each of its version -//! boundaries, and diffs against the checked-in golden output. Regenerate the -//! goldens with: -//! -//! ```text -//! CONFORMANCE_BLESS=1 cargo test -p comline-conformance -//! ``` - -use std::fs; -use std::path::{Path, PathBuf}; - -use std::collections::BTreeMap; - -use comline_codegen::connections; -use comline_codegen::features::{self, Column, Feature, Options, State, SupportTable}; -use comline_codegen::versions::{LangVersion, Versions}; -use comline_codegen::{protocol, GenerateRequest, GeneratedFile, PackageMeta, Registry, TargetLanguage}; -use comline_conformance::{corpus, Fixture}; -use comline_core::schema::idl::annotations::DEFAULT_FORMAT; -use comline_core::schema::ir::frozen::cas::blob::schema_ir_hash; -use comline_core::schema::ir::frozen::unit::FrozenUnit; - -const LANGS: &[&str] = &["rust", "typescript"]; - -fn generate(lang: &str, req: &GenerateRequest) -> eyre::Result> { - match lang { - "rust" => comline_codegen_rust::generate_rust(req), - "typescript" => comline_codegen_typescript::generate_typescript(req), - other => panic!("unknown language `{other}`"), - } -} - -/// What `lang`'s generator claims to support. -fn support(lang: &str) -> SupportTable { - match lang { - "rust" => comline_codegen_rust::SUPPORT, - "typescript" => comline_codegen_typescript::SUPPORT, - other => panic!("unknown language `{other}`"), - } -} - -/// Which versions `lang`'s generator handles. -fn versions(lang: &str) -> Versions { - match lang { - "rust" => comline_codegen_rust::VERSIONS, - "typescript" => comline_codegen_typescript::VERSIONS, - other => panic!("unknown language `{other}`"), - } -} - -/// Every version `lang`'s output or support can change at, the floor first: -/// testing at each covers every version. -fn boundaries(lang: &str) -> Vec<&'static str> { - versions(lang).boundaries() -} - -fn parsed(version: &str) -> LangVersion { - LangVersion::parse(version).unwrap_or_else(|| panic!("`{version}` isn't a version")) -} - -/// The request knobs `fx` sets, as the features detector reads them. -fn options(fx: &Fixture) -> Options { - Options { - mode: Some(fx.mode), - external_std: fx.external_std, - validate_on_decode: fx.validate_on_decode, - wire_format: fx.wire_format.map(str::to_string), - async_api: fx.async_api, - ..Default::default() - } -} - -/// Whether `fx` uses a feature `lang`'s generator claims not to support at -/// `version` - in which case it must refuse, and has no golden there. -fn refused(fx: &Fixture, lang: &str, version: &str) -> bool { - let uses = features::used(&fx.schemas, &options(fx)); - !features::unsupported_uses(&uses, support(lang), &parsed(version)).is_empty() -} - -/// `tests/golden///` for the floor, and -/// `/@/` for a later boundary whose output differs -/// from the one before it - one directory per (fixture, language, version), -/// holding the generated files at the paths the generator itself chose. -fn golden_dir(fixture: &str, lang: &str, version: &str) -> PathBuf { - let name = if version == versions(lang).floor { lang.to_string() } else { format!("{lang}@{version}") }; - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden").join(fixture).join(name) -} - -fn request(fx: &Fixture, lang: &str, version: &str) -> GenerateRequest { - request_for(&fx.schemas, &fx.dependencies, &options(fx), lang, version) -} - -/// A request for `schemas` under `options` at `version` - a fixture's own, -/// or the same with a feature stripped out. `dependencies` are the names the -/// package gives its dependencies, whose schemas are among `schemas`. -fn request_for( - schemas: &[(String, Vec)], - dependencies: &[&str], - options: &Options, - lang: &str, - version: &str, -) -> GenerateRequest { - let wire_format = options.wire_format.clone().unwrap_or_else(|| DEFAULT_FORMAT.to_string()); - let mut request = GenerateRequest { - mode: options.mode.expect("a fixture states its mode"), - schemas: schemas.to_vec(), - package: PackageMeta { - name: "conformance".to_string(), - version: "0.0.0".to_string(), - }, - // One of the generator's own boundaries: what a target declaring it - // gets, and every version up to the next boundary gets the same. - target: TargetLanguage { language: lang.to_string(), version: version.to_string() }, - wire_format: wire_format.clone(), - external_std: options.external_std, - validate_on_decode: options.validate_on_decode, - async_api: options.async_api, - encodings: comline_codegen::encodings::official_for(lang), - facts: None, - dependencies: dependencies.iter().map(|d| d.to_string()).collect(), - }; - // Only a package that needs them gets facts, as from `comline generation`: - // the package's own, a dependency's protocols having their own package's. - if comline_codegen::facts::needed_in(&request) { - let own: Vec<_> = schemas - .iter() - .filter(|(namespace, _)| !connections::is_dependency(&request.dependencies, namespace)) - .cloned() - .collect(); - request.facts = Some(comline_conformance::facts_for(&own, &wire_format)); - } - request -} - -/// Every file under `dir`, as paths relative to it — so a golden that no -/// longer corresponds to anything the generator emits is reported instead of -/// lingering. Blessing would otherwise leave orphans behind forever. -fn existing_goldens(dir: &Path) -> Vec { - fn walk(dir: &Path, base: &Path, out: &mut Vec) { - let Ok(entries) = fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - walk(&path, base, out); - } else if let Ok(rel) = path.strip_prefix(base) { - out.push(rel.to_path_buf()); - } - } - } - let mut out = Vec::new(); - walk(dir, dir, &mut out); - out.sort(); - out -} - -/// The generator protocol in process: for every fixture, at every boundary, -/// a `Generate` request through [`protocol::handle`] answers exactly the -/// files the generator returns when called directly, and a refusal comes -/// back as an error. -#[test] -fn the_protocol_generates_what_the_generator_does() { - let mut registry = Registry::new(); - comline_codegen_rust::register(&mut registry); - comline_codegen_typescript::register(&mut registry); - for fx in corpus() { - for &lang in LANGS { - for version in boundaries(lang) { - let req = request(&fx, lang, version); - let bytes = protocol::encode(&protocol::Request::generate(req.clone())).unwrap(); - let response: protocol::Response = protocol::decode(&protocol::handle(®istry, &bytes)).unwrap(); - let at = format!("{} / {lang}#{version}", fx.name); - match (generate(lang, &req), response) { - (Ok(files), protocol::Response::Generate(generated)) => { - let direct: Vec = files.into_iter().map(Into::into).collect(); - assert_eq!(generated.files, direct, "{at}"); - } - (Err(e), protocol::Response::Error { message }) => assert_eq!(message, format!("{e:#}"), "{at}"), - (direct, response) => panic!("{at}: directly {:?}, through the protocol {response:?}", direct.map(|f| f.len())), - } - } - } - } -} - -#[test] -fn corpus_matches_golden() { - let bless = std::env::var_os("CONFORMANCE_BLESS").is_some(); - let mut drift = Vec::new(); - - for fx in corpus() { - for &lang in LANGS { - // What the boundary before generated, which a boundary whose - // output is the same doesn't store again. - let mut previous: Option> = None; - for version in boundaries(lang) { - let at = format!("{} / {lang}#{version}", fx.name); - let dir = golden_dir(fx.name, lang, version); - let floor = version == versions(lang).floor; - - // A fixture using a feature this generator claims not to - // support here must be refused - and so has nothing to - // compare. - if refused(&fx, lang, version) { - if bless { - let _ = fs::remove_dir_all(&dir); - } else if !existing_goldens(&dir).is_empty() { - drift.push(format!("{at}: refused, but has goldens - run with CONFORMANCE_BLESS=1")); - } - previous = None; - continue; - } - - let files = generate(lang, &request(&fx, lang, version)) - .unwrap_or_else(|e| panic!("{at}: the generator failed: {e}")); - // A later boundary stores its own goldens only where its - // output differs from the boundary before. - let carried = !floor && previous.as_ref().is_some_and(|p| same_files(p, &files, &[])); - - if bless { - // Clear first: a file the generator no longer emits must - // not survive as a golden. - let _ = fs::remove_dir_all(&dir); - if !carried { - for file in &files { - let path = dir.join(&file.path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, &file.contents).unwrap(); - } - } - previous = Some(files); - continue; - } - - if carried { - if !existing_goldens(&dir).is_empty() { - drift.push(format!( - "{at}: generates the same as the boundary before, but has goldens of its own - \ - run with CONFORMANCE_BLESS=1" - )); - } - previous = Some(files); - continue; - } - - for file in &files { - let path = dir.join(&file.path); - match fs::read_to_string(&path) { - Ok(want) if file.contents == want => {} - Ok(want) => drift.push(format!( - "--- {at} / {} ---\n{}", - file.path.display(), - line_diff(&want, &file.contents) - )), - Err(_) => drift.push(format!( - "{at}: no golden at {} — run with CONFORMANCE_BLESS=1", - path.display() - )), - } - } - - let emitted: Vec = files.iter().map(|f| f.path.clone()).collect(); - for stale in existing_goldens(&dir) { - if !emitted.contains(&stale) { - drift.push(format!( - "{at}: golden `{}` is no longer emitted — run with CONFORMANCE_BLESS=1", - stale.display() - )); - } - } - previous = Some(files); - } - } - } - - // A golden *outside* any (language, boundary) directory. The sweep above - // can't see these: when fixtures were one schema the layout was - // `golden//.`, and moving to `/` left the - // old files tracked and invisible; a boundary a generator dropped leaves - // `@/` behind. Anything at the wrong level is reported - // rather than ignored. - let known: Vec = LANGS - .iter() - .flat_map(|&lang| boundaries(lang).into_iter().map(move |v| (lang, v))) - .map(|(lang, v)| if v == versions(lang).floor { lang.to_string() } else { format!("{lang}@{v}") }) - .collect(); - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"); - for fx in corpus() { - let dir = root.join(fx.name); - let Ok(entries) = fs::read_dir(&dir) else { - continue; - }; - for entry in entries.flatten() { - let path = entry.path(); - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default().to_string(); - if !path.is_dir() || !known.contains(&name) { - drift.push(format!( - "{}: `{name}` is not a (language, boundary) directory — a stale golden from an \ - older layout, or a boundary that's gone?", - fx.name, - )); - } - } - } - - assert!( - drift.is_empty(), - "conformance drift ({} case(s)):\n\n{}", - drift.len(), - drift.join("\n\n") - ); -} - -/// A minimal line-oriented diff for the failure message. -fn line_diff(want: &str, got: &str) -> String { - let mut out = String::new(); - let (w, g): (Vec<_>, Vec<_>) = (want.lines().collect(), got.lines().collect()); - for i in 0..w.len().max(g.len()) { - match (w.get(i), g.get(i)) { - (Some(a), Some(b)) if a == b => {} - (a, b) => { - if let Some(a) = a { - out.push_str(&format!("- {a}\n")); - } - if let Some(b) = b { - out.push_str(&format!("+ {b}\n")); - } - } - } - } - out -} - -/// The proof behind every generator's `SUPPORT` claims, against the corpus. -/// For each generator and feature: -/// - the table states it, once; -/// - **supported / partial**: some fixture uses it and generates (its golden -/// is checked by [`corpus_matches_golden`]); partial says what's missing; -/// - **ignored**: some fixture uses it and generates, and every fixture -/// using it generates exactly what it would with the feature stripped; -/// - **unsupported**: some fixture uses it, and every fixture using it is -/// refused with an error naming the feature. -/// -/// It also writes the report - `FEATURES.md` and `features.json` at the -/// repository root - from what it proved; `CONFORMANCE_BLESS=1` regenerates -/// them, and a stale one fails here like a stale golden. -#[test] -fn support_is_proven() { - let corpus = corpus(); - let mut failures = Vec::new(); - let mut evidence: BTreeMap<(String, Feature), Vec> = BTreeMap::new(); - - for &lang in LANGS { - let table = support(lang); - for problem in versions(lang).problems(table) { - failures.push(format!("{lang}: {problem}")); - } - - for &feature in Feature::ALL { - let entries = table.iter().filter(|(f, _)| *f == feature).count(); - if entries != 1 { - failures.push(format!("{lang}: `{}` is stated {entries} times, not once", feature.id())); - continue; - } - } - - for &feature in Feature::ALL { - let claim = features::support_for(table, feature); - let using: Vec<&Fixture> = corpus - .iter() - .filter(|fx| features::used(&fx.schemas, &options(fx)).iter().any(|u| u.feature == feature)) - .collect(); - if using.is_empty() { - failures.push(format!( - "{lang}: `{}` is claimed {}, but no fixture uses it", - feature.id(), - claim.state.id() - )); - continue; - } - - let mut all_proven: Vec = Vec::new(); - for version in boundaries(lang) { - let mut proven = Vec::new(); - let claim = features::support_at(table, feature, &parsed(version)); - let failed_before = failures.len(); - match claim.state { - State::Supported | State::Partial => { - if claim.state == State::Partial && claim.note.is_none() { - failures.push(format!("{lang}#{version}: `{}` is partial without saying what's missing", feature.id())); - } - // A feature that can be taken out must make a difference - // somewhere: generating the same without it is ignoring it. - let mut differs = false; - for fx in &using { - if refused(fx, lang, version) { - continue; - } - match generate(lang, &request(fx, lang, version)) { - Ok(with) => { - proven.push(fx.name.to_string()); - if let Some((schemas, stripped)) = features::strip(feature, &fx.schemas, &options(fx)) { - let hashes = ir_hashes(&fx.schemas, &schemas); - match generate(lang, &request_for(&schemas, &fx.dependencies, &stripped, lang, version)) { - Ok(without) => differs |= !same_files(&with, &without, &hashes), - Err(_) => differs = true, - } - } else { - differs = true; - } - } - Err(e) => failures.push(format!("{lang}#{version}: `{}` fails `{}`: {e}", fx.name, feature.id())), - } - } - if !proven.is_empty() && !differs { - failures.push(format!( - "{lang}#{version}: `{}` is claimed {}, but every fixture using it generates the same without it \ - - it's ignored", - feature.id(), - claim.state.id() - )); - } - } - State::Ignored => { - for fx in &using { - if refused(fx, lang, version) { - continue; - } - let Some((schemas, stripped)) = features::strip(feature, &fx.schemas, &options(fx)) else { - failures.push(format!( - "{lang}#{version}: `{}` is claimed ignored, but it can't be stripped to prove it", - feature.id() - )); - break; - }; - let with = generate(lang, &request(fx, lang, version)); - let without = generate(lang, &request_for(&schemas, &fx.dependencies, &stripped, lang, version)); - // The IR hash names the schema itself, so it differs - // with the feature taken out - rightly: a peer that - // does check must not handshake as the same schema. - // Everything else must be identical. - let hashes = ir_hashes(&fx.schemas, &schemas); - match (with, without) { - (Ok(with), Ok(without)) if same_files(&with, &without, &hashes) => { - proven.push(fx.name.to_string()) - } - (Ok(_), Ok(_)) => failures.push(format!( - "{lang}#{version}: `{}` is claimed ignored, but `{}` generates differently without it", - feature.id(), - fx.name - )), - (Err(e), _) | (_, Err(e)) => { - failures.push(format!("{lang}#{version}: `{}` fails `{}`: {e}", fx.name, feature.id())) - } - } - } - } - State::Unsupported => { - for fx in &using { - match generate(lang, &request(fx, lang, version)) { - Err(e) if e.to_string().contains(&format!("({})", feature.id())) => { - proven.push(fx.name.to_string()) - } - Err(e) => failures.push(format!( - "{lang}#{version}: `{}` is refused without naming `{}`: {e}", - fx.name, - feature.id() - )), - Ok(_) => failures.push(format!( - "{lang}#{version}: `{}` is claimed unsupported, but `{}` generates anyway", - feature.id(), - fx.name - )), - } - } - } - } - if proven.is_empty() && failures.len() == failed_before { - failures.push(format!( - "{lang}#{version}: `{}` is claimed {}, but every fixture using it is refused for another feature", - feature.id(), - claim.state.id() - )); - } - for name in proven { - if !all_proven.contains(&name) { - all_proven.push(name); - } - } - } - evidence.insert((lang.to_string(), feature), all_proven); - } - } - - // The report, from what was proven. - let columns: Vec = LANGS - .iter() - .map(|&lang| Column { generator: lang, versions: versions(lang), support: support(lang) }) - .collect(); - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); - let reports = [ - ( - root.join("FEATURES.md"), - format!( - "# Generator features\n\n\ - \n\n\ - What each generator implements, and the conformance fixtures that prove it. \ - A claim is checked, not trusted: a supported feature has a fixture that generates \ - and matches its golden, an ignored one generates exactly what it would without the \ - feature, and an unsupported one is refused with an error naming every use.\n\n{}", - features::markdown(&columns, &evidence) - ), - ), - ( - root.join("features.json"), - serde_json::to_string_pretty(&features::json(&columns, &evidence)).unwrap() + "\n", - ), - ]; - let bless = std::env::var_os("CONFORMANCE_BLESS").is_some(); - for (path, contents) in &reports { - if bless { - fs::write(path, contents).unwrap(); - } else if fs::read_to_string(path).ok().as_deref() != Some(contents.as_str()) { - failures.push(format!("`{}` is out of date - run with CONFORMANCE_BLESS=1", path.display())); - } - } - - assert!(failures.is_empty(), "unproven feature support ({}):\n {}", failures.len(), failures.join("\n ")); -} - -/// Every schema's IR hash in `a` and `b`, and each package's connection -/// hash, to mask when comparing their output. -fn ir_hashes(a: &[(String, Vec)], b: &[(String, Vec)]) -> Vec { - let mut hashes: Vec = a.iter().chain(b).map(|(_, units)| schema_ir_hash(units)).collect(); - hashes.extend([connections::connection_ir_hash(a), connections::connection_ir_hash(b)]); - hashes -} - -/// The same files with the same contents, in any order, once each of -/// `hashes` is masked out. -fn same_files(a: &[GeneratedFile], b: &[GeneratedFile], hashes: &[u64]) -> bool { - let mask = |contents: &str| { - hashes.iter().fold(contents.to_string(), |text, h| { - text.replace(&format!("{h:016x}"), "").replace(&format!("{h:x}"), "") - }) - }; - let key = |files: &[GeneratedFile]| { - let mut v: Vec<(PathBuf, String)> = files.iter().map(|f| (f.path.clone(), mask(&f.contents))).collect(); - v.sort(); - v - }; - key(a) == key(b) -} diff --git a/conformance/tests/golden/bounds/rust/conformance.rs b/conformance/tests/golden/bounds/rust/conformance.rs deleted file mode 100644 index 6360569..0000000 --- a/conformance/tests/golden/bounds/rust/conformance.rs +++ /dev/null @@ -1,188 +0,0 @@ -// This file uses `comline_runtime` - add it to your Cargo.toml: -// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51" } -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -pub type Name = String; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Customer { - #[serde( - deserialize_with = "comline_runtime::bounds::decode::string::<_, 32>", - serialize_with = "comline_runtime::bounds::encode::string::<_, 32>" - )] - pub name: Name, - #[serde(with = "__comline_bounds::chars_2")] - pub country: String, - #[serde(default)] - #[serde(with = "__comline_bounds::option_of_chars_max_254")] - pub email: Option, - #[serde(with = "__comline_bounds::items_max_8_of_chars_max_16")] - pub tags: Vec, - #[serde( - deserialize_with = "comline_runtime::bounds::decode::vec::<_, _, 10>", - serialize_with = "comline_runtime::bounds::encode::vec::<_, _, 10>" - )] - pub scores: Vec, -} - -#[derive(Debug, Clone)] -pub struct Node { - pub label: String, - pub children: Vec, -} - -/// [`Node`]'s fields as serde reads and writes them; its own impls -/// count how deep it nests, at most 16 levels (`@max_depth`). -#[doc(hidden)] -#[allow(dead_code, non_camel_case_types)] -#[derive(Serialize, Deserialize)] -#[serde(remote = "Node")] -struct __NodeDepth { - #[serde( - deserialize_with = "comline_runtime::bounds::decode::string::<_, 64>", - serialize_with = "comline_runtime::bounds::encode::string::<_, 64>" - )] - pub label: String, - #[serde( - deserialize_with = "comline_runtime::bounds::decode::vec::<_, _, 4>", - serialize_with = "comline_runtime::bounds::encode::vec::<_, _, 4>" - )] - pub children: Vec, -} - -impl __NodeDepth { - fn depth(f: impl FnOnce(&mut comline_runtime::bounds::Depth) -> R) -> R { - ::std::thread_local! { - static DEPTH: ::core::cell::Cell = - const { ::core::cell::Cell::new(comline_runtime::bounds::Depth::new(16)) }; - } - DEPTH.with(|cell| { - let mut depth = cell.get(); - let r = f(&mut depth); - cell.set(depth); - r - }) - } -} - -impl Serialize for Node { - fn serialize(&self, s: S) -> Result { - __NodeDepth::depth(|d| d.enter()).map_err(comline_runtime::bounds::ser_error)?; - let r = __NodeDepth::serialize(self, s); - __NodeDepth::depth(|d| d.leave()); - r - } -} - -impl<'de> Deserialize<'de> for Node { - fn deserialize>(d: D) -> Result { - __NodeDepth::depth(|d| d.enter()).map_err(comline_runtime::bounds::de_error)?; - let r = __NodeDepth::deserialize(d); - __NodeDepth::depth(|d| d.leave()); - r - } -} - -/// How this file's bounded values decode and encode (core#98): each -/// module is a `#[serde(with)]` for one shape of bounds. -#[doc(hidden)] -#[allow(dead_code, unused_imports)] -mod __comline_bounds { - /// A string of exactly `.0` characters: more is refused before - /// it's allocated, as a maximum is. - #[derive(Clone, Copy)] - pub struct Exact(pub u32); - - impl<'de> serde::de::DeserializeSeed<'de> for Exact { - type Value = String; - - fn deserialize>(self, d: D) -> Result { - let s: String = serde::de::DeserializeSeed::deserialize(comline_runtime::bounds::CharsSeed::::new(self.0), d)?; - if s.chars().count() != self.0 as usize { - return Err(serde::de::Error::custom(::core::format_args!("a string of exactly {} characters", self.0))); - } - Ok(s) - } - } - - /// An optional value, decoded through the seed `.0` when present. - #[derive(Clone, Copy)] - pub struct Opt(pub S); - - impl<'de, S: serde::de::DeserializeSeed<'de>> serde::de::DeserializeSeed<'de> for Opt { - type Value = Option; - - fn deserialize>(self, d: D) -> Result { - d.deserialize_option(self) - } - } - - impl<'de, S: serde::de::DeserializeSeed<'de>> serde::de::Visitor<'de> for Opt { - type Value = Option; - - fn expecting(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - f.write_str("an optional value") - } - - fn visit_none(self) -> Result { - Ok(None) - } - - fn visit_unit(self) -> Result { - Ok(None) - } - - fn visit_some>(self, d: D) -> Result { - self.0.deserialize(d).map(Some) - } - } - - pub mod chars_2 { - use super::*; - - pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result { - serde::de::DeserializeSeed::deserialize(Exact(2), d) - } - - pub fn serialize(value: &String, s: S) -> Result { - if value.chars().count() != 2 { - return Err(serde::ser::Error::custom("a string of exactly 2 characters")); - } - serde::Serialize::serialize(value, s) - } - } - - pub mod items_max_8_of_chars_max_16 { - use super::*; - - pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { - serde::de::DeserializeSeed::deserialize(comline_runtime::bounds::ItemsSeed::<_, Vec>::new(comline_runtime::bounds::CharsSeed::::new(16), 8), d) - } - - pub fn serialize(value: &Vec, s: S) -> Result { - comline_runtime::bounds::check_items(value.len(), 8).map_err(comline_runtime::bounds::ser_error)?; - for item12 in value.iter() { - comline_runtime::bounds::check_chars(item12, 16).map_err(comline_runtime::bounds::ser_error)?; - } - serde::Serialize::serialize(value, s) - } - } - - pub mod option_of_chars_max_254 { - use super::*; - - pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { - serde::de::DeserializeSeed::deserialize(Opt(comline_runtime::bounds::CharsSeed::::new(254)), d) - } - - pub fn serialize(value: &Option, s: S) -> Result { - if let Some(inner12) = value { - comline_runtime::bounds::check_chars(inner12, 254).map_err(comline_runtime::bounds::ser_error)?; - } - serde::Serialize::serialize(value, s) - } - } -} - diff --git a/conformance/tests/golden/bounds/typescript/conformance.ts b/conformance/tests/golden/bounds/typescript/conformance.ts deleted file mode 100644 index b657373..0000000 --- a/conformance/tests/golden/bounds/typescript/conformance.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { checkChars, type Layout } from "@comline/runtime"; - -/** A string of at most 32 characters: make one with `Name.from`. */ -export type Name = string & { readonly __brand: "Name" }; - -export const NameLayout: Layout = { chars: { max: 32 } }; - -export const Name = { - /** `value` as a `Name`; throws a `RuntimeError` unless it holds at most 32 characters. */ - from(value: string): Name { - checkChars(value, 32); - return value as Name; - }, -}; - -export interface Customer { - name: Name; - country: string; - email?: string; - tags: string[]; - scores: number[]; -} - -export const CustomerLayout: Layout = { struct: [["name", () => NameLayout], ["country", { chars: { length: 2 } }], ["email", { option: { chars: { max: 254 } } }], ["tags", { array: { chars: { max: 16 } }, max: 8 }], ["scores", { array: "u32", max: 10 }]] }; - -export interface Node { - label: string; - children: Node[]; -} - -export const NodeLayout: Layout = { depth: 16, of: { struct: [["label", { chars: { max: 64 } }], ["children", { array: () => NodeLayout, max: 4 }]] } }; - diff --git a/conformance/tests/golden/chars/rust/conformance.rs b/conformance/tests/golden/chars/rust/conformance.rs deleted file mode 100644 index 346a355..0000000 --- a/conformance/tests/golden/chars/rust/conformance.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Grade { - pub letter: char, -} - diff --git a/conformance/tests/golden/chars/typescript/conformance.ts b/conformance/tests/golden/chars/typescript/conformance.ts deleted file mode 100644 index d81dea9..0000000 --- a/conformance/tests/golden/chars/typescript/conformance.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Grade { - letter: string; -} - -export const GradeLayout: Layout = { struct: [["letter", "char"]] }; - diff --git a/conformance/tests/golden/connections/rust/conformance.rs b/conformance/tests/golden/connections/rust/conformance.rs deleted file mode 100644 index b5e3fc2..0000000 --- a/conformance/tests/golden/connections/rust/conformance.rs +++ /dev/null @@ -1,250 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xb97e34b203ec1425; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatSendParams { - pub n: u32, -} - -pub type ChatSendError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat { - fn send(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["send"]; - -#[doc(hidden)] -pub struct ChatDispatcher(pub S); - -impl Dispatch for ChatDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ChatSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ChatSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ChatSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn send(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EventsShownParams { - pub n: u32, -} - -pub type EventsShownError = ::core::convert::Infallible; - -pub type EventsError = ::core::convert::Infallible; - -pub trait Events { - fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>; - fn ping(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const EVENTS_CALLS: &[&str] = &["shown", "ping"]; - -#[doc(hidden)] -pub struct EventsDispatcher(pub S); - -impl Dispatch for EventsDispatcher { - fn calls(&self) -> &'static [&'static str] { - EVENTS_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: EventsShownParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.shown(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.ping(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl EventsDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::connect(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Events` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct EventsSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> EventsSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn shown(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "shown"), &EventsShownParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn ping(&mut self) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(1, "ping"), &()) - } -} - diff --git a/conformance/tests/golden/connections/rust/connection.rs b/conformance/tests/golden/connections/rust/connection.rs deleted file mode 100644 index 071340b..0000000 --- a/conformance/tests/golden/connections/rust/connection.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Chat`. -//! - Implement the trait of each protocol the client provides: `conformance::Events`. -//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`. -//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`. -//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ChatDispatcher(self.chat).provide_on(conn); - } -} - -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct ClientServices { - pub events: Events, -} - -impl ClientServices { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::EventsDispatcher(self.events).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake, then provide every protocol in -/// `services`, which the server calls. Call the server's protocols through -/// their senders. -pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} diff --git a/conformance/tests/golden/connections/typescript/conformance.ts b/conformance/tests/golden/connections/typescript/conformance.ts deleted file mode 100644 index 814c58c..0000000 --- a/conformance/tests/golden/connections/typescript/conformance.ts +++ /dev/null @@ -1,184 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xb97e34b203ec1425n; - -export interface ChatSendParams { - n: number; -} - -/** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Chat { - send(peer: Peer, params: ChatSendParams): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["send"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, CHAT_CALLS)) { - case 0: { - try { - const p = codec.decode(params, ChatSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: ChatSendParams): Promise { - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export interface EventsShownParams { - n: number; -} - -/** @internal */ -export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Events { - shown(peer: Peer, params: EventsShownParams): Promise; - ping(peer: Peer): Promise; -} - -/** @internal */ -export const EVENTS_CALLS = ["shown", "ping"] as const; - -/** @internal */ -export class EventsDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly impl: Events; - - constructor(impl: Events) { - this.impl = impl; - } - - calls(): readonly string[] { - return EVENTS_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, EVENTS_CALLS)) { - case 0: { - try { - const p = codec.decode(params, EventsShownParamsLayout); - reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); - } catch { - reply.fault(); - } - return; - } - case 1: { - try { - await this.impl.ping(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(EventsDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class EventsSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async shown(params: EventsShownParams): Promise { - const env = await this.peer.call(EventsSender.PROTOCOL, { id: 0, name: "shown" }, params, { layout: EventsShownParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async ping(): Promise { - await this.peer.notify(EventsSender.PROTOCOL, { id: 1, name: "ping" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/connections/typescript/connection.ts b/conformance/tests/golden/connections/typescript/connection.ts deleted file mode 100644 index 18b3931..0000000 --- a/conformance/tests/golden/connections/typescript/connection.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport, { events })`. - * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_conformance.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); -} - -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface ClientServices { - events: ns_conformance.Events; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake, then provide every protocol in -* `services`, which the server calls. Call the server's protocols through -* their senders. -*/ -export async function connect(transport: Transport, services: ClientServices): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - provideClientServices(conn, services); - return conn; -} diff --git a/conformance/tests/golden/connections/typescript/wire.ts b/conformance/tests/golden/connections/typescript/wire.ts deleted file mode 100644 index 351fa7f..0000000 --- a/conformance/tests/golden/connections/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xb97e34b203ec1425n; diff --git a/conformance/tests/golden/connections_async/rust/conformance.rs b/conformance/tests/golden/connections_async/rust/conformance.rs deleted file mode 100644 index 11b4f9b..0000000 --- a/conformance/tests/golden/connections_async/rust/conformance.rs +++ /dev/null @@ -1,216 +0,0 @@ -// This file uses `comline_runtime`'s async driver - enable its feature in your Cargo.toml: -// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51", features = ["async"] } -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::{Answer, AsyncConnection, AsyncDispatch, AsyncPeer}; -use comline_runtime::transport::AsyncTransport; -use comline_runtime::contract::{Call, CallError, Envelope, Fault, Kind, RuntimeError, WireFormat}; -use comline_runtime::contract::{ConnectionFraming, ProtocolNumber}; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xb97e34b203ec1425; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatSendParams { - pub n: u32, -} - -pub type ChatSendError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat: Send + Sync + 'static { - fn send(&self, peer: &impl AsyncPeer, n: u32) -> impl ::core::future::Future>> + Send; -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["send"]; - -#[doc(hidden)] -pub struct ChatAsyncDispatcher(pub S); - -impl AsyncDispatch for ChatAsyncDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - async fn dispatch<'a, P: AsyncPeer>( - &'a self, - call: Kind, - params: &'a [u8], - peer: &'a P, - ) -> Result { - match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ChatSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => return Ok(Answer::fault()), - }; - match self.0.send(peer, p.n).await { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - Ok(Answer::ok(body)) - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => Ok(Answer::fault()), - } - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatAsyncDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `AsyncConnection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on(self, conn: &mut AsyncConnection) - where - T: AsyncTransport, - W: WireFormat + Send + Sync + 'static, - F: ConnectionFraming + Send + Sync + 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer an -/// `AsyncConnection`'s handle reaches, or the one a handler was given. -pub struct ChatAsyncSender<'p, P: AsyncPeer>(pub &'p P); - -impl<'p, P: AsyncPeer> ChatAsyncSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p P) -> Self { - Self(peer) - } - - pub async fn send(&self, n: u32) -> Result> { - let reply = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n }).await?; - let fmt = self.0.format(); - match reply.envelope() { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EventsShownParams { - pub n: u32, -} - -pub type EventsShownError = ::core::convert::Infallible; - -pub type EventsError = ::core::convert::Infallible; - -pub trait Events: Send + Sync + 'static { - fn shown(&self, peer: &impl AsyncPeer, n: u32) -> impl ::core::future::Future>> + Send; - fn ping(&self, peer: &impl AsyncPeer) -> impl ::core::future::Future + Send; -} - -#[doc(hidden)] -pub const EVENTS_CALLS: &[&str] = &["shown", "ping"]; - -#[doc(hidden)] -pub struct EventsAsyncDispatcher(pub S); - -impl AsyncDispatch for EventsAsyncDispatcher { - fn calls(&self) -> &'static [&'static str] { - EVENTS_CALLS - } - - async fn dispatch<'a, P: AsyncPeer>( - &'a self, - call: Kind, - params: &'a [u8], - peer: &'a P, - ) -> Result { - match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: EventsShownParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => return Ok(Answer::fault()), - }; - match self.0.shown(peer, p.n).await { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - Ok(Answer::ok(body)) - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => Ok(Answer::fault()), - } - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(Answer::none()), - }; - self.0.ping(peer).await; - Ok(Answer::none()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl EventsAsyncDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `AsyncConnection::connect(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on(self, conn: &mut AsyncConnection) - where - T: AsyncTransport, - W: WireFormat + Send + Sync + 'static, - F: ConnectionFraming + Send + Sync + 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Events` on the other end of a connection: the peer an -/// `AsyncConnection`'s handle reaches, or the one a handler was given. -pub struct EventsAsyncSender<'p, P: AsyncPeer>(pub &'p P); - -impl<'p, P: AsyncPeer> EventsAsyncSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - pub fn new(peer: &'p P) -> Self { - Self(peer) - } - - pub async fn shown(&self, n: u32) -> Result> { - let reply = self.0.call(Self::PROTOCOL, Call::new(0, "shown"), &EventsShownParams { n }).await?; - let fmt = self.0.format(); - match reply.envelope() { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn ping(&self) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(1, "ping"), &()) - } -} - diff --git a/conformance/tests/golden/connections_async/rust/connection.rs b/conformance/tests/golden/connections_async/rust/connection.rs deleted file mode 100644 index f130cbd..0000000 --- a/conformance/tests/golden/connections_async/rust/connection.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Chat`. -//! - Implement the trait of each protocol the client provides: `conformance::Events`. -//! - Serve with [`serve`]`(transport, Services { chat: .. }).await`, which runs until the peer leaves. [`accept`] hands the connection back first, not yet running: take its `handle()` to call the client, then `run().await` it. -//! - Dial with [`connect`]`(transport, ClientServices { events: .. }).await`, then `run().await` the connection it returns. -//! - Call the server from the dialling side: `ChatAsyncSender::new(&conn.handle()).send(..).await`. -//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsAsyncSender::new(&conn.handle()).shown(..).await`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::AsyncTransport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::AsyncConnection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ChatAsyncDispatcher(self.chat).provide_on(conn); - } -} - -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct ClientServices { - pub events: Events, -} - -impl ClientServices { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::EventsAsyncDispatcher(self.events).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// running, so the caller can take a `handle()` to call the client with -/// before it runs. -pub async fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::AsyncConnection::accept(transport, Format::default(), CONNECTION_IR_HASH).await?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub async fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services).await?.run().await -} - -/// Dial over `transport`: run the handshake, then provide every protocol in -/// `services`, which the server calls. Call the server's protocols through -/// their senders. -pub async fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::AsyncConnection::connect(transport, Format::default(), CONNECTION_IR_HASH).await?; - services.provide_on(&mut conn); - Ok(conn) -} diff --git a/conformance/tests/golden/connections_async/typescript/conformance.ts b/conformance/tests/golden/connections_async/typescript/conformance.ts deleted file mode 100644 index 814c58c..0000000 --- a/conformance/tests/golden/connections_async/typescript/conformance.ts +++ /dev/null @@ -1,184 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xb97e34b203ec1425n; - -export interface ChatSendParams { - n: number; -} - -/** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Chat { - send(peer: Peer, params: ChatSendParams): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["send"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, CHAT_CALLS)) { - case 0: { - try { - const p = codec.decode(params, ChatSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: ChatSendParams): Promise { - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export interface EventsShownParams { - n: number; -} - -/** @internal */ -export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Events { - shown(peer: Peer, params: EventsShownParams): Promise; - ping(peer: Peer): Promise; -} - -/** @internal */ -export const EVENTS_CALLS = ["shown", "ping"] as const; - -/** @internal */ -export class EventsDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly impl: Events; - - constructor(impl: Events) { - this.impl = impl; - } - - calls(): readonly string[] { - return EVENTS_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, EVENTS_CALLS)) { - case 0: { - try { - const p = codec.decode(params, EventsShownParamsLayout); - reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); - } catch { - reply.fault(); - } - return; - } - case 1: { - try { - await this.impl.ping(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(EventsDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class EventsSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async shown(params: EventsShownParams): Promise { - const env = await this.peer.call(EventsSender.PROTOCOL, { id: 0, name: "shown" }, params, { layout: EventsShownParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async ping(): Promise { - await this.peer.notify(EventsSender.PROTOCOL, { id: 1, name: "ping" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/connections_async/typescript/connection.ts b/conformance/tests/golden/connections_async/typescript/connection.ts deleted file mode 100644 index 18b3931..0000000 --- a/conformance/tests/golden/connections_async/typescript/connection.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport, { events })`. - * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_conformance.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); -} - -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface ClientServices { - events: ns_conformance.Events; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake, then provide every protocol in -* `services`, which the server calls. Call the server's protocols through -* their senders. -*/ -export async function connect(transport: Transport, services: ClientServices): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - provideClientServices(conn, services); - return conn; -} diff --git a/conformance/tests/golden/connections_async/typescript/wire.ts b/conformance/tests/golden/connections_async/typescript/wire.ts deleted file mode 100644 index 351fa7f..0000000 --- a/conformance/tests/golden/connections_async/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xb97e34b203ec1425n; diff --git a/conformance/tests/golden/connections_default/rust/conformance.rs b/conformance/tests/golden/connections_default/rust/conformance.rs deleted file mode 100644 index a6aa6f7..0000000 --- a/conformance/tests/golden/connections_default/rust/conformance.rs +++ /dev/null @@ -1,261 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x1ad273c98d4e98fb; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatSendParams { - pub n: u32, -} - -pub type ChatSendError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat { - fn send(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["send"]; - -#[doc(hidden)] -pub struct ChatDispatcher(pub S); - -impl Dispatch for ChatDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 0 => { - let p: ChatSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ChatSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ChatSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn send(&mut self, n: u32) -> Result> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Chat", "send")?; - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EventsShownParams { - pub n: u32, -} - -pub type EventsShownError = ::core::convert::Infallible; - -pub type EventsError = ::core::convert::Infallible; - -pub trait Events { - fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>; - fn ping(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const EVENTS_CALLS: &[&str] = &["shown", "ping"]; - -#[doc(hidden)] -pub struct EventsDispatcher(pub S); - -impl Dispatch for EventsDispatcher { - fn calls(&self) -> &'static [&'static str] { - EVENTS_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 1 => { - let p: EventsShownParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.shown(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 0 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.ping(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl EventsDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Events` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct EventsSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> EventsSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn shown(&mut self, n: u32) -> Result> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::Events", "shown")?; - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "shown"), &EventsShownParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn ping(&mut self) -> Result<(), RuntimeError> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Events", "ping")?; - self.0.notify(Self::PROTOCOL, Call::new(0, "ping"), &()) - } -} - diff --git a/conformance/tests/golden/connections_default/rust/connection.rs b/conformance/tests/golden/connections_default/rust/connection.rs deleted file mode 100644 index 0550366..0000000 --- a/conformance/tests/golden/connections_default/rust/connection.rs +++ /dev/null @@ -1,209 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Chat`. -//! - Implement the trait of each protocol the client provides: `conformance::Events`. -//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`. -//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`. -//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::{Peer, Reason, RuntimeError}; -use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated}; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x1ad273c98d4e98fb; - -/// The framing the package's connection runs on (`datagram@3`). -pub type Framing = comline_runtime::contract::Datagram3Framing; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its -/// history records it. Its protocols, by wire number: -/// -/// - 0 `conformance::Chat`, line 0.1.0: `send` 0 -/// - 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0 -#[doc(hidden)] -pub const HELLO: &[u8] = &[ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x02, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x02, 0x00, 0x01, -]; - -/// The `comline@2` handshake, with [`HELLO`] and the parameters the package -/// states: `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. -#[doc(hidden)] -pub fn handshake() -> Comline2Handshake { - use comline_runtime::handshake::comline2 as c2; - let hello = match c2::Message::decode(HELLO) { - Ok(c2::Message::Hello(hello)) => hello, - _ => unreachable!("HELLO is a Hello message"), - }; - let params = c2::Params { - scope: c2::Scope::Protocol, - newer_consumer: c2::NewerConsumer::Degrade, - same_version_differs: c2::SameVersionDiffers::Refuse, - exchange: c2::Exchange::Offer, - }; - c2::Comline2Handshake::new(params, hello) -} - -/// The package's protocols on the connection, by wire number. -const PROTOCOLS: &[(u16, &str)] = &[(0, "conformance::Chat"), (1, "conformance::Events")]; - -fn protocol_path(number: u16) -> &'static str { - PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path) -} - -/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in -/// the connection's extensions. -#[derive(Debug, Clone)] -pub struct Negotiation { - pub negotiated: Negotiated, - /// The last call that wasn't made because the peer can't take it. - pub unavailable: Option, -} - -/// A call that wasn't sent because the peer can't take it: which, and why. -/// The call itself fails with `RuntimeError::Unavailable`, which carries no -/// detail; [`unavailable`] gives this. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Unavailable { - /// `namespace::Protocol`. - pub protocol: &'static str, - pub function: &'static str, - /// Why the peer refused the protocol, or `None` when the peer lacks the - /// function (`newer_consumer = degrade`). - pub refused: Option, -} - -impl ::core::fmt::Display for Unavailable { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - match self.refused { - Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol), - None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function), - } - } -} - -impl ::core::error::Error for Unavailable {} - -/// What the connection's `comline@2` handshake agreed, if `accept` / `connect` -/// opened it. -pub fn negotiated(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().map(|n| n.negotiated.clone()) -} - -/// The protocols that connected although their wire shape differs from the -/// peer's at the same version (`same_version_differs = warn`), by path. -pub fn warnings(peer: &mut P) -> Vec<&'static str> { - let extensions = peer.extensions(); - match extensions.get::() { - Some(n) => n.negotiated.warnings.iter().map(|p| protocol_path(*p)).collect(), - None => Vec::new(), - } -} - -/// The last call on this connection that failed with `Unavailable`: which -/// function, and why. -pub fn unavailable(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().and_then(|n| n.unavailable) -} - -/// Whether `function` of `protocol` may be called: what each sender runs -/// before it writes a request. A connection opened some other way than -/// `accept` / `connect` has nothing to check against, and every call goes. -#[doc(hidden)] -pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'static str, name: &'static str) -> Result<(), RuntimeError> { - let extensions = peer.extensions(); - let Some(n) = extensions.get_mut::() else { - return Ok(()); - }; - let error = match n.negotiated.check_call(protocol, function) { - Ok(()) => return Ok(()), - Err(error) => error, - }; - let refused = n.negotiated.protocols.iter().find(|p| p.number == protocol).and_then(|p| match p.state { - comline_runtime::handshake::comline2::ProtocolState::Refused { reason } => Some(reason), - _ => None, - }); - // A protocol this end doesn't have isn't refused by the peer: it's unknown. - let refused = refused.or_else(|| (!n.negotiated.protocols.iter().any(|p| p.number == protocol)).then_some(Reason::UnknownProtocol)); - n.unavailable = Some(Unavailable { protocol: path, function: name, refused }); - Err(error) -} - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ChatDispatcher(self.chat).provide_on(conn); - } -} - -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct ClientServices { - pub events: Events, -} - -impl ClientServices { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::EventsDispatcher(self.events).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake, then provide every protocol in -/// `services`, which the server calls. Call the server's protocols through -/// their senders. -pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - services.provide_on(&mut conn); - Ok(conn) -} diff --git a/conformance/tests/golden/connections_default/typescript/conformance.ts b/conformance/tests/golden/connections_default/typescript/conformance.ts deleted file mode 100644 index 6e963a2..0000000 --- a/conformance/tests/golden/connections_default/typescript/conformance.ts +++ /dev/null @@ -1,188 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - checkCall, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x1ad273c98d4e98fbn; - -export interface ChatSendParams { - n: number; -} - -/** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Chat { - send(peer: Peer, params: ChatSendParams): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["send"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 0: { - try { - const p = codec.decode(params, ChatSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: ChatSendParams): Promise { - checkCall(this.peer, ChatSender.PROTOCOL, 0, "conformance::Chat", "send"); - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export interface EventsShownParams { - n: number; -} - -/** @internal */ -export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Events { - shown(peer: Peer, params: EventsShownParams): Promise; - ping(peer: Peer): Promise; -} - -/** @internal */ -export const EVENTS_CALLS = ["shown", "ping"] as const; - -/** @internal */ -export class EventsDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly impl: Events; - - constructor(impl: Events) { - this.impl = impl; - } - - calls(): readonly string[] { - return EVENTS_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 1: { - try { - const p = codec.decode(params, EventsShownParamsLayout); - reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); - } catch { - reply.fault(); - } - return; - } - case 0: { - try { - await this.impl.ping(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(EventsDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class EventsSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async shown(params: EventsShownParams): Promise { - checkCall(this.peer, EventsSender.PROTOCOL, 1, "conformance::Events", "shown"); - const env = await this.peer.call(EventsSender.PROTOCOL, { id: 1, name: "shown" }, params, { layout: EventsShownParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async ping(): Promise { - checkCall(this.peer, EventsSender.PROTOCOL, 0, "conformance::Events", "ping"); - await this.peer.notify(EventsSender.PROTOCOL, { id: 0, name: "ping" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/connections_default/typescript/connection.ts b/conformance/tests/golden/connections_default/typescript/connection.ts deleted file mode 100644 index 64218a9..0000000 --- a/conformance/tests/golden/connections_default/typescript/connection.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport, { events })`. - * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - Datagram3Framing, - Comline2Handshake, - Negotiated, - type Peer, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `conformance::Chat`, line 0.1.0: `send` 0 - * - 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0 - * - * @internal - */ -export const HELLO = new Uint8Array([ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x02, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x02, 0x00, 0x01, -]); - -/** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. - * @internal - */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { - scope: "protocol", - newerConsumer: "degrade", - sameVersionDiffers: "refuse", - exchange: "offer", - }); -} - -/** The package's protocols on the connection, by wire number. */ -const PROTOCOLS = new Map([[0, "conformance::Chat"], [1, "conformance::Events"]]); - -/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ -export function negotiated(conn: Peer): Negotiated | undefined { - return conn.extensions.get(Negotiated); -} - -/** - * The protocols that connected although their wire shape differs from the - * peer's at the same version (`same_version_differs = warn`), by path. - */ -export function warnings(conn: Peer): string[] { - return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); -} - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_conformance.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); -} - -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface ClientServices { - events: ns_conformance.Events; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake, then provide every protocol in -* `services`, which the server calls. Call the server's protocols through -* their senders. -*/ -export async function connect(transport: Transport, services: ClientServices): Promise { - const agreed = handshake(); - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - provideClientServices(conn, services); - return conn; -} diff --git a/conformance/tests/golden/connections_default/typescript/wire.ts b/conformance/tests/golden/connections_default/typescript/wire.ts deleted file mode 100644 index 7629bc6..0000000 --- a/conformance/tests/golden/connections_default/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x1ad273c98d4e98fbn; diff --git a/conformance/tests/golden/connections_jsonrpc/rust/conformance.rs b/conformance/tests/golden/connections_jsonrpc/rust/conformance.rs deleted file mode 100644 index a9f2e75..0000000 --- a/conformance/tests/golden/connections_jsonrpc/rust/conformance.rs +++ /dev/null @@ -1,250 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x30c29bde2ae397d9; - -#[doc(hidden)] -pub use crate::connection::CONNECTION_IR_HASH; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatSendParams { - pub n: u32, -} - -pub type ChatSendError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat { - fn send(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["send"]; - -#[doc(hidden)] -pub struct ChatDispatcher(pub S); - -impl Dispatch for ChatDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(CHAT_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ChatSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept_with(transport, format, comline_runtime::framing::JsonRpcFraming, &mut ComlineHandshake, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ChatSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ChatSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn send(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &ChatSendParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EventsShownParams { - pub n: u32, -} - -pub type EventsShownError = ::core::convert::Infallible; - -pub type EventsError = ::core::convert::Infallible; - -pub trait Events { - fn shown(&self, peer: &mut impl Peer, n: u32) -> Result>; - fn ping(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const EVENTS_CALLS: &[&str] = &["conformance.Events/shown", "conformance.Events/ping"]; - -#[doc(hidden)] -pub struct EventsDispatcher(pub S); - -impl Dispatch for EventsDispatcher { - fn calls(&self) -> &'static [&'static str] { - EVENTS_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(EVENTS_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: EventsShownParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.shown(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.ping(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl EventsDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::connect_with(transport, format, comline_runtime::framing::JsonRpcFraming, &mut ComlineHandshake, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Events` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct EventsSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> EventsSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn shown(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "conformance.Events/shown"), &EventsShownParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn ping(&mut self) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(1, "conformance.Events/ping"), &()) - } -} - diff --git a/conformance/tests/golden/connections_jsonrpc/rust/connection.rs b/conformance/tests/golden/connections_jsonrpc/rust/connection.rs deleted file mode 100644 index 3c96bb7..0000000 --- a/conformance/tests/golden/connections_jsonrpc/rust/connection.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `jsonrpc` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Chat`. -//! - Implement the trait of each protocol the client provides: `conformance::Events`. -//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport, ClientServices { events: .. })`. -//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`. -//! - Call the client from the accepting side, on the connection [`accept`] returns or the peer a handler is given: `EventsSender::new(&mut conn).shown(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x30c29bde2ae397d9; - -/// The framing the package's connection runs on (`jsonrpc`). -pub type Framing = comline_runtime::framing::JsonRpcFraming; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: JSON over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ChatDispatcher(self.chat).provide_on(conn); - } -} - -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct ClientServices { - pub events: Events, -} - -impl ClientServices { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::EventsDispatcher(self.events).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept_with(transport, comline_runtime::format::Json::default(), comline_runtime::framing::JsonRpcFraming, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake, then provide every protocol in -/// `services`, which the server calls. Call the server's protocols through -/// their senders. -pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::connect_with(transport, comline_runtime::format::Json::default(), comline_runtime::framing::JsonRpcFraming, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} diff --git a/conformance/tests/golden/connections_jsonrpc/typescript/conformance.ts b/conformance/tests/golden/connections_jsonrpc/typescript/conformance.ts deleted file mode 100644 index d68215a..0000000 --- a/conformance/tests/golden/connections_jsonrpc/typescript/conformance.ts +++ /dev/null @@ -1,184 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x30c29bde2ae397d9n; - -export interface ChatSendParams { - n: number; -} - -/** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Chat { - send(peer: Peer, params: ChatSendParams): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["send"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, CHAT_CALLS)) { - case 0: { - try { - const p = codec.decode(params, ChatSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: ChatSendParams): Promise { - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export interface EventsShownParams { - n: number; -} - -/** @internal */ -export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Events { - shown(peer: Peer, params: EventsShownParams): Promise; - ping(peer: Peer): Promise; -} - -/** @internal */ -export const EVENTS_CALLS = ["conformance.Events/shown", "conformance.Events/ping"] as const; - -/** @internal */ -export class EventsDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly impl: Events; - - constructor(impl: Events) { - this.impl = impl; - } - - calls(): readonly string[] { - return EVENTS_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, EVENTS_CALLS)) { - case 0: { - try { - const p = codec.decode(params, EventsShownParamsLayout); - reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); - } catch { - reply.fault(); - } - return; - } - case 1: { - try { - await this.impl.ping(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(EventsDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class EventsSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async shown(params: EventsShownParams): Promise { - const env = await this.peer.call(EventsSender.PROTOCOL, { id: 0, name: "conformance.Events/shown" }, params, { layout: EventsShownParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async ping(): Promise { - await this.peer.notify(EventsSender.PROTOCOL, { id: 1, name: "conformance.Events/ping" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/connections_jsonrpc/typescript/connection.ts b/conformance/tests/golden/connections_jsonrpc/typescript/connection.ts deleted file mode 100644 index c6942d9..0000000 --- a/conformance/tests/golden/connections_jsonrpc/typescript/connection.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport, { events })`. - * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - JsonCodec, - JsonRpcConnectionFraming, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_conformance.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); -} - -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface ClientServices { - events: ns_conformance.Events; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake, then provide every protocol in -* `services`, which the server calls. Call the server's protocols through -* their senders. -*/ -export async function connect(transport: Transport, services: ClientServices): Promise { - const conn = await Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); - provideClientServices(conn, services); - return conn; -} diff --git a/conformance/tests/golden/connections_jsonrpc/typescript/wire.ts b/conformance/tests/golden/connections_jsonrpc/typescript/wire.ts deleted file mode 100644 index 4e964de..0000000 --- a/conformance/tests/golden/connections_jsonrpc/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x30c29bde2ae397d9n; diff --git a/conformance/tests/golden/constant/rust/conformance.rs b/conformance/tests/golden/constant/rust/conformance.rs deleted file mode 100644 index 9381954..0000000 --- a/conformance/tests/golden/constant/rust/conformance.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. - -pub const MAX_RETRIES: u8 = 5; - diff --git a/conformance/tests/golden/constant/typescript/conformance.ts b/conformance/tests/golden/constant/typescript/conformance.ts deleted file mode 100644 index 649c7df..0000000 --- a/conformance/tests/golden/constant/typescript/conformance.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -export const MAX_RETRIES = 5; - diff --git a/conformance/tests/golden/cross_schema/rust/api.rs b/conformance/tests/golden/cross_schema/rust/api.rs deleted file mode 100644 index 140cb68..0000000 --- a/conformance/tests/golden/cross_schema/rust/api.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Holder { - pub one: crate::shared::Shared, - pub maybe: Option, - pub list: Vec, -} - diff --git a/conformance/tests/golden/cross_schema/rust/shared.rs b/conformance/tests/golden/cross_schema/rust/shared.rs deleted file mode 100644 index 598eca1..0000000 --- a/conformance/tests/golden/cross_schema/rust/shared.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Shared { - pub value: i32, -} - diff --git a/conformance/tests/golden/cross_schema/typescript/api.ts b/conformance/tests/golden/cross_schema/typescript/api.ts deleted file mode 100644 index c829ad2..0000000 --- a/conformance/tests/golden/cross_schema/typescript/api.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { SharedLayout } from "./shared.js"; -import type { Shared } from "./shared.js"; - -export interface Holder { - one: Shared; - maybe?: Shared; - list: Shared[]; -} - -export const HolderLayout: Layout = { struct: [["one", () => SharedLayout], ["maybe", { option: () => SharedLayout }], ["list", { array: () => SharedLayout }]] }; - diff --git a/conformance/tests/golden/cross_schema/typescript/shared.ts b/conformance/tests/golden/cross_schema/typescript/shared.ts deleted file mode 100644 index 362c34d..0000000 --- a/conformance/tests/golden/cross_schema/typescript/shared.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Shared { - value: number; -} - -export const SharedLayout: Layout = { struct: [["value", "s32"]] }; - diff --git a/conformance/tests/golden/dependency_and_own_protocols/rust/api.rs b/conformance/tests/golden/dependency_and_own_protocols/rust/api.rs deleted file mode 100644 index 80d4d08..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/rust/api.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x25f4c4d936e7aa90; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Message { - pub greeting: crate::localdeps::greeting::Greeting, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatGreetParams { - pub n: u32, -} - -pub type ChatGreetError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat { - fn greet(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["greet"]; - -#[doc(hidden)] -pub struct ChatDispatcher(pub S); - -impl Dispatch for ChatDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 0 => { - let p: ChatGreetParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.greet(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ChatSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ChatSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn greet(&mut self, n: u32) -> Result> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "api::Chat", "greet")?; - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "greet"), &ChatGreetParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/dependency_and_own_protocols/rust/connection.rs b/conformance/tests/golden/dependency_and_own_protocols/rust/connection.rs deleted file mode 100644 index bbeb477..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/rust/connection.rs +++ /dev/null @@ -1,189 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `api::Chat`. -//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `ChatSender::new(&mut conn).greet(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::{Peer, Reason, RuntimeError}; -use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated}; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x55e3b94344a9c775; - -/// The framing the package's connection runs on (`datagram@3`). -pub type Framing = comline_runtime::contract::Datagram3Framing; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its -/// history records it. Its protocols, by wire number: -/// -/// - 0 `api::Chat`, line 0.1.0: `greet` 0 -#[doc(hidden)] -pub const HELLO: &[u8] = &[ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, -]; - -/// The `comline@2` handshake, with [`HELLO`] and the parameters the package -/// states: `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. -#[doc(hidden)] -pub fn handshake() -> Comline2Handshake { - use comline_runtime::handshake::comline2 as c2; - let hello = match c2::Message::decode(HELLO) { - Ok(c2::Message::Hello(hello)) => hello, - _ => unreachable!("HELLO is a Hello message"), - }; - let params = c2::Params { - scope: c2::Scope::Protocol, - newer_consumer: c2::NewerConsumer::Degrade, - same_version_differs: c2::SameVersionDiffers::Refuse, - exchange: c2::Exchange::Offer, - }; - c2::Comline2Handshake::new(params, hello) -} - -/// The package's protocols on the connection, by wire number. -const PROTOCOLS: &[(u16, &str)] = &[(0, "api::Chat")]; - -fn protocol_path(number: u16) -> &'static str { - PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path) -} - -/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in -/// the connection's extensions. -#[derive(Debug, Clone)] -pub struct Negotiation { - pub negotiated: Negotiated, - /// The last call that wasn't made because the peer can't take it. - pub unavailable: Option, -} - -/// A call that wasn't sent because the peer can't take it: which, and why. -/// The call itself fails with `RuntimeError::Unavailable`, which carries no -/// detail; [`unavailable`] gives this. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Unavailable { - /// `namespace::Protocol`. - pub protocol: &'static str, - pub function: &'static str, - /// Why the peer refused the protocol, or `None` when the peer lacks the - /// function (`newer_consumer = degrade`). - pub refused: Option, -} - -impl ::core::fmt::Display for Unavailable { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - match self.refused { - Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol), - None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function), - } - } -} - -impl ::core::error::Error for Unavailable {} - -/// What the connection's `comline@2` handshake agreed, if `accept` / `connect` -/// opened it. -pub fn negotiated(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().map(|n| n.negotiated.clone()) -} - -/// The protocols that connected although their wire shape differs from the -/// peer's at the same version (`same_version_differs = warn`), by path. -pub fn warnings(peer: &mut P) -> Vec<&'static str> { - let extensions = peer.extensions(); - match extensions.get::() { - Some(n) => n.negotiated.warnings.iter().map(|p| protocol_path(*p)).collect(), - None => Vec::new(), - } -} - -/// The last call on this connection that failed with `Unavailable`: which -/// function, and why. -pub fn unavailable(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().and_then(|n| n.unavailable) -} - -/// Whether `function` of `protocol` may be called: what each sender runs -/// before it writes a request. A connection opened some other way than -/// `accept` / `connect` has nothing to check against, and every call goes. -#[doc(hidden)] -pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'static str, name: &'static str) -> Result<(), RuntimeError> { - let extensions = peer.extensions(); - let Some(n) = extensions.get_mut::() else { - return Ok(()); - }; - let error = match n.negotiated.check_call(protocol, function) { - Ok(()) => return Ok(()), - Err(error) => error, - }; - let refused = n.negotiated.protocols.iter().find(|p| p.number == protocol).and_then(|p| match p.state { - comline_runtime::handshake::comline2::ProtocolState::Refused { reason } => Some(reason), - _ => None, - }); - // A protocol this end doesn't have isn't refused by the peer: it's unknown. - let refused = refused.or_else(|| (!n.negotiated.protocols.iter().any(|p| p.number == protocol)).then_some(Reason::UnknownProtocol)); - n.unavailable = Some(Unavailable { protocol: path, function: name, refused }); - Err(error) -} - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::api::ChatDispatcher(self.chat).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - Ok(conn) -} diff --git a/conformance/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs b/conformance/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs deleted file mode 100644 index 7a4d6a7..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x653ed335b8ab7ba0; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Greeting { - pub text: String, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FooGreetParams { - pub n: u32, -} - -pub type FooGreetError = ::core::convert::Infallible; - -pub type FooError = ::core::convert::Infallible; - -pub trait Foo { - fn greet(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const FOO_CALLS: &[&str] = &["greet"]; - -pub struct FooDispatcher(pub S); - -impl Dispatch for FooDispatcher { - fn calls(&self) -> &'static [&'static str] { - FOO_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 0 => { - let p: FooGreetParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.greet(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl FooDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Foo` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct FooSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> FooSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn greet(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "greet"), &FooGreetParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/dependency_and_own_protocols/typescript/api.ts b/conformance/tests/golden/dependency_and_own_protocols/typescript/api.ts deleted file mode 100644 index 2b606ed..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/typescript/api.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - checkCall, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -import { GreetingLayout } from "./localdeps/greeting.js"; -import type { Greeting } from "./localdeps/greeting.js"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x25f4c4d936e7aa90n; - -export interface Message { - greeting: Greeting; -} - -export const MessageLayout: Layout = { struct: [["greeting", () => GreetingLayout]] }; - -export interface ChatGreetParams { - n: number; -} - -/** @internal */ -export const ChatGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Chat { - greet(peer: Peer, params: ChatGreetParams): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["greet"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 0: { - try { - const p = codec.decode(params, ChatGreetParamsLayout); - reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async greet(params: ChatGreetParams): Promise { - checkCall(this.peer, ChatSender.PROTOCOL, 0, "api::Chat", "greet"); - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: ChatGreetParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/dependency_and_own_protocols/typescript/connection.ts b/conformance/tests/golden/dependency_and_own_protocols/typescript/connection.ts deleted file mode 100644 index 7f6dd4c..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/typescript/connection.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat` (in `./api.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new ChatSender(conn).greet(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - Datagram3Framing, - Comline2Handshake, - Negotiated, - type Peer, - type Transport, -} from "@comline/runtime"; -import * as ns_api from "./api.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `api::Chat`, line 0.1.0: `greet` 0 - * - * @internal - */ -export const HELLO = new Uint8Array([ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, -]); - -/** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. - * @internal - */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { - scope: "protocol", - newerConsumer: "degrade", - sameVersionDiffers: "refuse", - exchange: "offer", - }); -} - -/** The package's protocols on the connection, by wire number. */ -const PROTOCOLS = new Map([[0, "api::Chat"]]); - -/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ -export function negotiated(conn: Peer): Negotiated | undefined { - return conn.extensions.get(Negotiated); -} - -/** - * The protocols that connected although their wire shape differs from the - * peer's at the same version (`same_version_differs = warn`), by path. - */ -export function warnings(conn: Peer): string[] { - return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); -} - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_api.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_api.ChatDispatcher(services.chat).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const agreed = handshake(); - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - return conn; -} diff --git a/conformance/tests/golden/dependency_and_own_protocols/typescript/localdeps/greeting.ts b/conformance/tests/golden/dependency_and_own_protocols/typescript/localdeps/greeting.ts deleted file mode 100644 index 66fc420..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/typescript/localdeps/greeting.ts +++ /dev/null @@ -1,100 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x653ed335b8ab7ba0n; - -export interface Greeting { - text: string; -} - -export const GreetingLayout: Layout = { struct: [["text", "string"]] }; - -export interface FooGreetParams { - n: number; -} - -/** @internal */ -export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Foo { - greet(peer: Peer, params: FooGreetParams): Promise; -} - -/** @internal */ -export const FOO_CALLS = ["greet"] as const; - -export class FooDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Foo; - - constructor(impl: Foo) { - this.impl = impl; - } - - calls(): readonly string[] { - return FOO_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 0: { - try { - const p = codec.decode(params, FooGreetParamsLayout); - reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new Comline2Handshake())` (`Format` and `CONNECTION_IR_HASH` are in `../wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(FooDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Foo` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class FooSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async greet(params: FooGreetParams): Promise { - const env = await this.peer.call(FooSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: FooGreetParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/dependency_and_own_protocols/typescript/wire.ts b/conformance/tests/golden/dependency_and_own_protocols/typescript/wire.ts deleted file mode 100644 index bf972a3..0000000 --- a/conformance/tests/golden/dependency_and_own_protocols/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x55e3b94344a9c775n; diff --git a/conformance/tests/golden/dependency_protocol/rust/api.rs b/conformance/tests/golden/dependency_protocol/rust/api.rs deleted file mode 100644 index a2edfbe..0000000 --- a/conformance/tests/golden/dependency_protocol/rust/api.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Message { - pub greeting: crate::localdeps::greeting::Greeting, -} - diff --git a/conformance/tests/golden/dependency_protocol/rust/localdeps/greeting.rs b/conformance/tests/golden/dependency_protocol/rust/localdeps/greeting.rs deleted file mode 100644 index 3c3caae..0000000 --- a/conformance/tests/golden/dependency_protocol/rust/localdeps/greeting.rs +++ /dev/null @@ -1,140 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x653ed335b8ab7ba0; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xc1fed94bf808faea; - -/// The package's wire format (`wire.format`): what this file's helpers -/// encode with, and what the peer has to speak too. -pub type Format = comline_runtime::format::Packed; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Greeting { - pub text: String, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FooGreetParams { - pub n: u32, -} - -pub type FooGreetError = ::core::convert::Infallible; - -pub type FooError = ::core::convert::Infallible; - -pub trait Foo { - fn greet(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const FOO_CALLS: &[&str] = &["greet"]; - -pub struct FooDispatcher(pub S); - -impl Dispatch for FooDispatcher { - fn calls(&self) -> &'static [&'static str] { - FOO_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 0 => { - let p: FooGreetParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.greet(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl FooDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Foo` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct FooSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> FooSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn greet(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "greet"), &FooGreetParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/dependency_protocol/typescript/api.ts b/conformance/tests/golden/dependency_protocol/typescript/api.ts deleted file mode 100644 index 35d787a..0000000 --- a/conformance/tests/golden/dependency_protocol/typescript/api.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { GreetingLayout } from "./localdeps/greeting.js"; -import type { Greeting } from "./localdeps/greeting.js"; - -export interface Message { - greeting: Greeting; -} - -export const MessageLayout: Layout = { struct: [["greeting", () => GreetingLayout]] }; - diff --git a/conformance/tests/golden/dependency_protocol/typescript/localdeps/greeting.ts b/conformance/tests/golden/dependency_protocol/typescript/localdeps/greeting.ts deleted file mode 100644 index 643f01d..0000000 --- a/conformance/tests/golden/dependency_protocol/typescript/localdeps/greeting.ts +++ /dev/null @@ -1,109 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - PackedCodec, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x653ed335b8ab7ba0n; - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xc1fed94bf808faean; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - -export interface Greeting { - text: string; -} - -export const GreetingLayout: Layout = { struct: [["text", "string"]] }; - -export interface FooGreetParams { - n: number; -} - -/** @internal */ -export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Foo { - greet(peer: Peer, params: FooGreetParams): Promise; -} - -/** @internal */ -export const FOO_CALLS = ["greet"] as const; - -export class FooDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Foo; - - constructor(impl: Foo) { - this.impl = impl; - } - - calls(): readonly string[] { - return FOO_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 0: { - try { - const p = codec.decode(params, FooGreetParamsLayout); - reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new Comline2Handshake())`, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(FooDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Foo` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class FooSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async greet(params: FooGreetParams): Promise { - const env = await this.peer.call(FooSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: FooGreetParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/enum_basic/rust/conformance.rs b/conformance/tests/golden/enum_basic/rust/conformance.rs deleted file mode 100644 index 3a3ba14..0000000 --- a/conformance/tests/golden/enum_basic/rust/conformance.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum State { - Pending, - Active, - Closed, -} - diff --git a/conformance/tests/golden/enum_basic/typescript/conformance.ts b/conformance/tests/golden/enum_basic/typescript/conformance.ts deleted file mode 100644 index 3a104f0..0000000 --- a/conformance/tests/golden/enum_basic/typescript/conformance.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export const State = { - Pending: "Pending", - Active: "Active", - Closed: "Closed", -} as const; -export type State = (typeof State)[keyof typeof State]; - -export const StateLayout: Layout = { enum: ["Pending", "Active", "Closed"] }; - diff --git a/conformance/tests/golden/error_shapes/rust/conformance.rs b/conformance/tests/golden/error_shapes/rust/conformance.rs deleted file mode 100644 index 6fe443c..0000000 --- a/conformance/tests/golden/error_shapes/rust/conformance.rs +++ /dev/null @@ -1,326 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x6fc29e1014b9b9c8; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct TooLong { - pub limit: u32, -} - -impl core::fmt::Display for TooLong { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{} is the limit", self.limit) - } -} - -impl core::error::Error for TooLong {} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Denied { -} - -impl core::fmt::Display for Denied { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("denied") - } -} - -impl core::error::Error for Denied {} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct MultiSendParams<'a> { - #[serde(borrow)] - pub body: &'a str, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum MultiSendError { - Denied(Denied), - TooLong(TooLong), -} - -impl core::fmt::Display for MultiSendError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - MultiSendError::Denied(e) => e.fmt(f), - MultiSendError::TooLong(e) => e.fmt(f), - } - } -} - -impl core::error::Error for MultiSendError {} - -#[derive(Debug, Clone, PartialEq)] -pub enum MultiError { - TooLong(TooLong), - Denied(Denied), -} - -impl core::fmt::Display for MultiError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - MultiError::TooLong(e) => e.fmt(f), - MultiError::Denied(e) => e.fmt(f), - } - } -} - -impl core::error::Error for MultiError {} - -impl From for MultiError { - fn from(e: MultiSendError) -> Self { - match e { - MultiSendError::Denied(x) => MultiError::Denied(x), - MultiSendError::TooLong(x) => MultiError::TooLong(x), - } - } -} - -pub trait Multi { - fn send(&self, peer: &mut impl Peer, body: &str) -> Result>; -} - -#[doc(hidden)] -pub const MULTI_CALLS: &[&str] = &["send"]; - -#[doc(hidden)] -pub struct MultiDispatcher(pub S); - -impl Dispatch for MultiDispatcher { - fn calls(&self) -> &'static [&'static str] { - MULTI_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(MULTI_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: MultiSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send(peer, p.body) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(MultiSendError::Denied(e))) => { - let mut body = Vec::new(); - peer.format().encode(&e, &mut body)?; - reply.err(2u16, &body); - } - Err(Fault::App(MultiSendError::TooLong(e))) => { - let mut body = Vec::new(); - peer.format().encode(&e, &mut body)?; - reply.err(1u16, &body); - } - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl MultiDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Multi` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct MultiSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> MultiSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn send(&mut self, body: &str) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "send"), &MultiSendParams { body })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id: 2u16, body } => { - let e: Denied = fmt.decode(body)?; - Err(CallError::App(MultiSendError::Denied(e))) - } - Envelope::Err { id: 1u16, body } => { - let e: TooLong = fmt.decode(body)?; - Err(CallError::App(MultiSendError::TooLong(e))) - } - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -pub type QuietPingError = ::core::convert::Infallible; - -pub type QuietError = ::core::convert::Infallible; - -pub trait Quiet { - fn ping(&self, peer: &mut impl Peer) -> Result>; - fn hush(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const QUIET_CALLS: &[&str] = &["ping", "hush"]; - -#[doc(hidden)] -pub struct QuietDispatcher(pub S); - -impl Dispatch for QuietDispatcher { - fn calls(&self) -> &'static [&'static str] { - QUIET_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(QUIET_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.ping(peer) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.hush(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl QuietDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Quiet` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct QuietSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> QuietSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 1; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn ping(&mut self) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "ping"), &())?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn hush(&mut self) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(1, "hush"), &()) - } -} - diff --git a/conformance/tests/golden/error_shapes/rust/connection.rs b/conformance/tests/golden/error_shapes/rust/connection.rs deleted file mode 100644 index e8569c2..0000000 --- a/conformance/tests/golden/error_shapes/rust/connection.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Multi`, `conformance::Quiet`. -//! - Serve with [`serve`]`(transport, Services { multi: .., quiet: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `MultiSender::new(&mut conn).send(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x6fc29e1014b9b9c8; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub multi: Multi, - pub quiet: Quiet, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::MultiDispatcher(self.multi).provide_on(conn); - crate::conformance::QuietDispatcher(self.quiet).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/error_shapes/typescript/conformance.ts b/conformance/tests/golden/error_shapes/typescript/conformance.ts deleted file mode 100644 index 3963fca..0000000 --- a/conformance/tests/golden/error_shapes/typescript/conformance.ts +++ /dev/null @@ -1,217 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x6fc29e1014b9b9c8n; - -export interface TooLong { - limit: number; -} - -export const TooLongLayout: Layout = { struct: [["limit", "u32"]] }; - -export class TooLongError extends Error { - static readonly ordinal = 1; - readonly data: TooLong; - constructor(data: TooLong) { - super("TooLong"); - this.data = data; - this.name = "TooLongError"; - } -} - -export interface Denied { -} - -export const DeniedLayout: Layout = { struct: [] }; - -export class DeniedError extends Error { - static readonly ordinal = 2; - readonly data: Denied; - constructor(data: Denied) { - super("Denied"); - this.data = data; - this.name = "DeniedError"; - } -} - -export interface MultiSendParams { - body: string; -} - -/** @internal */ -export const MultiSendParamsLayout: Layout = { struct: [["body", "string"]] }; - -export interface Multi { - /** @throws {DeniedError | TooLongError} */ - send(peer: Peer, params: MultiSendParams): Promise; -} - -/** @internal */ -export const MULTI_CALLS = ["send"] as const; - -/** @internal */ -export class MultiDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Multi; - - constructor(impl: Multi) { - this.impl = impl; - } - - calls(): readonly string[] { - return MULTI_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, MULTI_CALLS)) { - case 0: { - try { - const p = codec.decode(params, MultiSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u64")); - } catch (e) { - if (e instanceof DeniedError) { reply.err(DeniedError.ordinal, codec.encode(e.data, DeniedLayout)); return; } - if (e instanceof TooLongError) { reply.err(TooLongError.ordinal, codec.encode(e.data, TooLongLayout)); return; } - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(MultiDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Multi` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class MultiSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: MultiSendParams): Promise { - const env = await this.peer.call(MultiSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: MultiSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u64"); - if ("fault" in env) throw RuntimeError.provider(); - switch (env.err.id) { - case DeniedError.ordinal: - throw new DeniedError(this.peer.codec.decode(env.err.body, DeniedLayout)); - case TooLongError.ordinal: - throw new TooLongError(this.peer.codec.decode(env.err.body, TooLongLayout)); - default: - throw RuntimeError.remote(env.err.id); - } - } -} - -export interface Quiet { - ping(peer: Peer): Promise; - hush(peer: Peer): Promise; -} - -/** @internal */ -export const QUIET_CALLS = ["ping", "hush"] as const; - -/** @internal */ -export class QuietDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly impl: Quiet; - - constructor(impl: Quiet) { - this.impl = impl; - } - - calls(): readonly string[] { - return QUIET_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, QUIET_CALLS)) { - case 0: { - try { - reply.ok(codec.encode((await this.impl.ping(peer)) ?? null, "u64")); - } catch { - reply.fault(); - } - return; - } - case 1: { - try { - await this.impl.hush(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(QuietDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Quiet` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class QuietSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 1; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async ping(): Promise { - const env = await this.peer.call(QuietSender.PROTOCOL, { id: 0, name: "ping" }, null, { layout: "unit" }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u64"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async hush(): Promise { - await this.peer.notify(QuietSender.PROTOCOL, { id: 1, name: "hush" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/error_shapes/typescript/connection.ts b/conformance/tests/golden/error_shapes/typescript/connection.ts deleted file mode 100644 index 7fb3179..0000000 --- a/conformance/tests/golden/error_shapes/typescript/connection.ts +++ /dev/null @@ -1,64 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Multi`, `Quiet` (in `./conformance.js`). - * - Serve with `serve(transport, { multi, quiet })`; `accept(transport, { multi, quiet })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new MultiSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - multi: ns_conformance.Multi; - quiet: ns_conformance.Quiet; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.MultiDispatcher(services.multi).provideOn(conn); - new ns_conformance.QuietDispatcher(services.quiet).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - return conn; -} diff --git a/conformance/tests/golden/error_shapes/typescript/wire.ts b/conformance/tests/golden/error_shapes/typescript/wire.ts deleted file mode 100644 index a7aab5f..0000000 --- a/conformance/tests/golden/error_shapes/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x6fc29e1014b9b9c8n; diff --git a/conformance/tests/golden/external_std/rust/Cargo.toml b/conformance/tests/golden/external_std/rust/Cargo.toml deleted file mode 100644 index 9957879..0000000 --- a/conformance/tests/golden/external_std/rust/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -# Generated by Comline -[package] -name = "conformance" -version = "0.0.0" -edition = "2024" -rust-version = "1.85.0" -# A schema namespace named `main` would otherwise be picked up as a -# binary target (`src/main.rs`) with no `fn main`. Core refuses that -# name outright now; this stays as a belt-and-braces guard for a -# `GenRequest` built by hand. -autobins = false - -[dependencies] -serde = { version = "1", features = ["derive"] } -comline_std = { git = "https://github.com/ComlineProject/comline-rust", rev = "fa2b4cc65cbd1b91443fd694d0df9c816f55fb51" } diff --git a/conformance/tests/golden/external_std/rust/src/api.rs b/conformance/tests/golden/external_std/rust/src/api.rs deleted file mode 100644 index 77c7416..0000000 --- a/conformance/tests/golden/external_std/rust/src/api.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Call { - pub request: comline_std::http::Request, -} - diff --git a/conformance/tests/golden/external_std/rust/src/lib.rs b/conformance/tests/golden/external_std/rust/src/lib.rs deleted file mode 100644 index 45b4e44..0000000 --- a/conformance/tests/golden/external_std/rust/src/lib.rs +++ /dev/null @@ -1,5 +0,0 @@ -// Generated by Comline - -//! This package declares no protocols: it holds types, so there is nothing to serve or dial. - -pub mod api; diff --git a/conformance/tests/golden/external_std/typescript/package.json b/conformance/tests/golden/external_std/typescript/package.json deleted file mode 100644 index 1f36da5..0000000 --- a/conformance/tests/golden/external_std/typescript/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "conformance", - "version": "0.0.0", - "type": "module", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js" - }, - "./*": { - "types": "./dist/*.d.ts", - "import": "./dist/*.js" - } - }, - "files": ["dist", "src"], - "scripts": { - "build": "tsc" - }, - "dependencies": { - "@comline/std": "^0.1.0" - }, - "peerDependencies": { - "@comline/runtime": "^0.1.0", - "typescript": ">=5.0" - }, - "peerDependenciesMeta": { - "@comline/runtime": { "optional": true }, - "typescript": { "optional": true } - }, - "devDependencies": { - "typescript": "^5.6.0" - } -} diff --git a/conformance/tests/golden/external_std/typescript/src/api.ts b/conformance/tests/golden/external_std/typescript/src/api.ts deleted file mode 100644 index da338fa..0000000 --- a/conformance/tests/golden/external_std/typescript/src/api.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { RequestLayout } from "@comline/std/http"; -import type { Request } from "@comline/std/http"; - -export interface Call { - request: Request; -} - -export const CallLayout: Layout = { struct: [["request", () => RequestLayout]] }; - diff --git a/conformance/tests/golden/external_std/typescript/src/index.ts b/conformance/tests/golden/external_std/typescript/src/index.ts deleted file mode 100644 index da04339..0000000 --- a/conformance/tests/golden/external_std/typescript/src/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Generated by Comline - -export * as api from "./api.js"; diff --git a/conformance/tests/golden/external_std/typescript/tsconfig.json b/conformance/tests/golden/external_std/typescript/tsconfig.json deleted file mode 100644 index 931f802..0000000 --- a/conformance/tests/golden/external_std/typescript/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "outDir": "dist", - "rootDir": "src", - "declaration": true, - "strict": true, - "exactOptionalPropertyTypes": true, - "noUncheckedIndexedAccess": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true - }, - "include": ["src/**/*.ts"] -} diff --git a/conformance/tests/golden/format_json/rust/conformance.rs b/conformance/tests/golden/format_json/rust/conformance.rs deleted file mode 100644 index ace4801..0000000 --- a/conformance/tests/golden/format_json/rust/conformance.rs +++ /dev/null @@ -1,237 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x8ee00745c73a32b2; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Record { - pub id: i32, - pub name: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct NotFound { -} - -impl core::fmt::Display for NotFound { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("NotFound occurred") - } -} - -impl core::error::Error for NotFound {} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceLookupParams { - pub id: i32, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceNotifyParams { - pub code: u16, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceLookupError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceLookupError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceLookupError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceLookupError {} - -pub type ServiceCountError = ::core::convert::Infallible; - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceError {} - -impl From for ServiceError { - fn from(e: ServiceLookupError) -> Self { - match e { - ServiceLookupError::NotFound(x) => ServiceError::NotFound(x), - } - } -} - -pub trait Service { - fn lookup(&self, peer: &mut impl Peer, id: i32) -> Result>; - fn count(&self, peer: &mut impl Peer) -> Result>; - fn notify(&self, peer: &mut impl Peer, code: u16); -} - -#[doc(hidden)] -pub const SERVICE_CALLS: &[&str] = &["lookup", "count", "notify"]; - -#[doc(hidden)] -pub struct ServiceDispatcher(pub S); - -impl Dispatch for ServiceDispatcher { - fn calls(&self) -> &'static [&'static str] { - SERVICE_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(SERVICE_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ServiceLookupParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.lookup(peer, p.id) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(ServiceLookupError::NotFound(e))) => { - let mut body = Vec::new(); - peer.format().encode(&e, &mut body)?; - reply.err(0u16, &body); - } - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.count(peer) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 2 => { - let p: ServiceNotifyParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => return Ok(()), - }; - self.0.notify(peer, p.code); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ServiceDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Service` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ServiceSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ServiceSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn lookup(&mut self, id: i32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "lookup"), &ServiceLookupParams { id })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id: 0u16, body } => { - let e: NotFound = fmt.decode(body)?; - Err(CallError::App(ServiceLookupError::NotFound(e))) - } - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn count(&mut self) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "count"), &())?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn notify(&mut self, code: u16) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(2, "notify"), &ServiceNotifyParams { code }) - } -} - diff --git a/conformance/tests/golden/format_json/rust/connection.rs b/conformance/tests/golden/format_json/rust/connection.rs deleted file mode 100644 index 327827b..0000000 --- a/conformance/tests/golden/format_json/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Service`. -//! - Serve with [`serve`]`(transport, Services { service: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `ServiceSender::new(&mut conn).lookup(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Json; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub service: Service, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ServiceDispatcher(self.service).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/format_json/typescript/conformance.ts b/conformance/tests/golden/format_json/typescript/conformance.ts deleted file mode 100644 index cd34d80..0000000 --- a/conformance/tests/golden/format_json/typescript/conformance.ts +++ /dev/null @@ -1,161 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x8ee00745c73a32b2n; - -export interface Record { - id: number; - name: string; -} - -export const RecordLayout: Layout = { struct: [["id", "s32"], ["name", "string"]] }; - -export interface NotFound { -} - -export const NotFoundLayout: Layout = { struct: [] }; - -export class NotFoundError extends Error { - static readonly ordinal = 0; - readonly data: NotFound; - constructor(data: NotFound) { - super("NotFound"); - this.data = data; - this.name = "NotFoundError"; - } -} - -export interface ServiceLookupParams { - id: number; -} - -/** @internal */ -export const ServiceLookupParamsLayout: Layout = { struct: [["id", "s32"]] }; - -export interface ServiceNotifyParams { - code: number; -} - -/** @internal */ -export const ServiceNotifyParamsLayout: Layout = { struct: [["code", "u16"]] }; - -export interface Service { - /** @throws {NotFoundError} */ - lookup(peer: Peer, params: ServiceLookupParams): Promise; - count(peer: Peer): Promise; - notify(peer: Peer, params: ServiceNotifyParams): Promise; -} - -/** @internal */ -export const SERVICE_CALLS = ["lookup", "count", "notify"] as const; - -/** @internal */ -export class ServiceDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Service; - - constructor(impl: Service) { - this.impl = impl; - } - - calls(): readonly string[] { - return SERVICE_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, SERVICE_CALLS)) { - case 0: { - try { - const p = codec.decode(params, ServiceLookupParamsLayout); - reply.ok(codec.encode((await this.impl.lookup(peer, p)) ?? null, RecordLayout)); - } catch (e) { - if (e instanceof NotFoundError) { reply.err(NotFoundError.ordinal, codec.encode(e.data, NotFoundLayout)); return; } - reply.fault(); - } - return; - } - case 1: { - try { - reply.ok(codec.encode((await this.impl.count(peer)) ?? null, "u64")); - } catch { - reply.fault(); - } - return; - } - case 2: { - try { - const p = codec.decode(params, ServiceNotifyParamsLayout); - await this.impl.notify(peer, p); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ServiceDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Service` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ServiceSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async lookup(params: ServiceLookupParams): Promise { - const env = await this.peer.call(ServiceSender.PROTOCOL, { id: 0, name: "lookup" }, params, { layout: ServiceLookupParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, RecordLayout); - if ("fault" in env) throw RuntimeError.provider(); - switch (env.err.id) { - case NotFoundError.ordinal: - throw new NotFoundError(this.peer.codec.decode(env.err.body, NotFoundLayout)); - default: - throw RuntimeError.remote(env.err.id); - } - } - - async count(): Promise { - const env = await this.peer.call(ServiceSender.PROTOCOL, { id: 1, name: "count" }, null, { layout: "unit" }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u64"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async notify(params: ServiceNotifyParams): Promise { - await this.peer.notify(ServiceSender.PROTOCOL, { id: 2, name: "notify" }, params, { layout: ServiceNotifyParamsLayout }); - } -} - diff --git a/conformance/tests/golden/format_json/typescript/connection.ts b/conformance/tests/golden/format_json/typescript/connection.ts deleted file mode 100644 index 1a1cedb..0000000 --- a/conformance/tests/golden/format_json/typescript/connection.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Service` (in `./conformance.js`). - * - Serve with `serve(transport, { service })`; `accept(transport, { service })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new ServiceSender(conn).lookup(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - service: ns_conformance.Service; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - return conn; -} diff --git a/conformance/tests/golden/format_json/typescript/wire.ts b/conformance/tests/golden/format_json/typescript/wire.ts deleted file mode 100644 index 409baeb..0000000 --- a/conformance/tests/golden/format_json/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - JsonCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new JsonCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x8ee00745c73a32b2n; diff --git a/conformance/tests/golden/format_msgpack/rust/conformance.rs b/conformance/tests/golden/format_msgpack/rust/conformance.rs deleted file mode 100644 index ace4801..0000000 --- a/conformance/tests/golden/format_msgpack/rust/conformance.rs +++ /dev/null @@ -1,237 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x8ee00745c73a32b2; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Record { - pub id: i32, - pub name: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct NotFound { -} - -impl core::fmt::Display for NotFound { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("NotFound occurred") - } -} - -impl core::error::Error for NotFound {} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceLookupParams { - pub id: i32, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceNotifyParams { - pub code: u16, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceLookupError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceLookupError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceLookupError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceLookupError {} - -pub type ServiceCountError = ::core::convert::Infallible; - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceError {} - -impl From for ServiceError { - fn from(e: ServiceLookupError) -> Self { - match e { - ServiceLookupError::NotFound(x) => ServiceError::NotFound(x), - } - } -} - -pub trait Service { - fn lookup(&self, peer: &mut impl Peer, id: i32) -> Result>; - fn count(&self, peer: &mut impl Peer) -> Result>; - fn notify(&self, peer: &mut impl Peer, code: u16); -} - -#[doc(hidden)] -pub const SERVICE_CALLS: &[&str] = &["lookup", "count", "notify"]; - -#[doc(hidden)] -pub struct ServiceDispatcher(pub S); - -impl Dispatch for ServiceDispatcher { - fn calls(&self) -> &'static [&'static str] { - SERVICE_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(SERVICE_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ServiceLookupParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.lookup(peer, p.id) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(ServiceLookupError::NotFound(e))) => { - let mut body = Vec::new(); - peer.format().encode(&e, &mut body)?; - reply.err(0u16, &body); - } - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.count(peer) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 2 => { - let p: ServiceNotifyParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => return Ok(()), - }; - self.0.notify(peer, p.code); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ServiceDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Service` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ServiceSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ServiceSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn lookup(&mut self, id: i32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "lookup"), &ServiceLookupParams { id })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id: 0u16, body } => { - let e: NotFound = fmt.decode(body)?; - Err(CallError::App(ServiceLookupError::NotFound(e))) - } - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn count(&mut self) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "count"), &())?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn notify(&mut self, code: u16) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(2, "notify"), &ServiceNotifyParams { code }) - } -} - diff --git a/conformance/tests/golden/format_msgpack/rust/connection.rs b/conformance/tests/golden/format_msgpack/rust/connection.rs deleted file mode 100644 index 9c2f825..0000000 --- a/conformance/tests/golden/format_msgpack/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Service`. -//! - Serve with [`serve`]`(transport, Services { service: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `ServiceSender::new(&mut conn).lookup(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::MsgPack; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub service: Service, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ServiceDispatcher(self.service).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/framing_datagram3/rust/conformance.rs b/conformance/tests/golden/framing_datagram3/rust/conformance.rs deleted file mode 100644 index 3094b8a..0000000 --- a/conformance/tests/golden/framing_datagram3/rust/conformance.rs +++ /dev/null @@ -1,144 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xbb9f4216f7365478; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CounterAddParams { - pub n: u32, -} - -pub type CounterAddError = ::core::convert::Infallible; - -pub type CounterError = ::core::convert::Infallible; - -pub trait Counter { - fn add(&self, peer: &mut impl Peer, n: u32) -> Result>; - fn reset(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const COUNTER_CALLS: &[&str] = &["add", "reset"]; - -#[doc(hidden)] -pub struct CounterDispatcher(pub S); - -impl Dispatch for CounterDispatcher { - fn calls(&self) -> &'static [&'static str] { - COUNTER_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 1 => { - let p: CounterAddParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.add(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 0 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.reset(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl CounterDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept_with(transport, format, comline_runtime::contract::Datagram3Framing, &mut ComlineHandshake, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Counter` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct CounterSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> CounterSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn add(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "add"), &CounterAddParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn reset(&mut self) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(0, "reset"), &()) - } -} - diff --git a/conformance/tests/golden/framing_datagram3/rust/connection.rs b/conformance/tests/golden/framing_datagram3/rust/connection.rs deleted file mode 100644 index a73dbda..0000000 --- a/conformance/tests/golden/framing_datagram3/rust/connection.rs +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@3` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Counter`. -//! - Serve with [`serve`]`(transport, Services { counter: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `CounterSender::new(&mut conn).add(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xbb9f4216f7365478; - -/// The framing the package's connection runs on (`datagram@3`). -pub type Framing = comline_runtime::contract::Datagram3Framing; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub counter: Counter, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::CounterDispatcher(self.counter).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut comline_runtime::handshake::ComlineHandshake, CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/framing_datagram3/typescript/conformance.ts b/conformance/tests/golden/framing_datagram3/typescript/conformance.ts deleted file mode 100644 index 88ac190..0000000 --- a/conformance/tests/golden/framing_datagram3/typescript/conformance.ts +++ /dev/null @@ -1,108 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xbb9f4216f7365478n; - -export interface CounterAddParams { - n: number; -} - -/** @internal */ -export const CounterAddParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Counter { - add(peer: Peer, params: CounterAddParams): Promise; - reset(peer: Peer): Promise; -} - -/** @internal */ -export const COUNTER_CALLS = ["add", "reset"] as const; - -/** @internal */ -export class CounterDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Counter; - - constructor(impl: Counter) { - this.impl = impl; - } - - calls(): readonly string[] { - return COUNTER_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 1: { - try { - const p = codec.decode(params, CounterAddParamsLayout); - reply.ok(codec.encode((await this.impl.add(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - case 0: { - try { - await this.impl.reset(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(CounterDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Counter` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class CounterSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async add(params: CounterAddParams): Promise { - const env = await this.peer.call(CounterSender.PROTOCOL, { id: 1, name: "add" }, params, { layout: CounterAddParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async reset(): Promise { - await this.peer.notify(CounterSender.PROTOCOL, { id: 0, name: "reset" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/framing_datagram3/typescript/connection.ts b/conformance/tests/golden/framing_datagram3/typescript/connection.ts deleted file mode 100644 index 0d1f323..0000000 --- a/conformance/tests/golden/framing_datagram3/typescript/connection.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Counter` (in `./conformance.js`). - * - Serve with `serve(transport, { counter })`; `accept(transport, { counter })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new CounterSender(conn).add(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - Datagram3Framing, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - counter: ns_conformance.Counter; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.CounterDispatcher(services.counter).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing()); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing()); - return conn; -} diff --git a/conformance/tests/golden/framing_datagram3/typescript/wire.ts b/conformance/tests/golden/framing_datagram3/typescript/wire.ts deleted file mode 100644 index b536004..0000000 --- a/conformance/tests/golden/framing_datagram3/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xbb9f4216f7365478n; diff --git a/conformance/tests/golden/framing_jsonrpc/rust/conformance.rs b/conformance/tests/golden/framing_jsonrpc/rust/conformance.rs deleted file mode 100644 index 55c8e66..0000000 --- a/conformance/tests/golden/framing_jsonrpc/rust/conformance.rs +++ /dev/null @@ -1,121 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::client::Client; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::serve::Server; -use comline_runtime::transport::Transport; -use comline_runtime::format::Json; -use comline_runtime::framing::JsonRpcFraming; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x1a95418a1177cd91; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RpcPingParams { - pub n: u32, -} - -pub type RpcPingError = ::core::convert::Infallible; - -pub type RpcError = ::core::convert::Infallible; - -pub trait Rpc { - fn ping(&self, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const RPC_CALLS: &[&str] = &["ping"]; - -pub struct RpcDispatcher(pub S); - -impl Dispatch for RpcDispatcher { - fn calls(&self) -> &'static [&'static str] { - RPC_CALLS - } - - fn dispatch( - &self, - call: Kind, - params: &[u8], - fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - match call.resolve(RPC_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: RpcPingParams = match fmt.decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.ping(p.n) { - Ok(value) => { - let mut body = Vec::new(); - fmt.encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl RpcDispatcher { - /// Serve this protocol over `transport`, running the connection - /// handshake (`IR_HASH` + `format`'s and the framing's names) against - /// the peer first. - /// Encodes with `Json`. - pub fn serve(self, transport: &mut T) -> Result<(), RuntimeError> { - self.serve_with_format(transport, Json::default()) - } - - /// [`serve`](Self::serve), encoding with `format` instead. - pub fn serve_with_format(self, transport: &mut T, format: W) - -> Result<(), RuntimeError> { - let framing = JsonRpcFraming; - Server::with_framing(self, format, framing).serve(transport, IR_HASH) - } -} - -pub struct RpcClient(pub Client); - -impl RpcClient { - pub fn new(client: Client) -> Self { - Self(client) - } - - /// Bind + run the connection handshake against the provider. - /// [`connect`](Self::connect), encoding with `format`. - pub fn connect_with_format(transport: T, format: W) -> Result { - let framing = JsonRpcFraming; - Ok(Self(Client::connect_with_framing(transport, format, framing, IR_HASH)?)) - } - - pub fn ping(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Call::new(0, "ping"), &RpcPingParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -impl RpcClient { - /// Bind + run the connection handshake against the provider. - /// Encodes with `Json`. - pub fn connect(transport: T) -> Result { - Self::connect_with_format(transport, Json::default()) - } -} - diff --git a/conformance/tests/golden/framing_jsonrpc/typescript/conformance.ts b/conformance/tests/golden/framing_jsonrpc/typescript/conformance.ts deleted file mode 100644 index 5fb7fe1..0000000 --- a/conformance/tests/golden/framing_jsonrpc/typescript/conformance.ts +++ /dev/null @@ -1,88 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - Client, - Server, - RuntimeError, - resolveKind, - JsonRpcFraming, - JsonCodec, - type Codec, - type Dispatch, - type Framing, - type Kind, - type Layout, - type Reply, - type Transport, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x1a95418a1177cd91n; - -export interface RpcPingParams { - n: number; -} - -/** @internal */ -export const RpcPingParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Rpc { - ping(params: RpcPingParams): Promise; -} - -/** @internal */ -export const RPC_CALLS = ["ping"] as const; - -export class RpcDispatcher implements Dispatch { - private readonly impl: Rpc; - - constructor(impl: Rpc) { - this.impl = impl; - } - - calls(): readonly string[] { - return RPC_CALLS; - } - - async dispatch(call: Kind, params: Uint8Array, codec: Codec, reply: Reply): Promise { - switch (resolveKind(call, RPC_CALLS)) { - case 0: { - try { - const p = codec.decode(params, RpcPingParamsLayout); - reply.ok(codec.encode((await this.impl.ping(p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } -} - -export class RpcClient { - private readonly client: Client; - - constructor(client: Client) { - this.client = client; - } - - static async connect(transport: Transport, codec: Codec = new JsonCodec(), framing: Framing = new JsonRpcFraming()): Promise { - return new RpcClient(await Client.connect(transport, codec, IR_HASH, framing)); - } - - async ping(params: RpcPingParams): Promise { - const env = await this.client.call({ id: 0, name: "ping" }, params, { layout: RpcPingParamsLayout }); - if ("ok" in env) return this.client.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export function serveRpc(impl: Rpc, transport: Transport, codec: Codec = new JsonCodec(), framing: Framing = new JsonRpcFraming()): Promise { - return new Server(new RpcDispatcher(impl), codec, framing).serve(transport, IR_HASH); -} - diff --git a/conformance/tests/golden/handshake_comline2/rust/conformance.rs b/conformance/tests/golden/handshake_comline2/rust/conformance.rs deleted file mode 100644 index 81c80c2..0000000 --- a/conformance/tests/golden/handshake_comline2/rust/conformance.rs +++ /dev/null @@ -1,146 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x9328a48fb76a93df; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatSendParams { - pub text: u32, -} - -pub type ChatSendError = ::core::convert::Infallible; - -pub type ChatError = ::core::convert::Infallible; - -pub trait Chat { - fn send(&self, peer: &mut impl Peer, text: u32) -> Result>; - fn leave(&self, peer: &mut impl Peer); -} - -#[doc(hidden)] -pub const CHAT_CALLS: &[&str] = &["send", "leave"]; - -#[doc(hidden)] -pub struct ChatDispatcher(pub S); - -impl Dispatch for ChatDispatcher { - fn calls(&self) -> &'static [&'static str] { - CHAT_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 1 => { - let p: ChatSendParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send(peer, p.text) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 0 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => return Ok(()), - }; - self.0.leave(peer); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ChatDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Chat` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ChatSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ChatSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn send(&mut self, text: u32) -> Result> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::Chat", "send")?; - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "send"), &ChatSendParams { text })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn leave(&mut self) -> Result<(), RuntimeError> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Chat", "leave")?; - self.0.notify(Self::PROTOCOL, Call::new(0, "leave"), &()) - } -} - diff --git a/conformance/tests/golden/handshake_comline2/rust/connection.rs b/conformance/tests/golden/handshake_comline2/rust/connection.rs deleted file mode 100644 index 9971097..0000000 --- a/conformance/tests/golden/handshake_comline2/rust/connection.rs +++ /dev/null @@ -1,189 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Chat`. -//! - Serve with [`serve`]`(transport, Services { chat: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `ChatSender::new(&mut conn).send(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::{Peer, Reason, RuntimeError}; -use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated}; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x9328a48fb76a93df; - -/// The framing the package's connection runs on (`datagram@3`). -pub type Framing = comline_runtime::contract::Datagram3Framing; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its -/// history records it. Its protocols, by wire number: -/// -/// - 0 `conformance::Chat`, line 0.1.0: `send` 1, `leave` 0 -#[doc(hidden)] -pub const HELLO: &[u8] = &[ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x02, 0x00, 0x01, -]; - -/// The `comline@2` handshake, with [`HELLO`] and the parameters the package -/// states: `scope = protocol`, `newer_consumer = refuse`, `same_version_differs = refuse`, `exchange = offer`. -#[doc(hidden)] -pub fn handshake() -> Comline2Handshake { - use comline_runtime::handshake::comline2 as c2; - let hello = match c2::Message::decode(HELLO) { - Ok(c2::Message::Hello(hello)) => hello, - _ => unreachable!("HELLO is a Hello message"), - }; - let params = c2::Params { - scope: c2::Scope::Protocol, - newer_consumer: c2::NewerConsumer::Refuse, - same_version_differs: c2::SameVersionDiffers::Refuse, - exchange: c2::Exchange::Offer, - }; - c2::Comline2Handshake::new(params, hello) -} - -/// The package's protocols on the connection, by wire number. -const PROTOCOLS: &[(u16, &str)] = &[(0, "conformance::Chat")]; - -fn protocol_path(number: u16) -> &'static str { - PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path) -} - -/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in -/// the connection's extensions. -#[derive(Debug, Clone)] -pub struct Negotiation { - pub negotiated: Negotiated, - /// The last call that wasn't made because the peer can't take it. - pub unavailable: Option, -} - -/// A call that wasn't sent because the peer can't take it: which, and why. -/// The call itself fails with `RuntimeError::Unavailable`, which carries no -/// detail; [`unavailable`] gives this. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Unavailable { - /// `namespace::Protocol`. - pub protocol: &'static str, - pub function: &'static str, - /// Why the peer refused the protocol, or `None` when the peer lacks the - /// function (`newer_consumer = degrade`). - pub refused: Option, -} - -impl ::core::fmt::Display for Unavailable { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - match self.refused { - Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol), - None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function), - } - } -} - -impl ::core::error::Error for Unavailable {} - -/// What the connection's `comline@2` handshake agreed, if `accept` / `connect` -/// opened it. -pub fn negotiated(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().map(|n| n.negotiated.clone()) -} - -/// The protocols that connected although their wire shape differs from the -/// peer's at the same version (`same_version_differs = warn`), by path. -pub fn warnings(peer: &mut P) -> Vec<&'static str> { - let extensions = peer.extensions(); - match extensions.get::() { - Some(n) => n.negotiated.warnings.iter().map(|p| protocol_path(*p)).collect(), - None => Vec::new(), - } -} - -/// The last call on this connection that failed with `Unavailable`: which -/// function, and why. -pub fn unavailable(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().and_then(|n| n.unavailable) -} - -/// Whether `function` of `protocol` may be called: what each sender runs -/// before it writes a request. A connection opened some other way than -/// `accept` / `connect` has nothing to check against, and every call goes. -#[doc(hidden)] -pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'static str, name: &'static str) -> Result<(), RuntimeError> { - let extensions = peer.extensions(); - let Some(n) = extensions.get_mut::() else { - return Ok(()); - }; - let error = match n.negotiated.check_call(protocol, function) { - Ok(()) => return Ok(()), - Err(error) => error, - }; - let refused = n.negotiated.protocols.iter().find(|p| p.number == protocol).and_then(|p| match p.state { - comline_runtime::handshake::comline2::ProtocolState::Refused { reason } => Some(reason), - _ => None, - }); - // A protocol this end doesn't have isn't refused by the peer: it's unknown. - let refused = refused.or_else(|| (!n.negotiated.protocols.iter().any(|p| p.number == protocol)).then_some(Reason::UnknownProtocol)); - n.unavailable = Some(Unavailable { protocol: path, function: name, refused }); - Err(error) -} - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub chat: Chat, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ChatDispatcher(self.chat).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - Ok(conn) -} diff --git a/conformance/tests/golden/handshake_comline2/typescript/conformance.ts b/conformance/tests/golden/handshake_comline2/typescript/conformance.ts deleted file mode 100644 index cd8ba98..0000000 --- a/conformance/tests/golden/handshake_comline2/typescript/conformance.ts +++ /dev/null @@ -1,111 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - checkCall, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x9328a48fb76a93dfn; - -export interface ChatSendParams { - text: number; -} - -/** @internal */ -export const ChatSendParamsLayout: Layout = { struct: [["text", "u32"]] }; - -export interface Chat { - send(peer: Peer, params: ChatSendParams): Promise; - leave(peer: Peer): Promise; -} - -/** @internal */ -export const CHAT_CALLS = ["send", "leave"] as const; - -/** @internal */ -export class ChatDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Chat; - - constructor(impl: Chat) { - this.impl = impl; - } - - calls(): readonly string[] { - return CHAT_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 1: { - try { - const p = codec.decode(params, ChatSendParamsLayout); - reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - case 0: { - try { - await this.impl.leave(peer); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ChatDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ChatSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async send(params: ChatSendParams): Promise { - checkCall(this.peer, ChatSender.PROTOCOL, 1, "conformance::Chat", "send"); - const env = await this.peer.call(ChatSender.PROTOCOL, { id: 1, name: "send" }, params, { layout: ChatSendParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async leave(): Promise { - checkCall(this.peer, ChatSender.PROTOCOL, 0, "conformance::Chat", "leave"); - await this.peer.notify(ChatSender.PROTOCOL, { id: 0, name: "leave" }, null, { layout: "unit" }); - } -} - diff --git a/conformance/tests/golden/handshake_comline2/typescript/connection.ts b/conformance/tests/golden/handshake_comline2/typescript/connection.ts deleted file mode 100644 index 23e9a02..0000000 --- a/conformance/tests/golden/handshake_comline2/typescript/connection.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Chat` (in `./conformance.js`). - * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - Datagram3Framing, - Comline2Handshake, - Negotiated, - type Peer, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `conformance::Chat`, line 0.1.0: `send` 1, `leave` 0 - * - * @internal - */ -export const HELLO = new Uint8Array([ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x02, 0x00, 0x01, -]); - -/** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. - * @internal - */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { - scope: "protocol", - newerConsumer: "refuse", - sameVersionDiffers: "refuse", - exchange: "offer", - }); -} - -/** The package's protocols on the connection, by wire number. */ -const PROTOCOLS = new Map([[0, "conformance::Chat"]]); - -/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ -export function negotiated(conn: Peer): Negotiated | undefined { - return conn.extensions.get(Negotiated); -} - -/** - * The protocols that connected although their wire shape differs from the - * peer's at the same version (`same_version_differs = warn`), by path. - */ -export function warnings(conn: Peer): string[] { - return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); -} - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - chat: ns_conformance.Chat; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const agreed = handshake(); - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - return conn; -} diff --git a/conformance/tests/golden/handshake_comline2/typescript/wire.ts b/conformance/tests/golden/handshake_comline2/typescript/wire.ts deleted file mode 100644 index d24e55e..0000000 --- a/conformance/tests/golden/handshake_comline2/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x9328a48fb76a93dfn; diff --git a/conformance/tests/golden/handshake_none/rust/conformance.rs b/conformance/tests/golden/handshake_none/rust/conformance.rs deleted file mode 100644 index 7eb2cb6..0000000 --- a/conformance/tests/golden/handshake_none/rust/conformance.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xb7e7d5c80c4d8287; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GatewayPingParams { - pub n: u32, -} - -pub type GatewayPingError = ::core::convert::Infallible; - -pub type GatewayError = ::core::convert::Infallible; - -pub trait Gateway { - fn ping(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const GATEWAY_CALLS: &[&str] = &["ping"]; - -/// **Unverified:** gives up schema agreement and encoding agreement. -/// Reason given: the gateway predates Comline -#[doc(hidden)] -pub struct GatewayDispatcher(pub S); - -impl Dispatch for GatewayDispatcher { - fn calls(&self) -> &'static [&'static str] { - GATEWAY_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(GATEWAY_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: GatewayPingParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.ping(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl GatewayDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept_with` and `NoHandshake` (`@handshake = "none"`), or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// **Unverified:** gives up schema agreement and encoding agreement. -/// Reason given: the gateway predates Comline -/// Calls protocol `Gateway` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct GatewaySender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> GatewaySender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn ping(&mut self, n: u32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "ping"), &GatewayPingParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/handshake_none/rust/connection.rs b/conformance/tests/golden/handshake_none/rust/connection.rs deleted file mode 100644 index 641f30c..0000000 --- a/conformance/tests/golden/handshake_none/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `none` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Gateway`. -//! - Serve with [`serve`]`(transport, Services { gateway: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `GatewaySender::new(&mut conn).ping(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xb7e7d5c80c4d8287; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub gateway: Gateway, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::GatewayDispatcher(self.gateway).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::new_unverified(transport, Format::default()); - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::new_unverified(transport, Format::default()); - Ok(conn) -} diff --git a/conformance/tests/golden/handshake_none/typescript/conformance.ts b/conformance/tests/golden/handshake_none/typescript/conformance.ts deleted file mode 100644 index a76c689..0000000 --- a/conformance/tests/golden/handshake_none/typescript/conformance.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xb7e7d5c80c4d8287n; - -export interface GatewayPingParams { - n: number; -} - -/** @internal */ -export const GatewayPingParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Gateway { - ping(peer: Peer, params: GatewayPingParams): Promise; -} - -/** @internal */ -export const GATEWAY_CALLS = ["ping"] as const; - -/** - * **Unverified:** gives up schema agreement and encoding agreement. - * Reason given: the gateway predates Comline - * - * @internal - */ -export class GatewayDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Gateway; - - constructor(impl: Gateway) { - this.impl = impl; - } - - calls(): readonly string[] { - return GATEWAY_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, GATEWAY_CALLS)) { - case 0: { - try { - const p = codec.decode(params, GatewayPingParamsLayout); - reply.ok(codec.encode((await this.impl.ping(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, framing, new NoHandshake())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(GatewayDispatcher.PROTOCOL, this); - } -} - -/** - * **Unverified:** gives up schema agreement and encoding agreement. - * Reason given: the gateway predates Comline - */ -/** Calls protocol `Gateway` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class GatewaySender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async ping(params: GatewayPingParams): Promise { - const env = await this.peer.call(GatewaySender.PROTOCOL, { id: 0, name: "ping" }, params, { layout: GatewayPingParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/handshake_none/typescript/connection.ts b/conformance/tests/golden/handshake_none/typescript/connection.ts deleted file mode 100644 index 91d1b57..0000000 --- a/conformance/tests/golden/handshake_none/typescript/connection.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Gateway` (in `./conformance.js`). - * - Serve with `serve(transport, { gateway })`; `accept(transport, { gateway })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new GatewaySender(conn).ping(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - NoHandshake, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - gateway: ns_conformance.Gateway; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.GatewayDispatcher(services.gateway).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new NoHandshake()); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, undefined, new NoHandshake()); - return conn; -} diff --git a/conformance/tests/golden/handshake_none/typescript/wire.ts b/conformance/tests/golden/handshake_none/typescript/wire.ts deleted file mode 100644 index 1290676..0000000 --- a/conformance/tests/golden/handshake_none/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xb7e7d5c80c4d8287n; diff --git a/conformance/tests/golden/import_alias/rust/api.rs b/conformance/tests/golden/import_alias/rust/api.rs deleted file mode 100644 index 5311a62..0000000 --- a/conformance/tests/golden/import_alias/rust/api.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Holder { - pub one: crate::shared::Shared, -} - diff --git a/conformance/tests/golden/import_alias/rust/shared.rs b/conformance/tests/golden/import_alias/rust/shared.rs deleted file mode 100644 index 598eca1..0000000 --- a/conformance/tests/golden/import_alias/rust/shared.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Shared { - pub value: i32, -} - diff --git a/conformance/tests/golden/import_alias/typescript/api.ts b/conformance/tests/golden/import_alias/typescript/api.ts deleted file mode 100644 index 89f4948..0000000 --- a/conformance/tests/golden/import_alias/typescript/api.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { SharedLayout as AliasedLayout } from "./shared.js"; -import type { Shared as Aliased } from "./shared.js"; - -export interface Holder { - one: Aliased; -} - -export const HolderLayout: Layout = { struct: [["one", () => AliasedLayout]] }; - diff --git a/conformance/tests/golden/import_alias/typescript/shared.ts b/conformance/tests/golden/import_alias/typescript/shared.ts deleted file mode 100644 index 362c34d..0000000 --- a/conformance/tests/golden/import_alias/typescript/shared.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Shared { - value: number; -} - -export const SharedLayout: Layout = { struct: [["value", "s32"]] }; - diff --git a/conformance/tests/golden/import_glob/rust/api.rs b/conformance/tests/golden/import_glob/rust/api.rs deleted file mode 100644 index 5311a62..0000000 --- a/conformance/tests/golden/import_glob/rust/api.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Holder { - pub one: crate::shared::Shared, -} - diff --git a/conformance/tests/golden/import_glob/rust/shared.rs b/conformance/tests/golden/import_glob/rust/shared.rs deleted file mode 100644 index 3d5c083..0000000 --- a/conformance/tests/golden/import_glob/rust/shared.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Shared { - pub value: i32, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Unused { - pub ignored: bool, -} - diff --git a/conformance/tests/golden/import_glob/typescript/api.ts b/conformance/tests/golden/import_glob/typescript/api.ts deleted file mode 100644 index 356d131..0000000 --- a/conformance/tests/golden/import_glob/typescript/api.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { SharedLayout } from "./shared.js"; -import type { Shared } from "./shared.js"; - -export interface Holder { - one: Shared; -} - -export const HolderLayout: Layout = { struct: [["one", () => SharedLayout]] }; - diff --git a/conformance/tests/golden/import_glob/typescript/shared.ts b/conformance/tests/golden/import_glob/typescript/shared.ts deleted file mode 100644 index f5efa1f..0000000 --- a/conformance/tests/golden/import_glob/typescript/shared.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Shared { - value: number; -} - -export const SharedLayout: Layout = { struct: [["value", "s32"]] }; - -export interface Unused { - ignored: boolean; -} - -export const UnusedLayout: Layout = { struct: [["ignored", "bool"]] }; - diff --git a/conformance/tests/golden/large_fixed_arrays_nested/typescript/conformance.ts b/conformance/tests/golden/large_fixed_arrays_nested/typescript/conformance.ts deleted file mode 100644 index f3147b8..0000000 --- a/conformance/tests/golden/large_fixed_arrays_nested/typescript/conformance.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Blocks { - maybe?: number[]; - many: number[][]; -} - -export const BlocksLayout: Layout = { struct: [["maybe", { option: { fixed: "u8", length: 64 } }], ["many", { array: { fixed: "u8", length: 64 } }]] }; - diff --git a/conformance/tests/golden/lockstep/rust/conformance.rs b/conformance/tests/golden/lockstep/rust/conformance.rs deleted file mode 100644 index c66f197..0000000 --- a/conformance/tests/golden/lockstep/rust/conformance.rs +++ /dev/null @@ -1,211 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::client::Client; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::serve::Server; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x7ea94b595fcf4393; - -/// The package's wire format (`wire.format`): what this file's helpers -/// encode with, and what the peer has to speak too. -pub type Format = comline_runtime::format::Packed; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Message { - pub body: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct RecipientNotFound { -} - -impl core::fmt::Display for RecipientNotFound { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("RecipientNotFound occurred") - } -} - -impl core::error::Error for RecipientNotFound {} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct MailSendMessageParams { - pub message: Message, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum MailSendMessageError { - RecipientNotFound(RecipientNotFound), -} - -impl core::fmt::Display for MailSendMessageError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - MailSendMessageError::RecipientNotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for MailSendMessageError {} - -pub type MailFetchInboxError = ::core::convert::Infallible; - -#[derive(Debug, Clone, PartialEq)] -pub enum MailError { - RecipientNotFound(RecipientNotFound), -} - -impl core::fmt::Display for MailError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - MailError::RecipientNotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for MailError {} - -impl From for MailError { - fn from(e: MailSendMessageError) -> Self { - match e { - MailSendMessageError::RecipientNotFound(x) => MailError::RecipientNotFound(x), - } - } -} - -pub trait Mail { - fn send_message(&self, message: Message) -> Result>; - fn fetch_inbox(&self) -> Result, Fault>; -} - -#[doc(hidden)] -pub const MAIL_CALLS: &[&str] = &["send_message", "fetch_inbox"]; - -pub struct MailDispatcher(pub S); - -impl Dispatch for MailDispatcher { - fn calls(&self) -> &'static [&'static str] { - MAIL_CALLS - } - - fn dispatch( - &self, - call: Kind, - params: &[u8], - fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - match call.resolve(MAIL_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: MailSendMessageParams = match fmt.decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.send_message(p.message) { - Ok(value) => { - let mut body = Vec::new(); - fmt.encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(MailSendMessageError::RecipientNotFound(e))) => { - let mut body = Vec::new(); - fmt.encode(&e, &mut body)?; - reply.err(0u16, &body); - } - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match fmt.decode(params) { - Ok(unit) => unit, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.fetch_inbox() { - Ok(value) => { - let mut body = Vec::new(); - fmt.encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl MailDispatcher { - /// Serve this protocol over `transport`, running the connection - /// handshake (`IR_HASH` + `format`'s and the framing's names) against - /// the peer first. - /// Encodes with `Format`. - pub fn serve(self, transport: &mut T) -> Result<(), RuntimeError> { - self.serve_with_format(transport, Format::default()) - } - - /// [`serve`](Self::serve), encoding with `format` instead. - pub fn serve_with_format(self, transport: &mut T, format: W) - -> Result<(), RuntimeError> { - Server::new(self, format).serve(transport, IR_HASH) - } -} - -pub struct MailClient(pub Client); - -impl MailClient { - pub fn new(client: Client) -> Self { - Self(client) - } - - /// Bind + run the connection handshake against the provider. - /// [`connect`](Self::connect), encoding with `format`. - pub fn connect_with_format(transport: T, format: W) -> Result { - Ok(Self(Client::connect(transport, format, IR_HASH)?)) - } - - pub fn send_message(&mut self, message: Message) -> Result> { - let (reply, fmt) = self.0.call_with_timeout(Call::new(0, "send_message"), &MailSendMessageParams { message }, core::time::Duration::from_millis(1000))?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id: 0u16, body } => { - let e: RecipientNotFound = fmt.decode(body)?; - Err(CallError::App(MailSendMessageError::RecipientNotFound(e))) - } - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn fetch_inbox(&mut self) -> Result, CallError> { - let (reply, fmt) = self.0.call(Call::new(1, "fetch_inbox"), &())?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - -impl MailClient { - /// Bind + run the connection handshake against the provider. - /// Encodes with `Format`. - pub fn connect(transport: T) -> Result { - Self::connect_with_format(transport, Format::default()) - } -} - diff --git a/conformance/tests/golden/lockstep/typescript/conformance.ts b/conformance/tests/golden/lockstep/typescript/conformance.ts deleted file mode 100644 index e180ea8..0000000 --- a/conformance/tests/golden/lockstep/typescript/conformance.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - Client, - Server, - RuntimeError, - resolveKind, - DatagramFraming, - PackedCodec, - type Codec, - type Dispatch, - type Framing, - type Kind, - type Layout, - type Reply, - type Transport, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x7ea94b595fcf4393n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - -export interface Message { - body: string; -} - -export const MessageLayout: Layout = { struct: [["body", "string"]] }; - -export interface RecipientNotFound { -} - -export const RecipientNotFoundLayout: Layout = { struct: [] }; - -export class RecipientNotFoundError extends Error { - static readonly ordinal = 0; - readonly data: RecipientNotFound; - constructor(data: RecipientNotFound) { - super("RecipientNotFound"); - this.data = data; - this.name = "RecipientNotFoundError"; - } -} - -export interface MailSendMessageParams { - message: Message; -} - -/** @internal */ -export const MailSendMessageParamsLayout: Layout = { struct: [["message", () => MessageLayout]] }; - -export interface Mail { - /** @throws {RecipientNotFoundError} */ - send_message(params: MailSendMessageParams): Promise; - fetch_inbox(): Promise; -} - -/** @internal */ -export const MAIL_CALLS = ["send_message", "fetch_inbox"] as const; - -export class MailDispatcher implements Dispatch { - private readonly impl: Mail; - - constructor(impl: Mail) { - this.impl = impl; - } - - calls(): readonly string[] { - return MAIL_CALLS; - } - - async dispatch(call: Kind, params: Uint8Array, codec: Codec, reply: Reply): Promise { - switch (resolveKind(call, MAIL_CALLS)) { - case 0: { - try { - const p = codec.decode(params, MailSendMessageParamsLayout); - reply.ok(codec.encode((await this.impl.send_message(p)) ?? null, "string")); - } catch (e) { - if (e instanceof RecipientNotFoundError) { reply.err(RecipientNotFoundError.ordinal, codec.encode(e.data, RecipientNotFoundLayout)); return; } - reply.fault(); - } - return; - } - case 1: { - try { - reply.ok(codec.encode((await this.impl.fetch_inbox()) ?? null, { array: MessageLayout })); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } -} - -export class MailClient { - private readonly client: Client; - - constructor(client: Client) { - this.client = client; - } - - static async connect(transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { - return new MailClient(await Client.connect(transport, codec, IR_HASH, framing)); - } - - async send_message(params: MailSendMessageParams): Promise { - const env = await this.client.call({ id: 0, name: "send_message" }, params, { layout: MailSendMessageParamsLayout }); - if ("ok" in env) return this.client.codec.decode(env.ok, "string"); - if ("fault" in env) throw RuntimeError.provider(); - switch (env.err.id) { - case RecipientNotFoundError.ordinal: - throw new RecipientNotFoundError(this.client.codec.decode(env.err.body, RecipientNotFoundLayout)); - default: - throw RuntimeError.remote(env.err.id); - } - } - - async fetch_inbox(): Promise { - const env = await this.client.call({ id: 1, name: "fetch_inbox" }, null, { layout: "unit" }); - if ("ok" in env) return this.client.codec.decode(env.ok, { array: MessageLayout }); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - -export function serveMail(impl: Mail, transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { - return new Server(new MailDispatcher(impl), codec, framing).serve(transport, IR_HASH); -} - diff --git a/conformance/tests/golden/nested_namespace/rust/Cargo.toml b/conformance/tests/golden/nested_namespace/rust/Cargo.toml deleted file mode 100644 index b71c780..0000000 --- a/conformance/tests/golden/nested_namespace/rust/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -# Generated by Comline -[package] -name = "conformance" -version = "0.0.0" -edition = "2024" -rust-version = "1.85.0" -# A schema namespace named `main` would otherwise be picked up as a -# binary target (`src/main.rs`) with no `fn main`. Core refuses that -# name outright now; this stays as a belt-and-braces guard for a -# `GenRequest` built by hand. -autobins = false - -[dependencies] -serde = { version = "1", features = ["derive"] } diff --git a/conformance/tests/golden/nested_namespace/rust/src/group.rs b/conformance/tests/golden/nested_namespace/rust/src/group.rs deleted file mode 100644 index 72e282f..0000000 --- a/conformance/tests/golden/nested_namespace/rust/src/group.rs +++ /dev/null @@ -1,4 +0,0 @@ -// Generated by Comline - -pub mod first; -pub mod second; diff --git a/conformance/tests/golden/nested_namespace/rust/src/group/first.rs b/conformance/tests/golden/nested_namespace/rust/src/group/first.rs deleted file mode 100644 index 2dc4da7..0000000 --- a/conformance/tests/golden/nested_namespace/rust/src/group/first.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct First { - pub top: crate::top::Top, -} - diff --git a/conformance/tests/golden/nested_namespace/rust/src/group/second.rs b/conformance/tests/golden/nested_namespace/rust/src/group/second.rs deleted file mode 100644 index b744697..0000000 --- a/conformance/tests/golden/nested_namespace/rust/src/group/second.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Second { - pub first: crate::group::first::First, -} - diff --git a/conformance/tests/golden/nested_namespace/rust/src/lib.rs b/conformance/tests/golden/nested_namespace/rust/src/lib.rs deleted file mode 100644 index 76d0aa5..0000000 --- a/conformance/tests/golden/nested_namespace/rust/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Generated by Comline - -//! This package declares no protocols: it holds types, so there is nothing to serve or dial. - -pub mod group; -pub mod top; diff --git a/conformance/tests/golden/nested_namespace/rust/src/top.rs b/conformance/tests/golden/nested_namespace/rust/src/top.rs deleted file mode 100644 index 1e9bc11..0000000 --- a/conformance/tests/golden/nested_namespace/rust/src/top.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Top { - pub value: i32, -} - diff --git a/conformance/tests/golden/nested_namespace/typescript/package.json b/conformance/tests/golden/nested_namespace/typescript/package.json deleted file mode 100644 index f4e1629..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "conformance", - "version": "0.0.0", - "type": "module", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js" - }, - "./*": { - "types": "./dist/*.d.ts", - "import": "./dist/*.js" - } - }, - "files": ["dist", "src"], - "scripts": { - "build": "tsc" - }, - "peerDependencies": { - "@comline/runtime": "^0.1.0", - "typescript": ">=5.0" - }, - "peerDependenciesMeta": { - "@comline/runtime": { "optional": true }, - "typescript": { "optional": true } - }, - "devDependencies": { - "typescript": "^5.6.0" - } -} diff --git a/conformance/tests/golden/nested_namespace/typescript/src/group/first.ts b/conformance/tests/golden/nested_namespace/typescript/src/group/first.ts deleted file mode 100644 index 313b80f..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/src/group/first.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { TopLayout } from "../top.js"; -import type { Top } from "../top.js"; - -export interface First { - top: Top; -} - -export const FirstLayout: Layout = { struct: [["top", () => TopLayout]] }; - diff --git a/conformance/tests/golden/nested_namespace/typescript/src/group/index.ts b/conformance/tests/golden/nested_namespace/typescript/src/group/index.ts deleted file mode 100644 index bf825b8..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/src/group/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Generated by Comline - -export * as first from "./first.js"; -export * as second from "./second.js"; diff --git a/conformance/tests/golden/nested_namespace/typescript/src/group/second.ts b/conformance/tests/golden/nested_namespace/typescript/src/group/second.ts deleted file mode 100644 index 4206fcc..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/src/group/second.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -import { FirstLayout } from "./first.js"; -import type { First } from "./first.js"; - -export interface Second { - first: First; -} - -export const SecondLayout: Layout = { struct: [["first", () => FirstLayout]] }; - diff --git a/conformance/tests/golden/nested_namespace/typescript/src/index.ts b/conformance/tests/golden/nested_namespace/typescript/src/index.ts deleted file mode 100644 index 45db4ac..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Generated by Comline - -export * as group from "./group/index.js"; -export * as top from "./top.js"; diff --git a/conformance/tests/golden/nested_namespace/typescript/src/top.ts b/conformance/tests/golden/nested_namespace/typescript/src/top.ts deleted file mode 100644 index fb35d7a..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/src/top.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Top { - value: number; -} - -export const TopLayout: Layout = { struct: [["value", "s32"]] }; - diff --git a/conformance/tests/golden/nested_namespace/typescript/tsconfig.json b/conformance/tests/golden/nested_namespace/typescript/tsconfig.json deleted file mode 100644 index 931f802..0000000 --- a/conformance/tests/golden/nested_namespace/typescript/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "outDir": "dist", - "rootDir": "src", - "declaration": true, - "strict": true, - "exactOptionalPropertyTypes": true, - "noUncheckedIndexedAccess": true, - "verbatimModuleSyntax": true, - "skipLibCheck": true - }, - "include": ["src/**/*.ts"] -} diff --git a/conformance/tests/golden/nested_protocol/rust/chat/admin.rs b/conformance/tests/golden/nested_protocol/rust/chat/admin.rs deleted file mode 100644 index 7e3beac..0000000 --- a/conformance/tests/golden/nested_protocol/rust/chat/admin.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xa6f61afefe65d74a; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Notice { - pub text: String, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct AdminGreetParams { - pub n: u32, -} - -pub type AdminGreetError = ::core::convert::Infallible; - -pub type AdminError = ::core::convert::Infallible; - -pub trait Admin { - fn greet(&self, peer: &mut impl Peer, n: u32) -> Result>; -} - -#[doc(hidden)] -pub const ADMIN_CALLS: &[&str] = &["greet"]; - -#[doc(hidden)] -pub struct AdminDispatcher(pub S); - -impl Dispatch for AdminDispatcher { - fn calls(&self) -> &'static [&'static str] { - ADMIN_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - let number = match call { - Kind::Id(number) => number, - Kind::Named(_) => return Err(RuntimeError::UnknownCall), - }; - match number { - 0 => { - let p: AdminGreetParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.greet(peer, p.n) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl AdminDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with the package's `accept` / `serve` / `connect`, which run `comline@2` with this package's facts. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Admin` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct AdminSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> AdminSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn greet(&mut self, n: u32) -> Result> { - crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "chat::admin::Admin", "greet")?; - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "greet"), &AdminGreetParams { n })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/nested_protocol/rust/connection.rs b/conformance/tests/golden/nested_protocol/rust/connection.rs deleted file mode 100644 index 2e6af9c..0000000 --- a/conformance/tests/golden/nested_protocol/rust/connection.rs +++ /dev/null @@ -1,189 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@3` framing, the `comline@2` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `chat::admin::Admin`. -//! - Serve with [`serve`]`(transport, Services { admin: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `AdminSender::new(&mut conn).greet(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::{Peer, Reason, RuntimeError}; -use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated}; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xa6f61afefe65d74a; - -/// The framing the package's connection runs on (`datagram@3`). -pub type Framing = comline_runtime::contract::Datagram3Framing; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over [`Framing`]. -pub type Connection = comline_runtime::connection::Connection; - -/// This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its -/// history records it. Its protocols, by wire number: -/// -/// - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 -#[doc(hidden)] -pub const HELLO: &[u8] = &[ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, -]; - -/// The `comline@2` handshake, with [`HELLO`] and the parameters the package -/// states: `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. -#[doc(hidden)] -pub fn handshake() -> Comline2Handshake { - use comline_runtime::handshake::comline2 as c2; - let hello = match c2::Message::decode(HELLO) { - Ok(c2::Message::Hello(hello)) => hello, - _ => unreachable!("HELLO is a Hello message"), - }; - let params = c2::Params { - scope: c2::Scope::Protocol, - newer_consumer: c2::NewerConsumer::Degrade, - same_version_differs: c2::SameVersionDiffers::Refuse, - exchange: c2::Exchange::Offer, - }; - c2::Comline2Handshake::new(params, hello) -} - -/// The package's protocols on the connection, by wire number. -const PROTOCOLS: &[(u16, &str)] = &[(0, "chat::admin::Admin")]; - -fn protocol_path(number: u16) -> &'static str { - PROTOCOLS.iter().find(|(n, _)| *n == number).map_or("?", |(_, path)| path) -} - -/// What the `comline@2` handshake agreed, which `accept` / `connect` keep in -/// the connection's extensions. -#[derive(Debug, Clone)] -pub struct Negotiation { - pub negotiated: Negotiated, - /// The last call that wasn't made because the peer can't take it. - pub unavailable: Option, -} - -/// A call that wasn't sent because the peer can't take it: which, and why. -/// The call itself fails with `RuntimeError::Unavailable`, which carries no -/// detail; [`unavailable`] gives this. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Unavailable { - /// `namespace::Protocol`. - pub protocol: &'static str, - pub function: &'static str, - /// Why the peer refused the protocol, or `None` when the peer lacks the - /// function (`newer_consumer = degrade`). - pub refused: Option, -} - -impl ::core::fmt::Display for Unavailable { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - match self.refused { - Some(reason) => write!(f, "`{}.{}` wasn't called: the connection refused protocol `{}` ({reason})", self.protocol, self.function, self.protocol), - None => write!(f, "`{}.{}` wasn't called: the peer lacks it", self.protocol, self.function), - } - } -} - -impl ::core::error::Error for Unavailable {} - -/// What the connection's `comline@2` handshake agreed, if `accept` / `connect` -/// opened it. -pub fn negotiated(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().map(|n| n.negotiated.clone()) -} - -/// The protocols that connected although their wire shape differs from the -/// peer's at the same version (`same_version_differs = warn`), by path. -pub fn warnings(peer: &mut P) -> Vec<&'static str> { - let extensions = peer.extensions(); - match extensions.get::() { - Some(n) => n.negotiated.warnings.iter().map(|p| protocol_path(*p)).collect(), - None => Vec::new(), - } -} - -/// The last call on this connection that failed with `Unavailable`: which -/// function, and why. -pub fn unavailable(peer: &mut P) -> Option { - let extensions = peer.extensions(); - extensions.get::().and_then(|n| n.unavailable) -} - -/// Whether `function` of `protocol` may be called: what each sender runs -/// before it writes a request. A connection opened some other way than -/// `accept` / `connect` has nothing to check against, and every call goes. -#[doc(hidden)] -pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'static str, name: &'static str) -> Result<(), RuntimeError> { - let extensions = peer.extensions(); - let Some(n) = extensions.get_mut::() else { - return Ok(()); - }; - let error = match n.negotiated.check_call(protocol, function) { - Ok(()) => return Ok(()), - Err(error) => error, - }; - let refused = n.negotiated.protocols.iter().find(|p| p.number == protocol).and_then(|p| match p.state { - comline_runtime::handshake::comline2::ProtocolState::Refused { reason } => Some(reason), - _ => None, - }); - // A protocol this end doesn't have isn't refused by the peer: it's unknown. - let refused = refused.or_else(|| (!n.negotiated.protocols.iter().any(|p| p.number == protocol)).then_some(Reason::UnknownProtocol)); - n.unavailable = Some(Unavailable { protocol: path, function: name, refused }); - Err(error) -} - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub admin: Admin, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::chat::admin::AdminDispatcher(self.admin).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::accept_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let mut handshake = handshake(); - let mut conn = comline_runtime::connection::Connection::connect_with(transport, Format::default(), comline_runtime::contract::Datagram3Framing, &mut handshake, CONNECTION_IR_HASH)?; - Peer::extensions(&mut conn).insert(Negotiation { negotiated: handshake.negotiated().cloned().unwrap_or_else(|| unreachable!("a handshake that succeeded agreed something")), unavailable: None }); - Ok(conn) -} diff --git a/conformance/tests/golden/nested_protocol/typescript/chat/admin.ts b/conformance/tests/golden/nested_protocol/typescript/chat/admin.ts deleted file mode 100644 index 02baaeb..0000000 --- a/conformance/tests/golden/nested_protocol/typescript/chat/admin.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - checkCall, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xa6f61afefe65d74an; - -export interface Notice { - text: string; -} - -export const NoticeLayout: Layout = { struct: [["text", "string"]] }; - -export interface AdminGreetParams { - n: number; -} - -/** @internal */ -export const AdminGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; - -export interface Admin { - greet(peer: Peer, params: AdminGreetParams): Promise; -} - -/** @internal */ -export const ADMIN_CALLS = ["greet"] as const; - -/** @internal */ -export class AdminDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Admin; - - constructor(impl: Admin) { - this.impl = impl; - } - - calls(): readonly string[] { - return ADMIN_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch ("id" in call ? call.id : -1) { - case 0: { - try { - const p = codec.decode(params, AdminGreetParamsLayout); - reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(AdminDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Admin` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class AdminSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async greet(params: AdminGreetParams): Promise { - checkCall(this.peer, AdminSender.PROTOCOL, 0, "chat::admin::Admin", "greet"); - const env = await this.peer.call(AdminSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: AdminGreetParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/nested_protocol/typescript/connection.ts b/conformance/tests/golden/nested_protocol/typescript/connection.ts deleted file mode 100644 index 82a2972..0000000 --- a/conformance/tests/golden/nested_protocol/typescript/connection.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Admin` (in `./chat/admin.js`). - * - Serve with `serve(transport, { admin })`; `accept(transport, { admin })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new AdminSender(conn).greet(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - Datagram3Framing, - Comline2Handshake, - Negotiated, - type Peer, - type Transport, -} from "@comline/runtime"; -import * as ns_chat_admin from "./chat/admin.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 - * - * @internal - */ -export const HELLO = new Uint8Array([ - 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, - 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, - 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, - 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, - 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, - 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, -]); - -/** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. - * @internal - */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { - scope: "protocol", - newerConsumer: "degrade", - sameVersionDiffers: "refuse", - exchange: "offer", - }); -} - -/** The package's protocols on the connection, by wire number. */ -const PROTOCOLS = new Map([[0, "chat::admin::Admin"]]); - -/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ -export function negotiated(conn: Peer): Negotiated | undefined { - return conn.extensions.get(Negotiated); -} - -/** - * The protocols that connected although their wire shape differs from the - * peer's at the same version (`same_version_differs = warn`), by path. - */ -export function warnings(conn: Peer): string[] { - return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); -} - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - admin: ns_chat_admin.Admin; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const agreed = handshake(); - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); - conn.extensions.set(agreed.negotiated!); - return conn; -} diff --git a/conformance/tests/golden/nested_protocol/typescript/wire.ts b/conformance/tests/golden/nested_protocol/typescript/wire.ts deleted file mode 100644 index cf9accb..0000000 --- a/conformance/tests/golden/nested_protocol/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xa6f61afefe65d74an; diff --git a/conformance/tests/golden/optional_and_arrays/rust/conformance.rs b/conformance/tests/golden/optional_and_arrays/rust/conformance.rs deleted file mode 100644 index c71626f..0000000 --- a/conformance/tests/golden/optional_and_arrays/rust/conformance.rs +++ /dev/null @@ -1,12 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Bag { - pub required: String, - pub maybe: Option, - pub many: Vec, - pub maybe_many: Option>, -} - diff --git a/conformance/tests/golden/optional_and_arrays/typescript/conformance.ts b/conformance/tests/golden/optional_and_arrays/typescript/conformance.ts deleted file mode 100644 index f535b07..0000000 --- a/conformance/tests/golden/optional_and_arrays/typescript/conformance.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Bag { - required: string; - maybe?: number; - many: string[]; - maybe_many?: number[]; -} - -export const BagLayout: Layout = { struct: [["required", "string"], ["maybe", { option: "u32" }], ["many", { array: "string" }], ["maybe_many", { option: { array: "u32" } }]] }; - diff --git a/conformance/tests/golden/primitives/rust/conformance.rs b/conformance/tests/golden/primitives/rust/conformance.rs deleted file mode 100644 index b39b390..0000000 --- a/conformance/tests/golden/primitives/rust/conformance.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Scalars { - pub flag: bool, - pub small: u8, - pub medium: u32, - pub large: u64, - pub huge: u128, - pub signed_small: i8, - pub signed_large: i64, - pub name: String, -} - diff --git a/conformance/tests/golden/primitives/typescript/conformance.ts b/conformance/tests/golden/primitives/typescript/conformance.ts deleted file mode 100644 index 600fa7e..0000000 --- a/conformance/tests/golden/primitives/typescript/conformance.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Scalars { - flag: boolean; - small: number; - medium: number; - large: bigint; - huge: bigint; - signed_small: number; - signed_large: bigint; - name: string; -} - -export const ScalarsLayout: Layout = { struct: [["flag", "bool"], ["small", "u8"], ["medium", "u32"], ["large", "u64"], ["huge", "u128"], ["signed_small", "s8"], ["signed_large", "s64"], ["name", "string"]] }; - diff --git a/conformance/tests/golden/protocol/rust/conformance.rs b/conformance/tests/golden/protocol/rust/conformance.rs deleted file mode 100644 index ace4801..0000000 --- a/conformance/tests/golden/protocol/rust/conformance.rs +++ /dev/null @@ -1,237 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0x8ee00745c73a32b2; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Record { - pub id: i32, - pub name: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct NotFound { -} - -impl core::fmt::Display for NotFound { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("NotFound occurred") - } -} - -impl core::error::Error for NotFound {} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceLookupParams { - pub id: i32, -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServiceNotifyParams { - pub code: u16, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceLookupError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceLookupError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceLookupError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceLookupError {} - -pub type ServiceCountError = ::core::convert::Infallible; - -#[derive(Debug, Clone, PartialEq)] -pub enum ServiceError { - NotFound(NotFound), -} - -impl core::fmt::Display for ServiceError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - ServiceError::NotFound(e) => e.fmt(f), - } - } -} - -impl core::error::Error for ServiceError {} - -impl From for ServiceError { - fn from(e: ServiceLookupError) -> Self { - match e { - ServiceLookupError::NotFound(x) => ServiceError::NotFound(x), - } - } -} - -pub trait Service { - fn lookup(&self, peer: &mut impl Peer, id: i32) -> Result>; - fn count(&self, peer: &mut impl Peer) -> Result>; - fn notify(&self, peer: &mut impl Peer, code: u16); -} - -#[doc(hidden)] -pub const SERVICE_CALLS: &[&str] = &["lookup", "count", "notify"]; - -#[doc(hidden)] -pub struct ServiceDispatcher(pub S); - -impl Dispatch for ServiceDispatcher { - fn calls(&self) -> &'static [&'static str] { - SERVICE_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(SERVICE_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: ServiceLookupParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.lookup(peer, p.id) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(ServiceLookupError::NotFound(e))) => { - let mut body = Vec::new(); - peer.format().encode(&e, &mut body)?; - reply.err(0u16, &body); - } - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 1 => { - let _: () = match peer.format().decode(params) { - Ok(unit) => unit, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.count(peer) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - 2 => { - let p: ServiceNotifyParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => return Ok(()), - }; - self.0.notify(peer, p.code); - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl ServiceDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Service` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct ServiceSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> ServiceSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn lookup(&mut self, id: i32) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "lookup"), &ServiceLookupParams { id })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id: 0u16, body } => { - let e: NotFound = fmt.decode(body)?; - Err(CallError::App(ServiceLookupError::NotFound(e))) - } - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn count(&mut self) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "count"), &())?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } - - pub fn notify(&mut self, code: u16) -> Result<(), RuntimeError> { - self.0.notify(Self::PROTOCOL, Call::new(2, "notify"), &ServiceNotifyParams { code }) - } -} - diff --git a/conformance/tests/golden/protocol/rust/connection.rs b/conformance/tests/golden/protocol/rust/connection.rs deleted file mode 100644 index db67fce..0000000 --- a/conformance/tests/golden/protocol/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Service`. -//! - Serve with [`serve`]`(transport, Services { service: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `ServiceSender::new(&mut conn).lookup(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub service: Service, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::ServiceDispatcher(self.service).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/protocol/typescript/conformance.ts b/conformance/tests/golden/protocol/typescript/conformance.ts deleted file mode 100644 index cd34d80..0000000 --- a/conformance/tests/golden/protocol/typescript/conformance.ts +++ /dev/null @@ -1,161 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0x8ee00745c73a32b2n; - -export interface Record { - id: number; - name: string; -} - -export const RecordLayout: Layout = { struct: [["id", "s32"], ["name", "string"]] }; - -export interface NotFound { -} - -export const NotFoundLayout: Layout = { struct: [] }; - -export class NotFoundError extends Error { - static readonly ordinal = 0; - readonly data: NotFound; - constructor(data: NotFound) { - super("NotFound"); - this.data = data; - this.name = "NotFoundError"; - } -} - -export interface ServiceLookupParams { - id: number; -} - -/** @internal */ -export const ServiceLookupParamsLayout: Layout = { struct: [["id", "s32"]] }; - -export interface ServiceNotifyParams { - code: number; -} - -/** @internal */ -export const ServiceNotifyParamsLayout: Layout = { struct: [["code", "u16"]] }; - -export interface Service { - /** @throws {NotFoundError} */ - lookup(peer: Peer, params: ServiceLookupParams): Promise; - count(peer: Peer): Promise; - notify(peer: Peer, params: ServiceNotifyParams): Promise; -} - -/** @internal */ -export const SERVICE_CALLS = ["lookup", "count", "notify"] as const; - -/** @internal */ -export class ServiceDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Service; - - constructor(impl: Service) { - this.impl = impl; - } - - calls(): readonly string[] { - return SERVICE_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, SERVICE_CALLS)) { - case 0: { - try { - const p = codec.decode(params, ServiceLookupParamsLayout); - reply.ok(codec.encode((await this.impl.lookup(peer, p)) ?? null, RecordLayout)); - } catch (e) { - if (e instanceof NotFoundError) { reply.err(NotFoundError.ordinal, codec.encode(e.data, NotFoundLayout)); return; } - reply.fault(); - } - return; - } - case 1: { - try { - reply.ok(codec.encode((await this.impl.count(peer)) ?? null, "u64")); - } catch { - reply.fault(); - } - return; - } - case 2: { - try { - const p = codec.decode(params, ServiceNotifyParamsLayout); - await this.impl.notify(peer, p); - } catch { - /* one-way: nowhere to report this */ - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(ServiceDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Service` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class ServiceSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async lookup(params: ServiceLookupParams): Promise { - const env = await this.peer.call(ServiceSender.PROTOCOL, { id: 0, name: "lookup" }, params, { layout: ServiceLookupParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, RecordLayout); - if ("fault" in env) throw RuntimeError.provider(); - switch (env.err.id) { - case NotFoundError.ordinal: - throw new NotFoundError(this.peer.codec.decode(env.err.body, NotFoundLayout)); - default: - throw RuntimeError.remote(env.err.id); - } - } - - async count(): Promise { - const env = await this.peer.call(ServiceSender.PROTOCOL, { id: 1, name: "count" }, null, { layout: "unit" }); - if ("ok" in env) return this.peer.codec.decode(env.ok, "u64"); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } - - async notify(params: ServiceNotifyParams): Promise { - await this.peer.notify(ServiceSender.PROTOCOL, { id: 2, name: "notify" }, params, { layout: ServiceNotifyParamsLayout }); - } -} - diff --git a/conformance/tests/golden/protocol/typescript/connection.ts b/conformance/tests/golden/protocol/typescript/connection.ts deleted file mode 100644 index 1a1cedb..0000000 --- a/conformance/tests/golden/protocol/typescript/connection.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Service` (in `./conformance.js`). - * - Serve with `serve(transport, { service })`; `accept(transport, { service })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new ServiceSender(conn).lookup(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - service: ns_conformance.Service; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - return conn; -} diff --git a/conformance/tests/golden/protocol/typescript/wire.ts b/conformance/tests/golden/protocol/typescript/wire.ts deleted file mode 100644 index b656979..0000000 --- a/conformance/tests/golden/protocol/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x8ee00745c73a32b2n; diff --git a/conformance/tests/golden/shapes/rust/conformance.rs b/conformance/tests/golden/shapes/rust/conformance.rs deleted file mode 100644 index 9a66b84..0000000 --- a/conformance/tests/golden/shapes/rust/conformance.rs +++ /dev/null @@ -1,19 +0,0 @@ -// This file uses `serde_big_array` - add it to your Cargo.toml: -// serde-big-array = "0.5" -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Sample { - pub ratio: f32, - pub precise: f64, - pub rgba: [u8; 4], - #[serde(with = "serde_big_array::BigArray")] - pub digest: [u8; 64], - pub rows: Vec<[u16; 3]>, - pub maybe_rgba: Option<[u8; 4]>, -} - -pub const SCALE: f32 = 2.0; - diff --git a/conformance/tests/golden/shapes/typescript/conformance.ts b/conformance/tests/golden/shapes/typescript/conformance.ts deleted file mode 100644 index c16949a..0000000 --- a/conformance/tests/golden/shapes/typescript/conformance.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Sample { - ratio: number; - precise: number; - rgba: number[]; - digest: number[]; - rows: number[][]; - maybe_rgba?: number[]; -} - -export const SampleLayout: Layout = { struct: [["ratio", "f32"], ["precise", "f64"], ["rgba", { fixed: "u8", length: 4 }], ["digest", { fixed: "u8", length: 64 }], ["rows", { array: { fixed: "u16", length: 3 } }], ["maybe_rgba", { option: { fixed: "u8", length: 4 } }]] }; - -export const SCALE = 2; - diff --git a/conformance/tests/golden/type_refs/rust/conformance.rs b/conformance/tests/golden/type_refs/rust/conformance.rs deleted file mode 100644 index 2d85d33..0000000 --- a/conformance/tests/golden/type_refs/rust/conformance.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Inner { - pub value: i32, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Outer { - pub one: Inner, - pub some: Option, - pub list: Vec, -} - diff --git a/conformance/tests/golden/type_refs/typescript/conformance.ts b/conformance/tests/golden/type_refs/typescript/conformance.ts deleted file mode 100644 index abe007d..0000000 --- a/conformance/tests/golden/type_refs/typescript/conformance.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export interface Inner { - value: number; -} - -export const InnerLayout: Layout = { struct: [["value", "s32"]] }; - -export interface Outer { - one: Inner; - some?: Inner; - list: Inner[]; -} - -export const OuterLayout: Layout = { struct: [["one", () => InnerLayout], ["some", { option: () => InnerLayout }], ["list", { array: () => InnerLayout }]] }; - diff --git a/conformance/tests/golden/unions/typescript/conformance.ts b/conformance/tests/golden/unions/typescript/conformance.ts deleted file mode 100644 index d32194c..0000000 --- a/conformance/tests/golden/unions/typescript/conformance.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import type { Layout } from "@comline/runtime"; - -export type Id = string | number; - -export const IdLayout: Layout = { union: ["string", "u32"] }; - -export interface Lookup { - key: string | number; -} - -export const LookupLayout: Layout = { struct: [["key", { union: ["string", "u32"] }]] }; - diff --git a/conformance/tests/golden/validators/rust/conformance.rs b/conformance/tests/golden/validators/rust/conformance.rs deleted file mode 100644 index d4ff3c3..0000000 --- a/conformance/tests/golden/validators/rust/conformance.rs +++ /dev/null @@ -1,301 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xeab4408b940579fb; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -pub const MIN_HANDLE: u32 = 2; - -pub type Handle = String; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Profile { - pub handle: Handle, - pub age: u32, - pub nickname: Option, - pub friends: Vec, -} - -impl comline_runtime::validation::Validate for Profile { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "handle"); - let value = &self.handle; - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - { - let path = comline_runtime::validation::field_path(path, "age"); - let value = &self.age; - // Range(min = 0, max = 120) - if first && !out.is_empty() { - return; - } - if !(((*value as i128) >= 0) && ((*value as i128) <= 120)) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be between {} and {}", path, 0i128, 120i128), - }); - } - } - { - let path = comline_runtime::validation::field_path(path, "nickname"); - if let Some(value) = &self.nickname { - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } - { - let path = comline_runtime::validation::field_path(path, "friends"); - let value = &self.friends; - for (i, value) in value.iter().enumerate() { - let path = comline_runtime::validation::index_path(&path, i); - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Post { - pub author: Profile, - pub body: String, -} - -impl comline_runtime::validation::Validate for Post { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "author"); - let value = &self.author; - comline_runtime::validation::Validate::validate_into(value, &path, out, first); - } - { - let path = comline_runtime::validation::field_path(path, "body"); - let value = &self.body; - // StringBounds(min_chars = 1, max_chars = 4294967295) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 1) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 1i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 4294967295) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 4294967295i128), - }); - } - } - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SocialRenameParams { - pub to: Handle, -} - -impl comline_runtime::validation::Validate for SocialRenameParams { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "to"); - let value = &self.to; - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } -} - -pub type SocialRenameError = ::core::convert::Infallible; - -pub type SocialError = ::core::convert::Infallible; - -pub trait Social { - fn rename(&self, peer: &mut impl Peer, to: Handle) -> Result>; -} - -#[doc(hidden)] -pub const SOCIAL_CALLS: &[&str] = &["rename"]; - -#[doc(hidden)] -pub struct SocialDispatcher(pub S); - -impl Dispatch for SocialDispatcher { - fn calls(&self) -> &'static [&'static str] { - SOCIAL_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(SOCIAL_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: SocialRenameParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - match self.0.rename(peer, p.to) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl SocialDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Social` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct SocialSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> SocialSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn rename(&mut self, to: Handle) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "rename"), &SocialRenameParams { to })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/validators/rust/connection.rs b/conformance/tests/golden/validators/rust/connection.rs deleted file mode 100644 index fb3ce3a..0000000 --- a/conformance/tests/golden/validators/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Social`. -//! - Serve with [`serve`]`(transport, Services { social: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `SocialSender::new(&mut conn).rename(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xf9d255a977b3b030; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub social: Social, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::SocialDispatcher(self.social).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/validators/rust/std/validators.rs b/conformance/tests/golden/validators/rust/std/validators.rs deleted file mode 100644 index 3202fde..0000000 --- a/conformance/tests/golden/validators/rust/std/validators.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. - diff --git a/conformance/tests/golden/validators/typescript/conformance.ts b/conformance/tests/golden/validators/typescript/conformance.ts deleted file mode 100644 index c72d455..0000000 --- a/conformance/tests/golden/validators/typescript/conformance.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xeab4408b940579fbn; - -export const MIN_HANDLE = 2; - -export type Handle = string; - -export const HandleLayout: Layout = "string"; - -export interface Profile { - handle: Handle; - age: number; - nickname?: Handle; - friends: Handle[]; -} - -export const ProfileLayout: Layout = { struct: [["handle", () => HandleLayout], ["age", "u32"], ["nickname", { option: () => HandleLayout }], ["friends", { array: () => HandleLayout }]] }; - -export interface Post { - author: Profile; - body: string; -} - -export const PostLayout: Layout = { struct: [["author", () => ProfileLayout], ["body", "string"]] }; - -export interface SocialRenameParams { - to: Handle; -} - -/** @internal */ -export const SocialRenameParamsLayout: Layout = { struct: [["to", () => HandleLayout]] }; - -export interface Social { - rename(peer: Peer, params: SocialRenameParams): Promise; -} - -/** @internal */ -export const SOCIAL_CALLS = ["rename"] as const; - -/** @internal */ -export class SocialDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Social; - - constructor(impl: Social) { - this.impl = impl; - } - - calls(): readonly string[] { - return SOCIAL_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, SOCIAL_CALLS)) { - case 0: { - try { - const p = codec.decode(params, SocialRenameParamsLayout); - reply.ok(codec.encode((await this.impl.rename(peer, p)) ?? null, HandleLayout)); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(SocialDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Social` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class SocialSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async rename(params: SocialRenameParams): Promise { - const env = await this.peer.call(SocialSender.PROTOCOL, { id: 0, name: "rename" }, params, { layout: SocialRenameParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, HandleLayout); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/validators/typescript/connection.ts b/conformance/tests/golden/validators/typescript/connection.ts deleted file mode 100644 index abe85a9..0000000 --- a/conformance/tests/golden/validators/typescript/connection.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Social` (in `./conformance.js`). - * - Serve with `serve(transport, { social })`; `accept(transport, { social })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new SocialSender(conn).rename(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - social: ns_conformance.Social; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.SocialDispatcher(services.social).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - return conn; -} diff --git a/conformance/tests/golden/validators/typescript/std/validators.ts b/conformance/tests/golden/validators/typescript/std/validators.ts deleted file mode 100644 index affa264..0000000 --- a/conformance/tests/golden/validators/typescript/std/validators.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - diff --git a/conformance/tests/golden/validators/typescript/wire.ts b/conformance/tests/golden/validators/typescript/wire.ts deleted file mode 100644 index 71c56b7..0000000 --- a/conformance/tests/golden/validators/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xf9d255a977b3b030n; diff --git a/conformance/tests/golden/validators_on_decode/rust/conformance.rs b/conformance/tests/golden/validators_on_decode/rust/conformance.rs deleted file mode 100644 index 0b4bf93..0000000 --- a/conformance/tests/golden/validators_on_decode/rust/conformance.rs +++ /dev/null @@ -1,355 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -use serde::{Deserialize, Serialize}; -use comline_runtime::connection::Connection; -use comline_runtime::contract::{ - Call, CallError, Dispatch, Envelope, Fault, Kind, Reply, RuntimeError, WireFormat, -}; -use comline_runtime::contract::{ConnectionFraming, Peer, ProtocolNumber}; -use comline_runtime::transport::Transport; - -/// Canonical digest of the frozen IR this file was generated from — the -/// two ends of a connection must agree on it, and the handshake checks. -pub const IR_HASH: u64 = 0xeab4408b940579fb; - -#[doc(hidden)] -pub use crate::connection::{CONNECTION_IR_HASH, Format}; - -pub const MIN_HANDLE: u32 = 2; - -pub type Handle = String; - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(try_from = "__ProfileUnchecked")] -pub struct Profile { - pub handle: Handle, - pub age: u32, - pub nickname: Option, - pub friends: Vec, -} - -impl comline_runtime::validation::Validate for Profile { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "handle"); - let value = &self.handle; - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - { - let path = comline_runtime::validation::field_path(path, "age"); - let value = &self.age; - // Range(min = 0, max = 120) - if first && !out.is_empty() { - return; - } - if !(((*value as i128) >= 0) && ((*value as i128) <= 120)) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be between {} and {}", path, 0i128, 120i128), - }); - } - } - { - let path = comline_runtime::validation::field_path(path, "nickname"); - if let Some(value) = &self.nickname { - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } - { - let path = comline_runtime::validation::field_path(path, "friends"); - let value = &self.friends; - for (i, value) in value.iter().enumerate() { - let path = comline_runtime::validation::index_path(&path, i); - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } - } -} - -/// [`Profile`] as decoded, before its checks run. -#[doc(hidden)] -#[allow(non_camel_case_types)] -#[derive(Deserialize)] -pub struct __ProfileUnchecked { - pub handle: Handle, - pub age: u32, - pub nickname: Option, - pub friends: Vec, -} - -impl TryFrom<__ProfileUnchecked> for Profile { - type Error = comline_runtime::validation::ValidationErrors; - - fn try_from(raw: __ProfileUnchecked) -> Result { - let value = Self { - handle: raw.handle, - age: raw.age, - nickname: raw.nickname, - friends: raw.friends, - }; - comline_runtime::validation::Validate::validate(&value)?; - Ok(value) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(try_from = "__PostUnchecked")] -pub struct Post { - pub author: Profile, - pub body: String, -} - -impl comline_runtime::validation::Validate for Post { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "author"); - let value = &self.author; - comline_runtime::validation::Validate::validate_into(value, &path, out, first); - } - { - let path = comline_runtime::validation::field_path(path, "body"); - let value = &self.body; - // StringBounds(min_chars = 1, max_chars = 4294967295) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 1) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 1i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 4294967295) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 4294967295i128), - }); - } - } - } -} - -/// [`Post`] as decoded, before its checks run. -#[doc(hidden)] -#[allow(non_camel_case_types)] -#[derive(Deserialize)] -pub struct __PostUnchecked { - pub author: Profile, - pub body: String, -} - -impl TryFrom<__PostUnchecked> for Post { - type Error = comline_runtime::validation::ValidationErrors; - - fn try_from(raw: __PostUnchecked) -> Result { - let value = Self { - author: raw.author, - body: raw.body, - }; - comline_runtime::validation::Validate::validate(&value)?; - Ok(value) - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SocialRenameParams { - pub to: Handle, -} - -impl comline_runtime::validation::Validate for SocialRenameParams { - #[allow(unused_variables)] - fn validate_into(&self, path: &str, out: &mut Vec, first: bool) { - { - let path = comline_runtime::validation::field_path(path, "to"); - let value = &self.to; - // StringBounds(min_chars = 2, max_chars = 8) - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) >= 2) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at least {} characters", path, 2i128), - }); - } - if first && !out.is_empty() { - return; - } - if !((value.chars().count() as i128) <= 8) { - out.push(comline_runtime::validation::ValidationError { - field: path.clone(), - message: format!("{} must be at most {} characters", path, 8i128), - }); - } - } - } -} - -pub type SocialRenameError = ::core::convert::Infallible; - -pub type SocialError = ::core::convert::Infallible; - -pub trait Social { - fn rename(&self, peer: &mut impl Peer, to: Handle) -> Result>; -} - -#[doc(hidden)] -pub const SOCIAL_CALLS: &[&str] = &["rename"]; - -#[doc(hidden)] -pub struct SocialDispatcher(pub S); - -impl Dispatch for SocialDispatcher { - fn calls(&self) -> &'static [&'static str] { - SOCIAL_CALLS - } - - /// Only served on a connection, whose handlers are given the peer: - /// anywhere else the caller hears a fault. - fn dispatch( - &self, - _call: Kind, - _params: &[u8], - _fmt: &W, - reply: &mut Reply, - ) -> Result<(), RuntimeError> { - reply.fault(); - Ok(()) - } - - fn dispatch_with( - &self, - call: Kind, - params: &[u8], - reply: &mut Reply, - peer: &mut P, - ) -> Result<(), RuntimeError> { - match call.resolve(SOCIAL_CALLS).ok_or(RuntimeError::UnknownCall)? { - 0 => { - let p: SocialRenameParams = match peer.format().decode(params) { - Ok(p) => p, - Err(_) => { - reply.fault(); - return Ok(()); - } - }; - if comline_runtime::validation::Validate::validate_first(&p).is_err() { - reply.fault(); - return Ok(()); - } - match self.0.rename(peer, p.to) { - Ok(value) => { - let mut body = Vec::new(); - peer.format().encode(&value, &mut body)?; - reply.ok(&body); - } - Err(Fault::App(never)) => match never {}, - Err(Fault::Internal) => reply.fault(), - } - Ok(()) - } - _ => Err(RuntimeError::UnknownCall), - } - } -} - -impl SocialDispatcher { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - /// Provide this protocol on `conn`: the peer's calls to it come here. - /// Open `conn` with `Connection::accept(transport, format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. - pub fn provide_on( - self, - conn: &mut Connection, - ) where - S: 'static, - { - conn.provide(Self::PROTOCOL, self) - } -} - -/// Calls protocol `Social` on the other end of a connection: the peer a -/// `Connection` reaches, or the one a handler was given. -pub struct SocialSender<'p, P: Peer>(pub &'p mut P); - -impl<'p, P: Peer> SocialSender<'p, P> { - /// This protocol's number on a connection. - #[doc(hidden)] - pub const PROTOCOL: ProtocolNumber = 0; - - pub fn new(peer: &'p mut P) -> Self { - Self(peer) - } - - pub fn rename(&mut self, to: Handle) -> Result> { - let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(0, "rename"), &SocialRenameParams { to })?; - match reply { - Envelope::Ok(payload) => fmt.decode(payload).map_err(CallError::Runtime), - Envelope::Err { id, .. } => Err(CallError::Runtime(RuntimeError::Remote { id })), - Envelope::Fault => Err(CallError::Runtime(RuntimeError::Provider)), - } - } -} - diff --git a/conformance/tests/golden/validators_on_decode/rust/connection.rs b/conformance/tests/golden/validators_on_decode/rust/connection.rs deleted file mode 100644 index fb3ce3a..0000000 --- a/conformance/tests/golden/validators_on_decode/rust/connection.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. -//! The package's protocols share one connection: `datagram@2` framing, the `comline@1` handshake. To use it: -//! -//! - Implement the trait of each protocol the server provides: `conformance::Social`. -//! - Serve with [`serve`]`(transport, Services { social: .. })`, which serves every call until the peer leaves. [`accept`] hands the connection back first, for a server that calls the client or serves one call at a time. -//! - Dial with [`connect`]`(transport)`. -//! - Call the server from the dialling side: `SocialSender::new(&mut conn).rename(..)`. -//! -//! [`Connection`](Connection) names the connection over a transport `T`, written `Connection`; [`Format`] is the package's wire format. - -use comline_runtime::contract::RuntimeError; -use comline_runtime::transport::Transport; - -/// The package's wire format (`wire.format`). -pub type Format = comline_runtime::format::Packed; - -/// Digest of every schema in the package — what a connection's handshake -/// checks, so both ends agree on each protocol's number. -pub const CONNECTION_IR_HASH: u64 = 0xf9d255a977b3b030; - -/// The package's connection over the transport `T`: what [`accept`] and [`connect`] -/// return, written `Connection`: [`Format`] over the default framing. -pub type Connection = comline_runtime::connection::Connection; - -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. -pub struct Services { - pub social: Social, -} - -impl Services { - /// Provide every protocol on `conn`: the peer's calls to them come here. - pub fn provide_on(self, conn: &mut Connection) { - crate::conformance::SocialDispatcher(self.social).provide_on(conn); - } -} - -/// Accept a connection over `transport`: run the handshake, then provide -/// every protocol in `services` on it. The connection comes back not yet -/// served, for a server that calls the client first, or serves one call at -/// a time. -pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { - let mut conn = comline_runtime::connection::Connection::accept(transport, Format::default(), CONNECTION_IR_HASH)?; - services.provide_on(&mut conn); - Ok(conn) -} - -/// [`accept`], then serve every call until the peer leaves. -pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { - accept(transport, services)?.serve() -} - -/// Dial over `transport`: run the handshake. Call the server's protocols -/// through their senders. -pub fn connect(transport: T) -> Result, RuntimeError> { - let conn = comline_runtime::connection::Connection::connect(transport, Format::default(), CONNECTION_IR_HASH)?; - Ok(conn) -} diff --git a/conformance/tests/golden/validators_on_decode/rust/std/validators.rs b/conformance/tests/golden/validators_on_decode/rust/std/validators.rs deleted file mode 100644 index 3202fde..0000000 --- a/conformance/tests/golden/validators_on_decode/rust/std/validators.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Generated by Comline -// For Rust 1.85.0 or later; verified up to 1.99. - diff --git a/conformance/tests/golden/validators_on_decode/typescript/conformance.ts b/conformance/tests/golden/validators_on_decode/typescript/conformance.ts deleted file mode 100644 index c72d455..0000000 --- a/conformance/tests/golden/validators_on_decode/typescript/conformance.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - RuntimeError, - resolveKind, - type Codec, - type Connection, - type Dispatch, - type Kind, - type Layout, - type Peer, - type Reply, -} from "@comline/runtime"; - -/** Canonical digest of the frozen IR this file was generated from — the -* two ends of a connection must agree on it. */ -export const IR_HASH = 0xeab4408b940579fbn; - -export const MIN_HANDLE = 2; - -export type Handle = string; - -export const HandleLayout: Layout = "string"; - -export interface Profile { - handle: Handle; - age: number; - nickname?: Handle; - friends: Handle[]; -} - -export const ProfileLayout: Layout = { struct: [["handle", () => HandleLayout], ["age", "u32"], ["nickname", { option: () => HandleLayout }], ["friends", { array: () => HandleLayout }]] }; - -export interface Post { - author: Profile; - body: string; -} - -export const PostLayout: Layout = { struct: [["author", () => ProfileLayout], ["body", "string"]] }; - -export interface SocialRenameParams { - to: Handle; -} - -/** @internal */ -export const SocialRenameParamsLayout: Layout = { struct: [["to", () => HandleLayout]] }; - -export interface Social { - rename(peer: Peer, params: SocialRenameParams): Promise; -} - -/** @internal */ -export const SOCIAL_CALLS = ["rename"] as const; - -/** @internal */ -export class SocialDispatcher implements Dispatch { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly impl: Social; - - constructor(impl: Social) { - this.impl = impl; - } - - calls(): readonly string[] { - return SOCIAL_CALLS; - } - - /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ - async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { - reply.fault(); - } - - async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { - const codec = peer.codec; - switch (resolveKind(call, SOCIAL_CALLS)) { - case 0: { - try { - const p = codec.decode(params, SocialRenameParamsLayout); - reply.ok(codec.encode((await this.impl.rename(peer, p)) ?? null, HandleLayout)); - } catch { - reply.fault(); - } - return; - } - default: - throw RuntimeError.unknownCall(); - } - } - - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ - provideOn(conn: Connection): void { - conn.provide(SocialDispatcher.PROTOCOL, this); - } -} - -/** Calls protocol `Social` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ -export class SocialSender { - /** This protocol's number on a connection. */ - static readonly PROTOCOL = 0; - - private readonly peer: Peer; - - constructor(peer: Peer) { - this.peer = peer; - } - - async rename(params: SocialRenameParams): Promise { - const env = await this.peer.call(SocialSender.PROTOCOL, { id: 0, name: "rename" }, params, { layout: SocialRenameParamsLayout }); - if ("ok" in env) return this.peer.codec.decode(env.ok, HandleLayout); - if ("fault" in env) throw RuntimeError.provider(); - throw RuntimeError.remote(env.err.id); - } -} - diff --git a/conformance/tests/golden/validators_on_decode/typescript/connection.ts b/conformance/tests/golden/validators_on_decode/typescript/connection.ts deleted file mode 100644 index abe85a9..0000000 --- a/conformance/tests/golden/validators_on_decode/typescript/connection.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -/** - * Where to start: - * - * - Implement what you provide: `Social` (in `./conformance.js`). - * - Serve with `serve(transport, { social })`; `accept(transport, { social })` takes the same and hands back the connection. - * - Dial with `connect(transport)`. - * - Call the other end with `new SocialSender(conn).rename(…)`, on the connection `connect` returns or the peer a handler is given. - * - * What is marked internal is wire plumbing: exported for hand-written use, and not what - * a user calls. - */ - -import { - Connection, - type Transport, -} from "@comline/runtime"; -import * as ns_conformance from "./conformance.js"; -import { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ -export { CONNECTION_IR_HASH, Format } from "./wire.js"; - -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ -export interface Services { - social: ns_conformance.Social; -} - -/** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. - * @internal - */ -export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.SocialDispatcher(services.social).provideOn(conn); -} - -/** -* Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, -* so the server can call the client through it. -*/ -export async function accept(transport: Transport, services: Services): Promise { - const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); - provideServices(conn, services); - return conn; -} - -/** {@link accept}, then serve every call until the peer leaves. */ -export async function serve(transport: Transport, services: Services): Promise { - await (await accept(transport, services)).closed; -} - -/** -* Dial over `transport`: run the handshake. Call the server's protocols -* through their senders. -*/ -export async function connect(transport: Transport): Promise { - const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); - return conn; -} diff --git a/conformance/tests/golden/validators_on_decode/typescript/std/validators.ts b/conformance/tests/golden/validators_on_decode/typescript/std/validators.ts deleted file mode 100644 index affa264..0000000 --- a/conformance/tests/golden/validators_on_decode/typescript/std/validators.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - diff --git a/conformance/tests/golden/validators_on_decode/typescript/wire.ts b/conformance/tests/golden/validators_on_decode/typescript/wire.ts deleted file mode 100644 index 71c56b7..0000000 --- a/conformance/tests/golden/validators_on_decode/typescript/wire.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Generated by Comline -// For TypeScript 5.0 or later; verified up to 5.9. - -import { - PackedCodec, - type Codec, -} from "@comline/runtime"; - -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xf9d255a977b3b030n; diff --git a/features.json b/features.json deleted file mode 100644 index d037fb4..0000000 --- a/features.json +++ /dev/null @@ -1,930 +0,0 @@ -{ - "features": [ - { - "description": "`struct` declarations", - "id": "structs", - "title": "structs" - }, - { - "description": "`enum` declarations", - "id": "enums", - "title": "enums" - }, - { - "description": "fields marked `optional`", - "id": "optional-fields", - "title": "optional fields" - }, - { - "description": "variable-length arrays, `T[]`", - "id": "arrays", - "title": "arrays" - }, - { - "description": "fixed-length arrays, `T[N]`", - "id": "fixed-arrays", - "title": "fixed-length arrays" - }, - { - "description": "a `T[N]` with N over 32 anywhere but a field's own, non-optional type: inside another array, optional, an alias, an argument or a return", - "id": "large-fixed-arrays-nested", - "title": "fixed arrays over 32 elements, nested" - }, - { - "description": "`union(A B ...)` types", - "id": "unions", - "title": "unions" - }, - { - "description": "`type Name = ...` declarations", - "id": "type-aliases", - "title": "type aliases" - }, - { - "description": "`const` declarations", - "id": "constants", - "title": "constants" - }, - { - "description": "`protocol` declarations and their functions", - "id": "protocols", - "title": "protocols" - }, - { - "description": "`error` declarations", - "id": "errors", - "title": "errors" - }, - { - "description": "functions declared with `! Error`", - "id": "throws", - "title": "functions that throw" - }, - { - "description": "`@validators` on fields and type aliases, checked in generated code", - "id": "validators", - "title": "validators" - }, - { - "description": "`use` of another schema's declarations", - "id": "imports", - "title": "imports between schemas" - }, - { - "description": "schemas in subdirectories (`chat::admin`)", - "id": "nested-namespaces", - "title": "nested namespaces" - }, - { - "description": "`--mode lib`: a buildable package, not bare source files", - "id": "lib-mode", - "title": "`lib` mode" - }, - { - "description": "`[generate] external_std`: `std` referenced as its own package", - "id": "external-std", - "title": "`external_std`" - }, - { - "description": "`[generate] validate_on_decode`: decoding runs the checks", - "id": "validate-on-decode", - "title": "`validate_on_decode`" - }, - { - "description": "`@framing = \"jsonrpc\"` (or as the package default)", - "id": "framing-jsonrpc", - "title": "JSON-RPC framing" - }, - { - "description": "`@handshake = \"none\"` (or as the package default)", - "id": "handshake-none", - "title": "no handshake" - }, - { - "description": "`@framing = \"datagram@3\"` (or as the package default): calls addressed by wire numbers", - "id": "framing-datagram3", - "title": "`datagram@3` framing" - }, - { - "description": "`@handshake = \"comline@2\"` (or as the package default): compatibility checked by each version's facts, calls the peer lacks failing locally", - "id": "handshake-comline2", - "title": "`comline@2` handshake" - }, - { - "description": "protocols on a connection, with calls in both directions: `datagram@3` (the default) or `datagram@2`, or `@provider = Client` / `Multiple`", - "id": "connections", - "title": "connections" - }, - { - "description": "`[generate] async`: connection protocols get async handlers and senders", - "id": "async", - "title": "`async`" - }, - { - "description": "`wire.format = \"packed@1\"`, the default: fixed-width fields, no tags", - "id": "format-packed", - "title": "the `packed@1` format" - }, - { - "description": "`wire.format = \"json@1\"`", - "id": "format-json", - "title": "the `json@1` format" - }, - { - "description": "`wire.format = \"msgpack@1\"`", - "id": "format-msgpack", - "title": "the `msgpack@1` format" - }, - { - "description": "a maximum or exact length on a string or list (`char[max 64]`, `char[8]`, `T[max N]`), or a depth limit (`@max_depth`): checked while decoding and encoding", - "id": "bounds", - "title": "bounds" - }, - { - "description": "`char`: one Unicode scalar value", - "id": "chars", - "title": "single characters" - } - ], - "generators": [ - { - "name": "rust", - "support": { - "arrays": { - "note": null, - "proven_by": [ - "optional_and_arrays", - "type_refs", - "shapes", - "cross_schema", - "validators", - "validators_on_decode", - "lockstep", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "async": { - "note": null, - "proven_by": [ - "connections_async" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "bounds": { - "note": null, - "proven_by": [ - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "chars": { - "note": null, - "proven_by": [ - "chars" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "connections": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "connections", - "connections_async", - "connections_jsonrpc", - "connections_default", - "format_json", - "format_msgpack", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "constants": { - "note": null, - "proven_by": [ - "constant", - "shapes", - "validators", - "validators_on_decode" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "enums": { - "note": null, - "proven_by": [ - "enum_basic" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "errors": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "lockstep", - "format_json", - "format_msgpack" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "external-std": { - "note": null, - "proven_by": [ - "external_std" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "fixed-arrays": { - "note": null, - "proven_by": [ - "shapes" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "format-json": { - "note": null, - "proven_by": [ - "format_json" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "format-msgpack": { - "note": null, - "proven_by": [ - "format_msgpack" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "format-packed": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "lockstep", - "connections", - "connections_async", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "framing-datagram3": { - "note": null, - "proven_by": [ - "framing_datagram3", - "handshake_comline2", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "framing-jsonrpc": { - "note": null, - "proven_by": [ - "framing_jsonrpc", - "connections_jsonrpc" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "handshake-comline2": { - "note": null, - "proven_by": [ - "handshake_comline2", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "handshake-none": { - "note": null, - "proven_by": [ - "handshake_none" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "imports": { - "note": null, - "proven_by": [ - "cross_schema", - "import_alias", - "import_glob", - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "dependency_protocol", - "dependency_and_own_protocols" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "large-fixed-arrays-nested": { - "note": "a fixed array over 32 elements renders only as a struct or error field's own, non-optional type (serde's derive stops at 32)", - "proven_by": [ - "large_fixed_arrays_nested" - ], - "since": null, - "state": "unsupported", - "tracking": null - }, - "lib-mode": { - "note": null, - "proven_by": [ - "nested_namespace", - "external_std" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "nested-namespaces": { - "note": null, - "proven_by": [ - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "optional-fields": { - "note": null, - "proven_by": [ - "optional_and_arrays", - "type_refs", - "shapes", - "cross_schema", - "validators", - "validators_on_decode", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "protocols": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "framing_jsonrpc", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "lockstep", - "connections", - "connections_async", - "connections_jsonrpc", - "connections_default", - "format_json", - "format_msgpack", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "structs": { - "note": null, - "proven_by": [ - "primitives", - "optional_and_arrays", - "type_refs", - "protocol", - "shapes", - "cross_schema", - "import_alias", - "import_glob", - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "lockstep", - "format_json", - "format_msgpack", - "bounds", - "chars", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "throws": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "lockstep", - "format_json", - "format_msgpack" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "type-aliases": { - "note": null, - "proven_by": [ - "validators", - "validators_on_decode", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "unions": { - "note": "Rust has no anonymous sum type to render one as", - "proven_by": [ - "unions" - ], - "since": null, - "state": "unsupported", - "tracking": null - }, - "validate-on-decode": { - "note": null, - "proven_by": [ - "validators_on_decode" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "validators": { - "note": null, - "proven_by": [ - "validators", - "validators_on_decode" - ], - "since": null, - "state": "supported", - "tracking": null - } - }, - "version": "1.85.0", - "versions": { - "changes": [], - "floor": "1.85.0", - "forward_compatible": true, - "verified_up_to": "1.99" - } - }, - { - "name": "typescript", - "support": { - "arrays": { - "note": null, - "proven_by": [ - "optional_and_arrays", - "type_refs", - "shapes", - "cross_schema", - "validators", - "validators_on_decode", - "large_fixed_arrays_nested", - "lockstep", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "async": { - "note": "handlers and senders always return Promises: the output is async either way", - "proven_by": [ - "connections_async" - ], - "since": null, - "state": "ignored", - "tracking": null - }, - "bounds": { - "note": null, - "proven_by": [ - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "chars": { - "note": null, - "proven_by": [ - "chars" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "connections": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "connections", - "connections_async", - "connections_jsonrpc", - "connections_default", - "format_json", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "constants": { - "note": null, - "proven_by": [ - "constant", - "shapes", - "validators", - "validators_on_decode" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "enums": { - "note": null, - "proven_by": [ - "enum_basic" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "errors": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "lockstep", - "format_json" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "external-std": { - "note": null, - "proven_by": [ - "external_std" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "fixed-arrays": { - "note": "rendered as `T[]`: the length isn't part of the type", - "proven_by": [ - "shapes", - "large_fixed_arrays_nested" - ], - "since": null, - "state": "partial", - "tracking": null - }, - "format-json": { - "note": null, - "proven_by": [ - "format_json" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "format-msgpack": { - "note": "`@comline/runtime` has no MessagePack codec yet", - "proven_by": [ - "format_msgpack" - ], - "since": null, - "state": "unsupported", - "tracking": null - }, - "format-packed": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "lockstep", - "connections", - "connections_async", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "framing-datagram3": { - "note": null, - "proven_by": [ - "framing_datagram3", - "handshake_comline2", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "framing-jsonrpc": { - "note": null, - "proven_by": [ - "framing_jsonrpc", - "connections_jsonrpc" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "handshake-comline2": { - "note": null, - "proven_by": [ - "handshake_comline2", - "connections_default", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "handshake-none": { - "note": null, - "proven_by": [ - "handshake_none" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "imports": { - "note": null, - "proven_by": [ - "cross_schema", - "import_alias", - "import_glob", - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "dependency_protocol", - "dependency_and_own_protocols" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "large-fixed-arrays-nested": { - "note": "rendered as `T[]`: the length isn't part of the type", - "proven_by": [ - "large_fixed_arrays_nested" - ], - "since": null, - "state": "partial", - "tracking": null - }, - "lib-mode": { - "note": null, - "proven_by": [ - "nested_namespace", - "external_std" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "nested-namespaces": { - "note": null, - "proven_by": [ - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "optional-fields": { - "note": null, - "proven_by": [ - "optional_and_arrays", - "type_refs", - "shapes", - "cross_schema", - "validators", - "validators_on_decode", - "large_fixed_arrays_nested", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "protocols": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "validators", - "validators_on_decode", - "framing_jsonrpc", - "handshake_none", - "framing_datagram3", - "handshake_comline2", - "lockstep", - "connections", - "connections_async", - "connections_jsonrpc", - "connections_default", - "format_json", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "structs": { - "note": null, - "proven_by": [ - "primitives", - "optional_and_arrays", - "type_refs", - "protocol", - "shapes", - "cross_schema", - "import_alias", - "import_glob", - "nested_namespace", - "external_std", - "validators", - "validators_on_decode", - "unions", - "large_fixed_arrays_nested", - "lockstep", - "format_json", - "bounds", - "chars", - "dependency_protocol", - "dependency_and_own_protocols", - "nested_protocol" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "throws": { - "note": null, - "proven_by": [ - "protocol", - "error_shapes", - "lockstep", - "format_json" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "type-aliases": { - "note": null, - "proven_by": [ - "validators", - "validators_on_decode", - "unions", - "bounds" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "unions": { - "note": null, - "proven_by": [ - "unions" - ], - "since": null, - "state": "supported", - "tracking": null - }, - "validate-on-decode": { - "note": "no checks are generated to run on decode yet", - "proven_by": [ - "validators_on_decode" - ], - "since": null, - "state": "ignored", - "tracking": "core#96" - }, - "validators": { - "note": "the types are generated; the checks aren't run yet", - "proven_by": [ - "validators", - "validators_on_decode" - ], - "since": null, - "state": "ignored", - "tracking": "core#96" - } - }, - "version": "5.0", - "versions": { - "changes": [], - "floor": "5.0", - "forward_compatible": false, - "verified_up_to": "5.9" - } - } - ] -} From 31e808ff05632acbfa4f48d208b8d5a2fbca3b0e Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 21:59:31 +0800 Subject: [PATCH 2/2] Point the doc comments at where the goldens now live --- codegen/src/features.rs | 9 +++++---- codegen/src/modules.rs | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/codegen/src/features.rs b/codegen/src/features.rs index ed929d5..e464f61 100644 --- a/codegen/src/features.rs +++ b/codegen/src/features.rs @@ -8,10 +8,11 @@ //! - each generator's claims: a `SUPPORT` table of [`Support`] per feature, //! handed to [`crate::Registry::register`]. //! -//! The claims are proven, not trusted: `comline-conformance` checks every -//! one against the corpus (a supported feature generates and matches its -//! golden; an ignored one generates exactly what it would without it; an -//! unsupported one is refused). The same detector and tables drive the +//! The claims are proven, not trusted: `comline-conformance`'s harness, run by +//! each generator's own suite, checks every one against the corpus (a +//! supported feature generates and matches its golden; an ignored one +//! generates exactly what it would without it; an unsupported one is +//! refused). The same detector and tables drive the //! CLI's pre-generation check, `comline targets --features`, the editor's //! warnings, and the rendered matrix ([`markdown`], [`json`]). diff --git a/codegen/src/modules.rs b/codegen/src/modules.rs index a8fff68..08cf8ac 100644 --- a/codegen/src/modules.rs +++ b/codegen/src/modules.rs @@ -401,9 +401,9 @@ mod tests { /// /// A shared abstraction is only worth having if it reproduces what it /// replaces. These assert the exact layouts the committed conformance -/// goldens hold for the `nested_namespace` fixture — `generation`'s -/// `conformance/tests/golden/nested_namespace/{rust,typescript}/` — so a -/// divergence shows up here rather than as golden drift in another repo. +/// goldens hold for the `nested_namespace` fixture — `comline-rust`'s and +/// `comline-typescript`'s `codegen/tests/golden/nested_namespace//` — +/// so a divergence shows up here rather than as golden drift in another repo. #[cfg(test)] mod parity { use super::tests_support::*;