From 541e8b33fe1bf9e6eb7feecd9ad87b87fa2cdcd1 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 22:02:28 +0800 Subject: [PATCH 1/2] conformance: run the corpus over this generator, against goldens held here comline-conformance's suite that needs a generator moved out of generation, which no longer depends on this repository (generation#159): the protocol round trip, the golden comparison and the proof of every SUPPORT claim run here as codegen/tests/conformance.rs, over generation's corpus and harness. The goldens are generation's own, moved byte-identical (the sha256 of every file is unchanged); nothing was re-blessed. FEATURES.md and features.json are this generator's column of what generation used to write for both. Pins generation at the head of generation#159 until it merges. --- FEATURES.md | 37 ++ README.md | 8 +- codegen/Cargo.toml | 11 +- codegen/tests/conformance.rs | 46 ++ .../tests/golden/bounds/rust/conformance.rs | 188 ++++++ .../tests/golden/chars/rust/conformance.rs | 9 + .../golden/connections/rust/conformance.rs | 250 ++++++++ .../golden/connections/rust/connection.rs | 76 +++ .../connections_async/rust/conformance.rs | 216 +++++++ .../connections_async/rust/connection.rs | 76 +++ .../connections_default/rust/conformance.rs | 261 +++++++++ .../connections_default/rust/connection.rs | 209 +++++++ .../connections_jsonrpc/rust/conformance.rs | 250 ++++++++ .../connections_jsonrpc/rust/connection.rs | 79 +++ .../tests/golden/constant/rust/conformance.rs | 5 + codegen/tests/golden/cross_schema/rust/api.rs | 11 + .../tests/golden/cross_schema/rust/shared.rs | 9 + .../dependency_and_own_protocols/rust/api.rs | 137 +++++ .../rust/connection.rs | 189 ++++++ .../rust/localdeps/greeting.rs | 135 +++++ .../golden/dependency_protocol/rust/api.rs | 9 + .../rust/localdeps/greeting.rs | 140 +++++ .../golden/enum_basic/rust/conformance.rs | 11 + .../golden/error_shapes/rust/conformance.rs | 326 +++++++++++ .../golden/error_shapes/rust/connection.rs | 61 ++ .../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 + .../golden/format_json/rust/conformance.rs | 237 ++++++++ .../golden/format_json/rust/connection.rs | 59 ++ .../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 ++ .../framing_jsonrpc/rust/conformance.rs | 121 ++++ .../handshake_comline2/rust/conformance.rs | 146 +++++ .../handshake_comline2/rust/connection.rs | 189 ++++++ .../golden/handshake_none/rust/conformance.rs | 131 +++++ .../golden/handshake_none/rust/connection.rs | 59 ++ codegen/tests/golden/import_alias/rust/api.rs | 9 + .../tests/golden/import_alias/rust/shared.rs | 9 + codegen/tests/golden/import_glob/rust/api.rs | 9 + .../tests/golden/import_glob/rust/shared.rs | 14 + .../tests/golden/lockstep/rust/conformance.rs | 211 +++++++ .../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 + .../golden/nested_protocol/rust/chat/admin.rs | 137 +++++ .../golden/nested_protocol/rust/connection.rs | 189 ++++++ .../optional_and_arrays/rust/conformance.rs | 12 + .../golden/primitives/rust/conformance.rs | 16 + .../tests/golden/protocol/rust/conformance.rs | 237 ++++++++ .../tests/golden/protocol/rust/connection.rs | 59 ++ .../tests/golden/shapes/rust/conformance.rs | 19 + .../golden/type_refs/rust/conformance.rs | 16 + .../golden/validators/rust/conformance.rs | 301 ++++++++++ .../golden/validators/rust/connection.rs | 59 ++ .../golden/validators/rust/std/validators.rs | 3 + .../validators_on_decode/rust/conformance.rs | 355 ++++++++++++ .../validators_on_decode/rust/connection.rs | 59 ++ .../rust/std/validators.rs | 3 + features.json | 540 ++++++++++++++++++ 65 files changed, 6522 insertions(+), 8 deletions(-) create mode 100644 FEATURES.md create mode 100644 codegen/tests/conformance.rs create mode 100644 codegen/tests/golden/bounds/rust/conformance.rs create mode 100644 codegen/tests/golden/chars/rust/conformance.rs create mode 100644 codegen/tests/golden/connections/rust/conformance.rs create mode 100644 codegen/tests/golden/connections/rust/connection.rs create mode 100644 codegen/tests/golden/connections_async/rust/conformance.rs create mode 100644 codegen/tests/golden/connections_async/rust/connection.rs create mode 100644 codegen/tests/golden/connections_default/rust/conformance.rs create mode 100644 codegen/tests/golden/connections_default/rust/connection.rs create mode 100644 codegen/tests/golden/connections_jsonrpc/rust/conformance.rs create mode 100644 codegen/tests/golden/connections_jsonrpc/rust/connection.rs create mode 100644 codegen/tests/golden/constant/rust/conformance.rs create mode 100644 codegen/tests/golden/cross_schema/rust/api.rs create mode 100644 codegen/tests/golden/cross_schema/rust/shared.rs create mode 100644 codegen/tests/golden/dependency_and_own_protocols/rust/api.rs create mode 100644 codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs create mode 100644 codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs create mode 100644 codegen/tests/golden/dependency_protocol/rust/api.rs create mode 100644 codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs create mode 100644 codegen/tests/golden/enum_basic/rust/conformance.rs create mode 100644 codegen/tests/golden/error_shapes/rust/conformance.rs create mode 100644 codegen/tests/golden/error_shapes/rust/connection.rs create mode 100644 codegen/tests/golden/external_std/rust/Cargo.toml create mode 100644 codegen/tests/golden/external_std/rust/src/api.rs create mode 100644 codegen/tests/golden/external_std/rust/src/lib.rs create mode 100644 codegen/tests/golden/format_json/rust/conformance.rs create mode 100644 codegen/tests/golden/format_json/rust/connection.rs create mode 100644 codegen/tests/golden/format_msgpack/rust/conformance.rs create mode 100644 codegen/tests/golden/format_msgpack/rust/connection.rs create mode 100644 codegen/tests/golden/framing_datagram3/rust/conformance.rs create mode 100644 codegen/tests/golden/framing_datagram3/rust/connection.rs create mode 100644 codegen/tests/golden/framing_jsonrpc/rust/conformance.rs create mode 100644 codegen/tests/golden/handshake_comline2/rust/conformance.rs create mode 100644 codegen/tests/golden/handshake_comline2/rust/connection.rs create mode 100644 codegen/tests/golden/handshake_none/rust/conformance.rs create mode 100644 codegen/tests/golden/handshake_none/rust/connection.rs create mode 100644 codegen/tests/golden/import_alias/rust/api.rs create mode 100644 codegen/tests/golden/import_alias/rust/shared.rs create mode 100644 codegen/tests/golden/import_glob/rust/api.rs create mode 100644 codegen/tests/golden/import_glob/rust/shared.rs create mode 100644 codegen/tests/golden/lockstep/rust/conformance.rs create mode 100644 codegen/tests/golden/nested_namespace/rust/Cargo.toml create mode 100644 codegen/tests/golden/nested_namespace/rust/src/group.rs create mode 100644 codegen/tests/golden/nested_namespace/rust/src/group/first.rs create mode 100644 codegen/tests/golden/nested_namespace/rust/src/group/second.rs create mode 100644 codegen/tests/golden/nested_namespace/rust/src/lib.rs create mode 100644 codegen/tests/golden/nested_namespace/rust/src/top.rs create mode 100644 codegen/tests/golden/nested_protocol/rust/chat/admin.rs create mode 100644 codegen/tests/golden/nested_protocol/rust/connection.rs create mode 100644 codegen/tests/golden/optional_and_arrays/rust/conformance.rs create mode 100644 codegen/tests/golden/primitives/rust/conformance.rs create mode 100644 codegen/tests/golden/protocol/rust/conformance.rs create mode 100644 codegen/tests/golden/protocol/rust/connection.rs create mode 100644 codegen/tests/golden/shapes/rust/conformance.rs create mode 100644 codegen/tests/golden/type_refs/rust/conformance.rs create mode 100644 codegen/tests/golden/validators/rust/conformance.rs create mode 100644 codegen/tests/golden/validators/rust/connection.rs create mode 100644 codegen/tests/golden/validators/rust/std/validators.rs create mode 100644 codegen/tests/golden/validators_on_decode/rust/conformance.rs create mode 100644 codegen/tests/golden/validators_on_decode/rust/connection.rs create mode 100644 codegen/tests/golden/validators_on_decode/rust/std/validators.rs create mode 100644 features.json diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..4e9e17e --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,37 @@ +# Generator features + + + +What the rust 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 | +|---|---| +| structs
`structs` | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +17 more | +| enums
`enums` | ✅ supported
proven by `enum_basic` | +| optional fields
`optional-fields` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +4 more | +| arrays
`arrays` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | +| fixed-length arrays
`fixed-arrays` | ✅ supported
proven by `shapes` | +| 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` | +| unions
`unions` | ❌ unsupported: Rust has no anonymous sum type to render one as
proven by `unions` | +| type aliases
`type-aliases` | ✅ supported
proven by `validators`, `validators_on_decode`, `bounds` | +| constants
`constants` | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | +| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +15 more | +| errors
`errors` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | +| functions that throw
`throws` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | +| validators
`validators` | ✅ supported
proven by `validators`, `validators_on_decode` | +| imports between schemas
`imports` | ✅ 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 | +| `lib` mode
`lib-mode` | ✅ supported
proven by `nested_namespace`, `external_std` | +| `external_std`
`external-std` | ✅ supported
proven by `external_std` | +| `validate_on_decode`
`validate-on-decode` | ✅ supported
proven by `validators_on_decode` | +| JSON-RPC framing
`framing-jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | +| no handshake
`handshake-none` | ✅ supported
proven by `handshake_none` | +| `datagram@3` framing
`framing-datagram3` | ✅ 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 | +| connections
`connections` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +13 more | +| `async`
`async` | ✅ supported
proven by `connections_async` | +| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | +| the `json@1` format
`format-json` | ✅ supported
proven by `format_json` | +| the `msgpack@1` format
`format-msgpack` | ✅ supported
proven by `format_msgpack` | +| bounds
`bounds` | ✅ supported
proven by `bounds` | +| single characters
`chars` | ✅ supported
proven by `chars` | diff --git a/README.md b/README.md index 49afca8..02bd259 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,14 @@ rewrite, not a port. ## Features What this generator implements, feature by feature. Each claim is checked by -the conformance suite in [`ComlineProject/generation`](https://github.com/ComlineProject/generation): +`codegen/tests/conformance.rs`, which runs the conformance corpus of +[`ComlineProject/generation`](https://github.com/ComlineProject/generation) +over this generator, against the goldens in `codegen/tests/golden/`: a supported feature has a fixture that generates and matches its golden output, an ignored one generates exactly what it would without the feature, and an unsupported one is refused with an error naming every use. The full matrix, -with the fixtures that prove each claim, is in -[`FEATURES.md`](https://github.com/ComlineProject/generation/blob/master/FEATURES.md). +with the fixtures that prove each claim, is in [`FEATURES.md`](FEATURES.md) +(also as [`features.json`](features.json)), which that run writes. diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index a0fc43a..7450d1e 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -9,7 +9,7 @@ license = "GPL-3.0-only" # repository structure — no crates.io publishing at this stage). Pinned to the # same generation rev `comline-typescript` uses, so a CLI build has one # `comline-codegen`. Local iteration: add a `[patch]` onto a sibling checkout. -comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "e900919375429591d73c906380f1d354d636ab22" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "31e808ff05632acbfa4f48d208b8d5a2fbca3b0e" } comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922", default-features = false } eyre = "0.6.8" @@ -21,9 +21,10 @@ name = "comline-gen-rust" path = "src/bin/comline-gen-rust.rs" [dev-dependencies] -# The conformance corpus: every fixture is a whole package. Same generation -# rev as `comline-codegen` above, so the corpus and the generator share one -# `comline-codegen`. -comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "e900919375429591d73c906380f1d354d636ab22" } +# The conformance corpus and the harness that runs this generator over it +# (`tests/conformance.rs`, against `tests/golden/`): every fixture is a whole +# package. Same generation rev as `comline-codegen` above, so the corpus and +# the generator share one `comline-codegen`. +comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "31e808ff05632acbfa4f48d208b8d5a2fbca3b0e" } # The tests compile schemas, so they need core's compiler. comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922" } diff --git a/codegen/tests/conformance.rs b/codegen/tests/conformance.rs new file mode 100644 index 0000000..bd36bd9 --- /dev/null +++ b/codegen/tests/conformance.rs @@ -0,0 +1,46 @@ +//! The conformance corpus (`comline-conformance`, in ComlineProject/generation) +//! run over this generator: its output for every fixture, at each of its +//! version boundaries, against the goldens under `tests/golden/`; the +//! generator protocol round trip; and the proof of every claim in `SUPPORT`, +//! with the report `FEATURES.md` and `features.json` at the repository root. +//! Regenerate the goldens and the report with: +//! +//! ```text +//! CONFORMANCE_BLESS=1 cargo test -p comline-codegen-rust --test conformance +//! ``` +//! +//! A blessed golden is a snapshot of what the generator does now: a diff in +//! one is a change to what it emits, to be read as one. + +use std::path::Path; + +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 the_protocol_generates_what_the_generator_does() { + harness::the_protocol_generates_what_the_generator_does(&GENERATOR); +} + +#[test] +fn corpus_matches_golden() { + harness::corpus_matches_golden( + &GENERATOR, + &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"), + ); +} + +#[test] +fn support_is_proven() { + harness::support_is_proven( + &GENERATOR, + &Path::new(env!("CARGO_MANIFEST_DIR")).join(".."), + ); +} diff --git a/codegen/tests/golden/bounds/rust/conformance.rs b/codegen/tests/golden/bounds/rust/conformance.rs new file mode 100644 index 0000000..6360569 --- /dev/null +++ b/codegen/tests/golden/bounds/rust/conformance.rs @@ -0,0 +1,188 @@ +// 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/codegen/tests/golden/chars/rust/conformance.rs b/codegen/tests/golden/chars/rust/conformance.rs new file mode 100644 index 0000000..346a355 --- /dev/null +++ b/codegen/tests/golden/chars/rust/conformance.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/connections/rust/conformance.rs b/codegen/tests/golden/connections/rust/conformance.rs new file mode 100644 index 0000000..b5e3fc2 --- /dev/null +++ b/codegen/tests/golden/connections/rust/conformance.rs @@ -0,0 +1,250 @@ +// 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/codegen/tests/golden/connections/rust/connection.rs b/codegen/tests/golden/connections/rust/connection.rs new file mode 100644 index 0000000..071340b --- /dev/null +++ b/codegen/tests/golden/connections/rust/connection.rs @@ -0,0 +1,76 @@ +// 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/codegen/tests/golden/connections_async/rust/conformance.rs b/codegen/tests/golden/connections_async/rust/conformance.rs new file mode 100644 index 0000000..11b4f9b --- /dev/null +++ b/codegen/tests/golden/connections_async/rust/conformance.rs @@ -0,0 +1,216 @@ +// 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/codegen/tests/golden/connections_async/rust/connection.rs b/codegen/tests/golden/connections_async/rust/connection.rs new file mode 100644 index 0000000..f130cbd --- /dev/null +++ b/codegen/tests/golden/connections_async/rust/connection.rs @@ -0,0 +1,76 @@ +// 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/codegen/tests/golden/connections_default/rust/conformance.rs b/codegen/tests/golden/connections_default/rust/conformance.rs new file mode 100644 index 0000000..a6aa6f7 --- /dev/null +++ b/codegen/tests/golden/connections_default/rust/conformance.rs @@ -0,0 +1,261 @@ +// 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/codegen/tests/golden/connections_default/rust/connection.rs b/codegen/tests/golden/connections_default/rust/connection.rs new file mode 100644 index 0000000..0550366 --- /dev/null +++ b/codegen/tests/golden/connections_default/rust/connection.rs @@ -0,0 +1,209 @@ +// 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/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs b/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs new file mode 100644 index 0000000..a9f2e75 --- /dev/null +++ b/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs @@ -0,0 +1,250 @@ +// 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/codegen/tests/golden/connections_jsonrpc/rust/connection.rs b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs new file mode 100644 index 0000000..3c96bb7 --- /dev/null +++ b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs @@ -0,0 +1,79 @@ +// 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/codegen/tests/golden/constant/rust/conformance.rs b/codegen/tests/golden/constant/rust/conformance.rs new file mode 100644 index 0000000..9381954 --- /dev/null +++ b/codegen/tests/golden/constant/rust/conformance.rs @@ -0,0 +1,5 @@ +// Generated by Comline +// For Rust 1.85.0 or later; verified up to 1.99. + +pub const MAX_RETRIES: u8 = 5; + diff --git a/codegen/tests/golden/cross_schema/rust/api.rs b/codegen/tests/golden/cross_schema/rust/api.rs new file mode 100644 index 0000000..140cb68 --- /dev/null +++ b/codegen/tests/golden/cross_schema/rust/api.rs @@ -0,0 +1,11 @@ +// 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/codegen/tests/golden/cross_schema/rust/shared.rs b/codegen/tests/golden/cross_schema/rust/shared.rs new file mode 100644 index 0000000..598eca1 --- /dev/null +++ b/codegen/tests/golden/cross_schema/rust/shared.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs new file mode 100644 index 0000000..80d4d08 --- /dev/null +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs @@ -0,0 +1,137 @@ +// 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/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs new file mode 100644 index 0000000..bbeb477 --- /dev/null +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs @@ -0,0 +1,189 @@ +// 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/codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs new file mode 100644 index 0000000..7a4d6a7 --- /dev/null +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs @@ -0,0 +1,135 @@ +// 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/codegen/tests/golden/dependency_protocol/rust/api.rs b/codegen/tests/golden/dependency_protocol/rust/api.rs new file mode 100644 index 0000000..a2edfbe --- /dev/null +++ b/codegen/tests/golden/dependency_protocol/rust/api.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs b/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs new file mode 100644 index 0000000..3c3caae --- /dev/null +++ b/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs @@ -0,0 +1,140 @@ +// 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/codegen/tests/golden/enum_basic/rust/conformance.rs b/codegen/tests/golden/enum_basic/rust/conformance.rs new file mode 100644 index 0000000..3a3ba14 --- /dev/null +++ b/codegen/tests/golden/enum_basic/rust/conformance.rs @@ -0,0 +1,11 @@ +// 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/codegen/tests/golden/error_shapes/rust/conformance.rs b/codegen/tests/golden/error_shapes/rust/conformance.rs new file mode 100644 index 0000000..6fe443c --- /dev/null +++ b/codegen/tests/golden/error_shapes/rust/conformance.rs @@ -0,0 +1,326 @@ +// 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/codegen/tests/golden/error_shapes/rust/connection.rs b/codegen/tests/golden/error_shapes/rust/connection.rs new file mode 100644 index 0000000..e8569c2 --- /dev/null +++ b/codegen/tests/golden/error_shapes/rust/connection.rs @@ -0,0 +1,61 @@ +// 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/codegen/tests/golden/external_std/rust/Cargo.toml b/codegen/tests/golden/external_std/rust/Cargo.toml new file mode 100644 index 0000000..9957879 --- /dev/null +++ b/codegen/tests/golden/external_std/rust/Cargo.toml @@ -0,0 +1,15 @@ +# 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/codegen/tests/golden/external_std/rust/src/api.rs b/codegen/tests/golden/external_std/rust/src/api.rs new file mode 100644 index 0000000..77c7416 --- /dev/null +++ b/codegen/tests/golden/external_std/rust/src/api.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/external_std/rust/src/lib.rs b/codegen/tests/golden/external_std/rust/src/lib.rs new file mode 100644 index 0000000..45b4e44 --- /dev/null +++ b/codegen/tests/golden/external_std/rust/src/lib.rs @@ -0,0 +1,5 @@ +// 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/codegen/tests/golden/format_json/rust/conformance.rs b/codegen/tests/golden/format_json/rust/conformance.rs new file mode 100644 index 0000000..ace4801 --- /dev/null +++ b/codegen/tests/golden/format_json/rust/conformance.rs @@ -0,0 +1,237 @@ +// 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/codegen/tests/golden/format_json/rust/connection.rs b/codegen/tests/golden/format_json/rust/connection.rs new file mode 100644 index 0000000..327827b --- /dev/null +++ b/codegen/tests/golden/format_json/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/format_msgpack/rust/conformance.rs b/codegen/tests/golden/format_msgpack/rust/conformance.rs new file mode 100644 index 0000000..ace4801 --- /dev/null +++ b/codegen/tests/golden/format_msgpack/rust/conformance.rs @@ -0,0 +1,237 @@ +// 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/codegen/tests/golden/format_msgpack/rust/connection.rs b/codegen/tests/golden/format_msgpack/rust/connection.rs new file mode 100644 index 0000000..9c2f825 --- /dev/null +++ b/codegen/tests/golden/format_msgpack/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/framing_datagram3/rust/conformance.rs b/codegen/tests/golden/framing_datagram3/rust/conformance.rs new file mode 100644 index 0000000..3094b8a --- /dev/null +++ b/codegen/tests/golden/framing_datagram3/rust/conformance.rs @@ -0,0 +1,144 @@ +// 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/codegen/tests/golden/framing_datagram3/rust/connection.rs b/codegen/tests/golden/framing_datagram3/rust/connection.rs new file mode 100644 index 0000000..a73dbda --- /dev/null +++ b/codegen/tests/golden/framing_datagram3/rust/connection.rs @@ -0,0 +1,62 @@ +// 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/codegen/tests/golden/framing_jsonrpc/rust/conformance.rs b/codegen/tests/golden/framing_jsonrpc/rust/conformance.rs new file mode 100644 index 0000000..55c8e66 --- /dev/null +++ b/codegen/tests/golden/framing_jsonrpc/rust/conformance.rs @@ -0,0 +1,121 @@ +// 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/codegen/tests/golden/handshake_comline2/rust/conformance.rs b/codegen/tests/golden/handshake_comline2/rust/conformance.rs new file mode 100644 index 0000000..81c80c2 --- /dev/null +++ b/codegen/tests/golden/handshake_comline2/rust/conformance.rs @@ -0,0 +1,146 @@ +// 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/codegen/tests/golden/handshake_comline2/rust/connection.rs b/codegen/tests/golden/handshake_comline2/rust/connection.rs new file mode 100644 index 0000000..9971097 --- /dev/null +++ b/codegen/tests/golden/handshake_comline2/rust/connection.rs @@ -0,0 +1,189 @@ +// 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/codegen/tests/golden/handshake_none/rust/conformance.rs b/codegen/tests/golden/handshake_none/rust/conformance.rs new file mode 100644 index 0000000..7eb2cb6 --- /dev/null +++ b/codegen/tests/golden/handshake_none/rust/conformance.rs @@ -0,0 +1,131 @@ +// 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/codegen/tests/golden/handshake_none/rust/connection.rs b/codegen/tests/golden/handshake_none/rust/connection.rs new file mode 100644 index 0000000..641f30c --- /dev/null +++ b/codegen/tests/golden/handshake_none/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/import_alias/rust/api.rs b/codegen/tests/golden/import_alias/rust/api.rs new file mode 100644 index 0000000..5311a62 --- /dev/null +++ b/codegen/tests/golden/import_alias/rust/api.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/import_alias/rust/shared.rs b/codegen/tests/golden/import_alias/rust/shared.rs new file mode 100644 index 0000000..598eca1 --- /dev/null +++ b/codegen/tests/golden/import_alias/rust/shared.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/import_glob/rust/api.rs b/codegen/tests/golden/import_glob/rust/api.rs new file mode 100644 index 0000000..5311a62 --- /dev/null +++ b/codegen/tests/golden/import_glob/rust/api.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/import_glob/rust/shared.rs b/codegen/tests/golden/import_glob/rust/shared.rs new file mode 100644 index 0000000..3d5c083 --- /dev/null +++ b/codegen/tests/golden/import_glob/rust/shared.rs @@ -0,0 +1,14 @@ +// 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/codegen/tests/golden/lockstep/rust/conformance.rs b/codegen/tests/golden/lockstep/rust/conformance.rs new file mode 100644 index 0000000..c66f197 --- /dev/null +++ b/codegen/tests/golden/lockstep/rust/conformance.rs @@ -0,0 +1,211 @@ +// 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/codegen/tests/golden/nested_namespace/rust/Cargo.toml b/codegen/tests/golden/nested_namespace/rust/Cargo.toml new file mode 100644 index 0000000..b71c780 --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/Cargo.toml @@ -0,0 +1,14 @@ +# 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/codegen/tests/golden/nested_namespace/rust/src/group.rs b/codegen/tests/golden/nested_namespace/rust/src/group.rs new file mode 100644 index 0000000..72e282f --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/src/group.rs @@ -0,0 +1,4 @@ +// Generated by Comline + +pub mod first; +pub mod second; diff --git a/codegen/tests/golden/nested_namespace/rust/src/group/first.rs b/codegen/tests/golden/nested_namespace/rust/src/group/first.rs new file mode 100644 index 0000000..2dc4da7 --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/src/group/first.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/nested_namespace/rust/src/group/second.rs b/codegen/tests/golden/nested_namespace/rust/src/group/second.rs new file mode 100644 index 0000000..b744697 --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/src/group/second.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/nested_namespace/rust/src/lib.rs b/codegen/tests/golden/nested_namespace/rust/src/lib.rs new file mode 100644 index 0000000..76d0aa5 --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/src/lib.rs @@ -0,0 +1,6 @@ +// 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/codegen/tests/golden/nested_namespace/rust/src/top.rs b/codegen/tests/golden/nested_namespace/rust/src/top.rs new file mode 100644 index 0000000..1e9bc11 --- /dev/null +++ b/codegen/tests/golden/nested_namespace/rust/src/top.rs @@ -0,0 +1,9 @@ +// 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/codegen/tests/golden/nested_protocol/rust/chat/admin.rs b/codegen/tests/golden/nested_protocol/rust/chat/admin.rs new file mode 100644 index 0000000..7e3beac --- /dev/null +++ b/codegen/tests/golden/nested_protocol/rust/chat/admin.rs @@ -0,0 +1,137 @@ +// 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/codegen/tests/golden/nested_protocol/rust/connection.rs b/codegen/tests/golden/nested_protocol/rust/connection.rs new file mode 100644 index 0000000..2e6af9c --- /dev/null +++ b/codegen/tests/golden/nested_protocol/rust/connection.rs @@ -0,0 +1,189 @@ +// 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/codegen/tests/golden/optional_and_arrays/rust/conformance.rs b/codegen/tests/golden/optional_and_arrays/rust/conformance.rs new file mode 100644 index 0000000..c71626f --- /dev/null +++ b/codegen/tests/golden/optional_and_arrays/rust/conformance.rs @@ -0,0 +1,12 @@ +// 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/codegen/tests/golden/primitives/rust/conformance.rs b/codegen/tests/golden/primitives/rust/conformance.rs new file mode 100644 index 0000000..b39b390 --- /dev/null +++ b/codegen/tests/golden/primitives/rust/conformance.rs @@ -0,0 +1,16 @@ +// 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/codegen/tests/golden/protocol/rust/conformance.rs b/codegen/tests/golden/protocol/rust/conformance.rs new file mode 100644 index 0000000..ace4801 --- /dev/null +++ b/codegen/tests/golden/protocol/rust/conformance.rs @@ -0,0 +1,237 @@ +// 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/codegen/tests/golden/protocol/rust/connection.rs b/codegen/tests/golden/protocol/rust/connection.rs new file mode 100644 index 0000000..db67fce --- /dev/null +++ b/codegen/tests/golden/protocol/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/shapes/rust/conformance.rs b/codegen/tests/golden/shapes/rust/conformance.rs new file mode 100644 index 0000000..9a66b84 --- /dev/null +++ b/codegen/tests/golden/shapes/rust/conformance.rs @@ -0,0 +1,19 @@ +// 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/codegen/tests/golden/type_refs/rust/conformance.rs b/codegen/tests/golden/type_refs/rust/conformance.rs new file mode 100644 index 0000000..2d85d33 --- /dev/null +++ b/codegen/tests/golden/type_refs/rust/conformance.rs @@ -0,0 +1,16 @@ +// 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/codegen/tests/golden/validators/rust/conformance.rs b/codegen/tests/golden/validators/rust/conformance.rs new file mode 100644 index 0000000..d4ff3c3 --- /dev/null +++ b/codegen/tests/golden/validators/rust/conformance.rs @@ -0,0 +1,301 @@ +// 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/codegen/tests/golden/validators/rust/connection.rs b/codegen/tests/golden/validators/rust/connection.rs new file mode 100644 index 0000000..fb3ce3a --- /dev/null +++ b/codegen/tests/golden/validators/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/validators/rust/std/validators.rs b/codegen/tests/golden/validators/rust/std/validators.rs new file mode 100644 index 0000000..3202fde --- /dev/null +++ b/codegen/tests/golden/validators/rust/std/validators.rs @@ -0,0 +1,3 @@ +// Generated by Comline +// For Rust 1.85.0 or later; verified up to 1.99. + diff --git a/codegen/tests/golden/validators_on_decode/rust/conformance.rs b/codegen/tests/golden/validators_on_decode/rust/conformance.rs new file mode 100644 index 0000000..0b4bf93 --- /dev/null +++ b/codegen/tests/golden/validators_on_decode/rust/conformance.rs @@ -0,0 +1,355 @@ +// 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/codegen/tests/golden/validators_on_decode/rust/connection.rs b/codegen/tests/golden/validators_on_decode/rust/connection.rs new file mode 100644 index 0000000..fb3ce3a --- /dev/null +++ b/codegen/tests/golden/validators_on_decode/rust/connection.rs @@ -0,0 +1,59 @@ +// 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/codegen/tests/golden/validators_on_decode/rust/std/validators.rs b/codegen/tests/golden/validators_on_decode/rust/std/validators.rs new file mode 100644 index 0000000..3202fde --- /dev/null +++ b/codegen/tests/golden/validators_on_decode/rust/std/validators.rs @@ -0,0 +1,3 @@ +// Generated by Comline +// For Rust 1.85.0 or later; verified up to 1.99. + diff --git a/features.json b/features.json new file mode 100644 index 0000000..9743a19 --- /dev/null +++ b/features.json @@ -0,0 +1,540 @@ +{ + "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" + } + } + ] +} From 0a99651109e20d06e1a6d7bb4d94be438010704e Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 22:14:07 +0800 Subject: [PATCH 2/2] xtask: pin generation at the same rev as the generator --- xtask/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 722e8e5..38d1544 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -8,7 +8,7 @@ publish = false # Same rev `codegen` pins, so this tool and the generator it drives agree on # one `comline-core` - see codegen/Cargo.toml's own comment. comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922" } -comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "e900919375429591d73c906380f1d354d636ab22" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "31e808ff05632acbfa4f48d208b8d5a2fbca3b0e" } comline-codegen-rust = { path = "../codegen" } eyre = "0.6.8"