diff --git a/FEATURES.md b/FEATURES.md index 5433939..e513b76 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -6,18 +6,18 @@ What each generator implements, and the conformance fixtures that prove it. A cl | Feature | rust ≥ 1.85.0 | typescript ≥ 5.0 | |---|---|---| -| structs
`structs` | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +16 more | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +17 more | +| structs
`structs` | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +17 more | ✅ supported
proven by `primitives`, `optional_and_arrays`, `type_refs` +18 more | | enums
`enums` | ✅ supported
proven by `enum_basic` | ✅ supported
proven by `enum_basic` | | optional fields
`optional-fields` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +4 more | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | -| arrays
`arrays` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +4 more | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | +| arrays
`arrays` | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +5 more | ✅ supported
proven by `optional_and_arrays`, `type_refs`, `shapes` +6 more | | fixed-length arrays
`fixed-arrays` | ✅ supported
proven by `shapes` | 🟡 partial: rendered as `T[]`: the length isn't part of the type
proven by `shapes`, `large_fixed_arrays_nested` | | fixed arrays over 32 elements, nested
`large-fixed-arrays-nested` | ❌ unsupported: a fixed array over 32 elements renders only as a struct or error field's own, non-optional type (serde's derive stops at 32)
proven by `large_fixed_arrays_nested` | 🟡 partial: rendered as `T[]`: the length isn't part of the type
proven by `large_fixed_arrays_nested` | | unions
`unions` | ❌ unsupported: Rust has no anonymous sum type to render one as
proven by `unions` | ✅ supported
proven by `unions` | | type aliases
`type-aliases` | ✅ supported
proven by `validators`, `validators_on_decode`, `bounds` | ✅ supported
proven by `validators`, `validators_on_decode`, `unions` +1 more | | constants
`constants` | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | -| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +13 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +12 more | -| errors
`errors` | ✅ supported
proven by `protocol`, `error_shapes`, `format_json` +1 more | ✅ supported
proven by `protocol`, `error_shapes`, `format_json` | -| functions that throw
`throws` | ✅ supported
proven by `protocol`, `error_shapes`, `format_json` +1 more | ✅ supported
proven by `protocol`, `error_shapes`, `format_json` | +| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +15 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +14 more | +| errors
`errors` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | +| functions that throw
`throws` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +2 more | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | | validators
`validators` | ✅ supported
proven by `validators`, `validators_on_decode` | ⚪ ignored: the types are generated; the checks aren't run yet (core#96)
proven by `validators`, `validators_on_decode` | | imports between schemas
`imports` | ✅ supported
proven by `cross_schema`, `import_alias`, `import_glob` +6 more | ✅ supported
proven by `cross_schema`, `import_alias`, `import_glob` +6 more | | nested namespaces
`nested-namespaces` | ✅ supported
proven by `nested_namespace`, `external_std`, `validators` +4 more | ✅ supported
proven by `nested_namespace`, `external_std`, `validators` +4 more | @@ -26,11 +26,11 @@ What each generator implements, and the conformance fixtures that prove it. A cl | `validate_on_decode`
`validate-on-decode` | ✅ supported
proven by `validators_on_decode` | ⚪ ignored: no checks are generated to run on decode yet (core#96)
proven by `validators_on_decode` | | JSON-RPC framing
`framing-jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | | no handshake
`handshake-none` | ✅ supported
proven by `handshake_none` | ✅ supported
proven by `handshake_none` | -| `datagram@3` framing
`framing-datagram3` | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `dependency_protocol` +2 more | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `dependency_protocol` +2 more | -| `comline@2` handshake
`handshake-comline2` | ✅ supported
proven by `handshake_comline2`, `dependency_protocol`, `dependency_and_own_protocols` +1 more | ✅ supported
proven by `handshake_comline2`, `dependency_protocol`, `dependency_and_own_protocols` +1 more | -| connections
`connections` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +12 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | +| `datagram@3` framing
`framing-datagram3` | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +3 more | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +3 more | +| `comline@2` handshake
`handshake-comline2` | ✅ supported
proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +2 more | ✅ supported
proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +2 more | +| connections
`connections` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +13 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +12 more | | `async`
`async` | ✅ supported
proven by `connections_async` | ⚪ ignored: handlers and senders always return Promises: the output is async either way
proven by `connections_async` | -| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +9 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +9 more | +| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | | the `json@1` format
`format-json` | ✅ supported
proven by `format_json` | ✅ supported
proven by `format_json` | | the `msgpack@1` format
`format-msgpack` | ✅ supported
proven by `format_msgpack` | ❌ unsupported: `@comline/runtime` has no MessagePack codec yet
proven by `format_msgpack` | | bounds
`bounds` | ✅ supported
proven by `bounds` | ✅ supported
proven by `bounds` | diff --git a/conformance/src/lib.rs b/conformance/src/lib.rs index f64b7ae..19805f7 100644 --- a/conformance/src/lib.rs +++ b/conformance/src/lib.rs @@ -130,9 +130,11 @@ pub fn corpus() -> Vec { handshake_none(), framing_datagram3(), handshake_comline2(), + lockstep(), connections(), connections_async(), connections_jsonrpc(), + connections_default(), format_json(), format_msgpack(), bounds(), @@ -1029,6 +1031,45 @@ fn handshake_none() -> Fixture { ) } +/// The Protocols guide's `Mail`, on the lockstep `datagram` framing (no +/// version), which gets a `Dispatcher` and a `Client`: a +/// function that returns a string and throws, with a call +/// timeout, and one that returns an array. +fn lockstep() -> Fixture { + let send_message = FrozenUnit::Function { + docstring: String::new(), + parameters: vec![FrozenUnit::Property { name: "timeout_ms".to_string(), value: ConfigValue::Integer(1000) }], + name: "send_message".to_string(), + arguments: vec![FrozenArgument { + name: "message".to_string(), + ty: type_of("Message"), + span: (0, 0), + parameters: vec![], + }], + _return: Some(type_of("string")), + throws: vec![0], + span: (0, 0), + }; + Fixture::one( + "lockstep", + "conformance", + vec![ + structure("Message", vec![field("body", "string", false)]), + error(0, "RecipientNotFound"), + FrozenUnit::Protocol { + docstring: "Lockstep".to_string(), + parameters: vec![FrozenUnit::Property { + name: "framing".to_string(), + value: ConfigValue::Str("datagram".to_string()), + }], + name: "Mail".to_string(), + functions: vec![send_message, function("fetch_inbox", vec![], Some("Message[]"), vec![])], + span: (0, 0), + }, + ], + ) +} + /// Two protocols on one connection: `Chat`, which the accepting side /// provides over `datagram@2`, and `Events`, which the dialling side does. /// `connections`, with `async`: the same protocols, generated for an async @@ -1100,6 +1141,48 @@ fn connections() -> Fixture { ) } +/// [`connections`] under the defaults core writes into a protocol, `datagram@3` +/// and `comline@2`: the server's `Services`, the client's `ClientServices`, and +/// the handshake between them. +fn connections_default() -> Fixture { + let defaults = || { + vec![ + FrozenUnit::Property { name: "framing".to_string(), value: ConfigValue::Str("datagram@3".to_string()) }, + FrozenUnit::Property { name: "handshake".to_string(), value: ConfigValue::Str("comline@2".to_string()) }, + ] + }; + Fixture::one( + "connections_default", + "conformance", + vec![ + FrozenUnit::Protocol { + docstring: "What the server provides".to_string(), + parameters: defaults(), + name: "Chat".to_string(), + functions: vec![function("send", vec![arg("n", PrimitiveType::U32)], Some("u32"), vec![])], + span: (0, 0), + }, + FrozenUnit::Protocol { + docstring: "What the client provides".to_string(), + parameters: [ + vec![FrozenUnit::Property { + name: "provider".to_string(), + value: ConfigValue::Name("Client".to_string()), + }], + defaults(), + ] + .concat(), + name: "Events".to_string(), + functions: vec![ + function("shown", vec![arg("n", PrimitiveType::U32)], Some("bool"), vec![]), + function("ping", vec![], None, vec![]), + ], + span: (0, 0), + }, + ], + ) +} + /// [`protocol`] under `wire.format = "json@1"`. fn format_json() -> Fixture { Fixture { name: "format_json", ..protocol() }.with_format("json@1") diff --git a/conformance/tests/golden/connections_default/rust/conformance.rs b/conformance/tests/golden/connections_default/rust/conformance.rs new file mode 100644 index 0000000..a6aa6f7 --- /dev/null +++ b/conformance/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/conformance/tests/golden/connections_default/rust/connection.rs b/conformance/tests/golden/connections_default/rust/connection.rs new file mode 100644 index 0000000..0550366 --- /dev/null +++ b/conformance/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/conformance/tests/golden/connections_default/typescript/conformance.ts b/conformance/tests/golden/connections_default/typescript/conformance.ts new file mode 100644 index 0000000..6e963a2 --- /dev/null +++ b/conformance/tests/golden/connections_default/typescript/conformance.ts @@ -0,0 +1,188 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0x1ad273c98d4e98fbn; + +export interface ChatSendParams { + n: number; +} + +/** @internal */ +export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Chat { + send(peer: Peer, params: ChatSendParams): Promise; +} + +/** @internal */ +export const CHAT_CALLS = ["send"] as const; + +/** @internal */ +export class ChatDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Chat; + + constructor(impl: Chat) { + this.impl = impl; + } + + calls(): readonly string[] { + return CHAT_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, ChatSendParamsLayout); + reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(ChatDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class ChatSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async send(params: ChatSendParams): Promise { + checkCall(this.peer, ChatSender.PROTOCOL, 0, "conformance::Chat", "send"); + const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + +export interface EventsShownParams { + n: number; +} + +/** @internal */ +export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Events { + shown(peer: Peer, params: EventsShownParams): Promise; + ping(peer: Peer): Promise; +} + +/** @internal */ +export const EVENTS_CALLS = ["shown", "ping"] as const; + +/** @internal */ +export class EventsDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly impl: Events; + + constructor(impl: Events) { + this.impl = impl; + } + + calls(): readonly string[] { + return EVENTS_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 1: { + try { + const p = codec.decode(params, EventsShownParamsLayout); + reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); + } catch { + reply.fault(); + } + return; + } + case 0: { + try { + await this.impl.ping(peer); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(EventsDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class EventsSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async shown(params: EventsShownParams): Promise { + checkCall(this.peer, EventsSender.PROTOCOL, 1, "conformance::Events", "shown"); + const env = await this.peer.call(EventsSender.PROTOCOL, { id: 1, name: "shown" }, params, { layout: EventsShownParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } + + async ping(): Promise { + checkCall(this.peer, EventsSender.PROTOCOL, 0, "conformance::Events", "ping"); + await this.peer.notify(EventsSender.PROTOCOL, { id: 0, name: "ping" }, null, { layout: "unit" }); + } +} + diff --git a/conformance/tests/golden/connections_default/typescript/connection.ts b/conformance/tests/golden/connections_default/typescript/connection.ts new file mode 100644 index 0000000..64218a9 --- /dev/null +++ b/conformance/tests/golden/connections_default/typescript/connection.ts @@ -0,0 +1,137 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events })`. + * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + Datagram3Framing, + Comline2Handshake, + Negotiated, + type Peer, + type Transport, +} from "@comline/runtime"; +import * as ns_conformance from "./conformance.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** + * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history + * records it. Its protocols, by wire number: + * + * - 0 `conformance::Chat`, line 0.1.0: `send` 0 + * - 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0 + * + * @internal + */ +export const HELLO = new Uint8Array([ + 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, + 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, + 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, + 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, + 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, + 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x02, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x02, 0x00, 0x01, +]); + +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ +export function handshake(): Comline2Handshake { + return new Comline2Handshake(HELLO, { + scope: "protocol", + newerConsumer: "degrade", + sameVersionDiffers: "refuse", + exchange: "offer", + }); +} + +/** The package's protocols on the connection, by wire number. */ +const PROTOCOLS = new Map([[0, "conformance::Chat"], [1, "conformance::Events"]]); + +/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ +export function negotiated(conn: Peer): Negotiated | undefined { + return conn.extensions.get(Negotiated); +} + +/** + * The protocols that connected although their wire shape differs from the + * peer's at the same version (`same_version_differs = warn`), by path. + */ +export function warnings(conn: Peer): string[] { + return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); +} + +/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface Services { + chat: ns_conformance.Chat; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); +} + +/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface ClientServices { + events: ns_conformance.Events; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideClientServices(conn: Connection, services: ClientServices): void { + new ns_conformance.EventsDispatcher(services.events).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* every protocol in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const agreed = handshake(); + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake, then provide every protocol in +* `services`, which the server calls. Call the server's protocols through +* their senders. +*/ +export async function connect(transport: Transport, services: ClientServices): Promise { + const agreed = handshake(); + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideClientServices(conn, services); + return conn; +} diff --git a/conformance/tests/golden/connections_default/typescript/wire.ts b/conformance/tests/golden/connections_default/typescript/wire.ts new file mode 100644 index 0000000..7629bc6 --- /dev/null +++ b/conformance/tests/golden/connections_default/typescript/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x1ad273c98d4e98fbn; diff --git a/conformance/tests/golden/lockstep/rust/conformance.rs b/conformance/tests/golden/lockstep/rust/conformance.rs new file mode 100644 index 0000000..c66f197 --- /dev/null +++ b/conformance/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/conformance/tests/golden/lockstep/typescript/conformance.ts b/conformance/tests/golden/lockstep/typescript/conformance.ts new file mode 100644 index 0000000..e180ea8 --- /dev/null +++ b/conformance/tests/golden/lockstep/typescript/conformance.ts @@ -0,0 +1,136 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + Client, + Server, + RuntimeError, + resolveKind, + DatagramFraming, + PackedCodec, + type Codec, + type Dispatch, + type Framing, + type Kind, + type Layout, + type Reply, + type Transport, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0x7ea94b595fcf4393n; + +/** The package's wire format (`wire.format`): what this file's helpers +* encode with, and what the peer has to speak too. */ +export const Format: Codec = new PackedCodec(); + +export interface Message { + body: string; +} + +export const MessageLayout: Layout = { struct: [["body", "string"]] }; + +export interface RecipientNotFound { +} + +export const RecipientNotFoundLayout: Layout = { struct: [] }; + +export class RecipientNotFoundError extends Error { + static readonly ordinal = 0; + readonly data: RecipientNotFound; + constructor(data: RecipientNotFound) { + super("RecipientNotFound"); + this.data = data; + this.name = "RecipientNotFoundError"; + } +} + +export interface MailSendMessageParams { + message: Message; +} + +/** @internal */ +export const MailSendMessageParamsLayout: Layout = { struct: [["message", () => MessageLayout]] }; + +export interface Mail { + /** @throws {RecipientNotFoundError} */ + send_message(params: MailSendMessageParams): Promise; + fetch_inbox(): Promise; +} + +/** @internal */ +export const MAIL_CALLS = ["send_message", "fetch_inbox"] as const; + +export class MailDispatcher implements Dispatch { + private readonly impl: Mail; + + constructor(impl: Mail) { + this.impl = impl; + } + + calls(): readonly string[] { + return MAIL_CALLS; + } + + async dispatch(call: Kind, params: Uint8Array, codec: Codec, reply: Reply): Promise { + switch (resolveKind(call, MAIL_CALLS)) { + case 0: { + try { + const p = codec.decode(params, MailSendMessageParamsLayout); + reply.ok(codec.encode((await this.impl.send_message(p)) ?? null, "string")); + } catch (e) { + if (e instanceof RecipientNotFoundError) { reply.err(RecipientNotFoundError.ordinal, codec.encode(e.data, RecipientNotFoundLayout)); return; } + reply.fault(); + } + return; + } + case 1: { + try { + reply.ok(codec.encode((await this.impl.fetch_inbox()) ?? null, { array: MessageLayout })); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } +} + +export class MailClient { + private readonly client: Client; + + constructor(client: Client) { + this.client = client; + } + + static async connect(transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { + return new MailClient(await Client.connect(transport, codec, IR_HASH, framing)); + } + + async send_message(params: MailSendMessageParams): Promise { + const env = await this.client.call({ id: 0, name: "send_message" }, params, { layout: MailSendMessageParamsLayout }); + if ("ok" in env) return this.client.codec.decode(env.ok, "string"); + if ("fault" in env) throw RuntimeError.provider(); + switch (env.err.id) { + case RecipientNotFoundError.ordinal: + throw new RecipientNotFoundError(this.client.codec.decode(env.err.body, RecipientNotFoundLayout)); + default: + throw RuntimeError.remote(env.err.id); + } + } + + async fetch_inbox(): Promise { + const env = await this.client.call({ id: 1, name: "fetch_inbox" }, null, { layout: "unit" }); + if ("ok" in env) return this.client.codec.decode(env.ok, { array: MessageLayout }); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + +export function serveMail(impl: Mail, transport: Transport, codec: Codec = Format, framing: Framing = new DatagramFraming()): Promise { + return new Server(new MailDispatcher(impl), codec, framing).serve(transport, IR_HASH); +} + diff --git a/features.json b/features.json index ea2a04c..d037fb4 100644 --- a/features.json +++ b/features.json @@ -159,6 +159,7 @@ "cross_schema", "validators", "validators_on_decode", + "lockstep", "bounds" ], "since": null, @@ -205,6 +206,7 @@ "connections", "connections_async", "connections_jsonrpc", + "connections_default", "format_json", "format_msgpack", "dependency_protocol", @@ -241,6 +243,7 @@ "proven_by": [ "protocol", "error_shapes", + "lockstep", "format_json", "format_msgpack" ], @@ -294,8 +297,10 @@ "handshake_none", "framing_datagram3", "handshake_comline2", + "lockstep", "connections", "connections_async", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -309,6 +314,7 @@ "proven_by": [ "framing_datagram3", "handshake_comline2", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -331,6 +337,7 @@ "note": null, "proven_by": [ "handshake_comline2", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -425,9 +432,11 @@ "handshake_none", "framing_datagram3", "handshake_comline2", + "lockstep", "connections", "connections_async", "connections_jsonrpc", + "connections_default", "format_json", "format_msgpack", "dependency_protocol", @@ -453,6 +462,7 @@ "external_std", "validators", "validators_on_decode", + "lockstep", "format_json", "format_msgpack", "bounds", @@ -470,6 +480,7 @@ "proven_by": [ "protocol", "error_shapes", + "lockstep", "format_json", "format_msgpack" ], @@ -538,6 +549,7 @@ "validators", "validators_on_decode", "large_fixed_arrays_nested", + "lockstep", "bounds" ], "since": null, @@ -584,6 +596,7 @@ "connections", "connections_async", "connections_jsonrpc", + "connections_default", "format_json", "dependency_protocol", "dependency_and_own_protocols", @@ -619,6 +632,7 @@ "proven_by": [ "protocol", "error_shapes", + "lockstep", "format_json" ], "since": null, @@ -672,8 +686,10 @@ "handshake_none", "framing_datagram3", "handshake_comline2", + "lockstep", "connections", "connections_async", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -687,6 +703,7 @@ "proven_by": [ "framing_datagram3", "handshake_comline2", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -709,6 +726,7 @@ "note": null, "proven_by": [ "handshake_comline2", + "connections_default", "dependency_protocol", "dependency_and_own_protocols", "nested_protocol" @@ -804,9 +822,11 @@ "handshake_none", "framing_datagram3", "handshake_comline2", + "lockstep", "connections", "connections_async", "connections_jsonrpc", + "connections_default", "format_json", "dependency_protocol", "dependency_and_own_protocols", @@ -833,6 +853,7 @@ "validators_on_decode", "unions", "large_fixed_arrays_nested", + "lockstep", "format_json", "bounds", "chars", @@ -849,6 +870,7 @@ "proven_by": [ "protocol", "error_shapes", + "lockstep", "format_json" ], "since": null,