diff --git a/FEATURES.md b/FEATURES.md index 4e9e17e..603c785 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -15,22 +15,22 @@ What the rust generator implements, and the conformance fixtures that prove it. | 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 | +| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +16 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 | +| nested namespaces
`nested-namespaces` | ✅ supported
proven by `nested_namespace`, `external_std`, `validators` +5 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 | +| `datagram@3` framing
`framing-datagram3` | ✅ supported
proven by `framing_datagram3`, `handshake_comline2`, `connections_default` +4 more | +| `comline@2` handshake
`handshake-comline2` | ✅ supported
proven by `handshake_comline2`, `connections_default`, `dependency_protocol` +3 more | +| connections
`connections` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +14 more | | `async`
`async` | ✅ supported
proven by `connections_async` | -| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | +| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +12 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` | diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 69ee0fc..7f864db 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 = "37ed342faf04d1fe2665724b3e11e7edc172af94" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "99187d77f16827b5c159c5a91da8aa66f74864ed" } comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922", default-features = false } eyre = "0.6.8" @@ -25,6 +25,6 @@ path = "src/bin/comline-gen-rust.rs" # (`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 = "37ed342faf04d1fe2665724b3e11e7edc172af94" } +comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "99187d77f16827b5c159c5a91da8aa66f74864ed" } # The tests compile schemas, so they need core's compiler. comline-core = { git = "https://github.com/ComlineProject/core", rev = "69039e7ab05953760bb7a6818f61e98c14b43922" } diff --git a/codegen/src/generator.rs b/codegen/src/generator.rs index 711a859..2846b17 100644 --- a/codegen/src/generator.rs +++ b/codegen/src/generator.rs @@ -78,7 +78,7 @@ fn uses_async_driver(source: &str) -> bool { /// by git rev (no crates.io yet); see design/runtime-repo-structure.md. const RUNTIME_GIT: &str = "https://github.com/ComlineProject/runtime"; /// The first with `datagram@3` and `comline@2`, core's defaults. -const RUNTIME_REV: &str = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51"; +const RUNTIME_REV: &str = "e7362217e95f8d22bbce181746562054974e659a"; /// `comline_std` — std's own pre-generated bindings, referenced instead of /// inlined when `external_std` is on. Same git-pin shape as @@ -1230,6 +1230,7 @@ fn package_module( "Reason", "Negotiated", "Comline2Handshake", + "c2", "Negotiation", "Unavailable", ] @@ -1248,7 +1249,7 @@ fn package_module( }); if comline2 { imports.push( - "use comline_runtime::handshake::comline2::{Comline2Handshake, Negotiated};".into(), + "use comline_runtime::handshake::comline2::{self as c2, Comline2Handshake, Negotiated};".into(), ); } imports.push(format!("use comline_runtime::transport::{transport_ty};")); @@ -1301,6 +1302,30 @@ fn package_module( comline2_items(req, &package, asynchronous, &mut l).ok()?; } + // What may stand for each protocol in `Services` / `ClientServices`: a + // trait per protocol, which anything implementing the protocol's trait + // satisfies, and `Absent` does to leave it out. + let slot_of = |p: &connections::Provided| -> String { + let mut name = String::from("Provide"); + for segment in comline_codegen::facts::namespace_segments(&p.namespace) { + name.push_str(&pascal(segment)); + } + name.push_str(&p.name); + name + }; + let slots: Vec = { + let mut seen: Vec = Vec::new(); + for p in server.iter().chain(&client) { + let slot = slot_of(p); + if !seen.contains(&slot) { + seen.push(slot); + } + } + seen + }; + reserved.push("Absent".into()); + reserved.extend(slots.iter().cloned()); + // Generic names that nothing else in the module can mean: a protocol // is named after its trait, and one named `Transport` or `Connection` // would otherwise hide the item the signatures below use. @@ -1323,6 +1348,70 @@ fn package_module( name }; + // The name `Absent` stands for a protocol left out, in the fields a + // subset doesn't give. + l.push( + "/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided,".into(), + ); + if comline2 { + l.push("/// and the `comline@2` Hello doesn't list it unless this end calls it.".into()); + } else { + l.push("/// and the connection has no dispatcher for it.".into()); + } + l.push("#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]".into()); + l.push("pub struct Absent;".into()); + l.push(String::new()); + // One trait per protocol, with the two ways to fill its slot. + let mut written: Vec = Vec::new(); + for p in server.iter().chain(&client) { + let slot = slot_of(p); + if written.contains(&slot) { + continue; + } + written.push(slot.clone()); + let path = format!("crate::{}::{}", segments(&p.namespace), ident(&p.name)); + l.push(format!( + "/// What provides `{}` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`].", + display_path(&p.namespace, &p.name) + )); + l.push("#[doc(hidden)]".into()); + l.push(format!("pub trait {slot} {{")); + if comline2 { + l.push(" /// Its entry in the Hello, when something provides it.".into()); + l.push(" const ENTRY: $Option>;".into()); + } + l.push(format!( + " fn provide(self, conn: &mut Connection) -> $Result<(), RuntimeError>;" + )); + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl {slot} for Absent {{")); + if comline2 { + l.push(" const ENTRY: $Option> = $None;".into()); + } + l.push(format!( + " fn provide(self, _conn: &mut Connection) -> $Result<(), RuntimeError> {{" + )); + l.push(" $Ok(())".into()); + l.push(" }".into()); + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl {slot} for P {{")); + if comline2 { + l.push(format!( + " const ENTRY: $Option> = $Some({});", + entry_const(&p.namespace, &p.name) + )); + } + l.push(format!( + " fn provide(self, conn: &mut Connection) -> $Result<(), RuntimeError> {{" + )); + l.push(format!(" {path}{dispatcher}(self).provide_on(conn)")); + l.push(" }".into()); + l.push("}".into()); + l.push(String::new()); + } + // `Services`, its generics, their bounds and the struct itself. struct Side { ty: &'static str, @@ -1330,63 +1419,134 @@ fn package_module( bounds: String, } let mut declared: Vec<&'static str> = Vec::new(); - let mut side = - |ty: &'static str, provided: &[connections::Provided], who: &str| -> Option { - if provided.is_empty() { - return None; - } - declared.push(ty); - let names: Vec = provided.iter().map(|p| generic(&p.field)).collect(); - let bounds: Vec = provided - .iter() - .zip(&names) - .map(|(p, g)| { - format!( - "{g}: crate::{}::{}{bound}", - segments(&p.namespace), - ident(&p.name) - ) - }) - .collect(); + let mut side = |ty: &'static str, + provided: &[connections::Provided], + who: &str| + -> Option { + if provided.is_empty() { + return None; + } + declared.push(ty); + let names: Vec = provided.iter().map(|p| generic(&p.field)).collect(); + let bounds: Vec = provided + .iter() + .zip(&names) + .map(|(p, g)| format!("{g}: {}", slot_of(p))) + .collect(); + let generics = names.join(", "); + let absent = vec!["Absent"; provided.len()].join(", "); + l.push(format!( + "/// What {who} provides: one field per protocol. Every field is a" + )); + l.push("/// protocol's implementation, or [`Absent`] to leave the protocol out;".into()); + l.push(format!( + "/// `{ty}::new()` has them all absent, and `with_` provides one." + )); + l.push(format!("pub struct {ty}<{generics}> {{")); + for (p, g) in provided.iter().zip(&names) { + l.push(format!(" pub {}: {g},", ident(&p.field))); + } + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl {ty}<{absent}> {{")); + l.push(" /// Nothing provided yet.".into()); + l.push(" pub fn new() -> Self {".into()); + l.push(format!(" {ty} {{")); + for p in provided { + l.push(format!(" {}: Absent,", ident(&p.field))); + } + l.push(" }".into()); + l.push(" }".into()); + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl Default for {ty}<{absent}> {{")); + l.push(" fn default() -> Self {".into()); + l.push(" Self::new()".into()); + l.push(" }".into()); + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl<{generics}> {ty}<{generics}> {{")); + for (i, p) in provided.iter().enumerate() { + let mut into = names.clone(); + into[i] = "P".into(); l.push(format!( - "/// What {who} provides: one field per protocol, so leaving one out" + " /// Provide `{}` with `provider`, in place of what was there.", + display_path(&p.namespace, &p.name) )); - l.push("/// doesn't compile.".into()); - l.push(format!("pub struct {ty}<{}> {{", names.join(", "))); - for (p, g) in provided.iter().zip(&names) { - l.push(format!(" pub {}: {g},", ident(&p.field))); - } - l.push("}".into()); - l.push(String::new()); l.push(format!( - "impl<{}> {ty}<{}> {{", - bounds.join(", "), - names.join(", ") + " pub fn with_{}(self, provider: P) -> {ty}<{}> {{", + p.field, + segments(&p.namespace), + ident(&p.name), + into.join(", ") )); + l.push(format!(" {ty} {{")); + for (j, q) in provided.iter().enumerate() { + if i == j { + l.push(format!(" {}: provider,", ident(&q.field))); + } else { + l.push(format!( + " {}: self.{},", + ident(&q.field), + ident(&q.field) + )); + } + } + l.push(" }".into()); + l.push(" }".into()); + } + l.push("}".into()); + l.push(String::new()); + l.push(format!("impl<{}> {ty}<{generics}> {{", bounds.join(", "))); + l.push( + " /// Provide every protocol given on `conn`: the peer's calls to them come here." + .into(), + ); + if comline2 { + l.push(" /// The protocols left [`Absent`] aren't provided. Fails with".into()); l.push( - " /// Provide every protocol on `conn`: the peer's calls to them come here." + " /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept." .into(), ); + } else { + l.push(" /// The protocols left [`Absent`] aren't provided.".into()); + } + l.push(format!( + " pub fn provide_on(self, conn: &mut Connection) -> $Result<(), RuntimeError> {{" + )); + for p in provided { l.push(format!( - " pub fn provide_on(self, conn: &mut Connection) {{" + " {}::provide(self.{}, conn)?;", + slot_of(p), + ident(&p.field) )); - for p in provided { - l.push(format!( - " crate::{}::{}{dispatcher}(self.{}).provide_on(conn);", - segments(&p.namespace), - ident(&p.name), - ident(&p.field) - )); - } - l.push(" }".into()); - l.push("}".into()); + } + l.push(" $Ok(())".into()); + l.push(" }".into()); + if comline2 { l.push(String::new()); - Some(Side { - ty, - generics: names.join(", "), - bounds: bounds.join(", "), - }) - }; + l.push(" /// The Hello entries of the protocols given.".into()); + l.push(" #[doc(hidden)]".into()); + l.push(" pub fn entries(&self) -> $Vec> {".into()); + let entries: Vec = provided + .iter() + .zip(&names) + .map(|(p, g)| format!("<{g} as {}>::ENTRY", slot_of(p))) + .collect(); + l.push(format!( + " [{}].into_iter().flatten().collect()", + entries.join(", ") + )); + l.push(" }".into()); + } + l.push("}".into()); + l.push(String::new()); + Some(Side { + ty, + generics, + bounds: bounds.join(", "), + }) + }; let server_side = side("Services", &server, "the accepting side"); let client_side = side("ClientServices", &client, "the dialling side"); reserved.extend(declared.into_iter().map(String::from)); @@ -1403,9 +1563,26 @@ fn package_module( ), } }; - let body = |l: &mut Vec, side: &Option, open: String| { + // `called`: what the other side provides, which this end lists in its + // Hello to call. + let body = |l: &mut Vec, + side: &Option, + open: String, + called: &[connections::Provided]| { if comline2 { - l.push(" let mut handshake = handshake();".into()); + let provided = if side.is_some() { + "&services.entries()" + } else { + "&[]" + }; + let called: Vec = called + .iter() + .map(|p| entry_const(&p.namespace, &p.name)) + .collect(); + l.push(format!( + " let mut handshake = handshake({provided}, &[{}]);", + called.join(", ") + )); // An async connection's extensions are reached through a handle. let binding = if asynchronous && side.is_none() { "conn" @@ -1426,11 +1603,11 @@ fn package_module( )); } if side.is_some() { - l.push(" services.provide_on(&mut conn);".into()); + l.push(" services.provide_on(&mut conn)?;".into()); } } else if side.is_some() { l.push(format!(" let mut conn = {open};")); - l.push(" services.provide_on(&mut conn);".into()); + l.push(" services.provide_on(&mut conn)?;".into()); } else { l.push(format!(" let conn = {open};")); } @@ -1451,7 +1628,7 @@ fn package_module( l.push("/// a time.".into()); } l.push(signature("accept", &server_side, "Connection")); - body(&mut l, &server_side, open("accept")); + body(&mut l, &server_side, open("accept"), &client); l.push("/// [`accept`], then serve every call until the peer leaves.".into()); l.push(signature("serve", &server_side, "()")); @@ -1481,7 +1658,7 @@ fn package_module( l.push("/// through their senders.".into()); } l.push(signature("connect", &client_side, "Connection")); - body(&mut l, &client_side, open("connect")); + body(&mut l, &client_side, open("connect"), &server); // What the package's user is pointed at, first. let mut docs: Vec = vec![ @@ -1540,6 +1717,28 @@ fn package_module( )); docs.push(format!("- Dial with [`connect`]`({connect_args})`.")); } + // A side provides a subset of its protocols as well as all of them. + let subset_of = |ty: &str, provided: &[connections::Provided]| { + provided + .first() + .map(|p| format!("`{ty}::new().with_{}(..)`", p.field)) + }; + let subset: Vec = [ + subset_of("Services", &server), + subset_of("ClientServices", &client), + ] + .into_iter() + .flatten() + .collect(); + docs.push(format!( + "- To provide only some of a side's protocols, start from {} and add each with its `with_` method, or write [`Absent`] in the fields left out. {}", + subset.join(" or "), + if comline2 { + "The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection." + } else { + "The connection then has a dispatcher for those only." + } + )); let call = |p: &connections::Provided| -> Option { let function = first_function(&req.schemas, &p.namespace, &p.name)?; Some(if asynchronous { @@ -1729,60 +1928,109 @@ fn display_path(namespace: &str, name: &str) -> String { segments.join("::") } -/// The package module's `comline@2` items: this end's Hello (the facts it -/// was generated from), `handshake()` with the parameters the package states, -/// and what senders check each call against. +/// The name of a protocol's [`ProtocolEntry`](comline_codegen::facts::HelloEntry) +/// constant in the package module: `P_` and the protocol's path, upper case. +fn entry_const(namespace: &str, name: &str) -> String { + let mut path: Vec = comline_codegen::facts::namespace_segments(namespace) + .map(screaming_snake) + .collect(); + path.push(screaming_snake(name)); + format!("P_{}", path.join("_")) +} + +/// The package module's `comline@2` items: this end's Hello as the facts it +/// is built from (the header, and one entry per protocol), `handshake()` +/// which builds it from the protocols provided and called, and what senders +/// check each call against. fn comline2_items( req: &GenerateRequest, package: &connections::PackageConnection, asynchronous: bool, l: &mut Vec, ) -> Result<()> { - let (hello, protocols) = comline_codegen::facts::hello(req, package)?; + let parts = comline_codegen::facts::hello_parts(req, package)?; let params = comline_codegen::facts::Comline2Params::of(&package.handshake_value); - let facts = req.facts.as_ref().expect("hello() had facts"); + let facts = req.facts.as_ref().expect("hello_parts() had facts"); + let hash = |bytes: &[u8; 16]| -> String { + let bytes: Vec = bytes.iter().map(|b| format!("{b:#04x}")).collect(); + format!("c2::Hash128([{}])", bytes.join(", ")) + }; + let release = |(major, minor, patch): (u32, u32, u32)| { + format!("c2::Release::new({major}, {minor}, {patch})") + }; + l.push(format!( + "/// What this end's `comline@2` Hello holds whichever protocols it lists: version {} of", + facts.version + )); l.push(format!( - "/// This end's `comline@2` Hello: version {} of package `{}`, as its", - facts.version, + "/// package `{}`, as its history records it, and the connection's encodings.", facts.id.as_deref().unwrap_or_default() )); - l.push("/// history records it. Its protocols, by wire number:".into()); - l.push("///".into()); - for p in &protocols { + l.push( + "/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each." + .into(), + ); + l.push("#[doc(hidden)]".into()); + l.push("pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader {".into()); + l.push(format!( + " exchange: c2::Exchange::{},", + pascal(&parts.exchange) + )); + l.push(format!(" package_id: {},", hash(&parts.package))); + l.push(format!(" version: {},", release(parts.version))); + l.push(format!(" pre: {:?},", parts.pre)); + l.push(" encodings: &[".into()); + for encoding in &parts.encodings { + let kind = match encoding.kind { + 0 => "Format", + 1 => "Framing", + _ => "Handshake", + }; + l.push(format!( + " c2::Encoding {{ kind: c2::EncodingKind::{kind}, param_hash: {} }},", + hash(&encoding.hash) + )); + } + l.push(" ],".into()); + l.push("};".into()); + l.push(String::new()); + for p in &parts.protocols { let functions: Vec = p .functions .iter() .map(|(f, n)| format!("`{f}` {n}")) .collect(); l.push(format!( - "/// - {} `{}`, line {}: {}", - p.number, + "/// `{}`, wire number {}, line {}: {}", display_path(&p.namespace, &p.name), + p.number, p.line, functions.join(", ") )); + l.push("#[doc(hidden)]".into()); + l.push(format!( + "pub const {}: c2::ProtocolEntry<'static> = c2::ProtocolEntry {{", + entry_const(&p.namespace, &p.name) + )); + l.push(format!(" number: {},", p.number)); + l.push(format!(" line: {},", release(p.release))); + l.push(format!(" shape_hash: {},", hash(&p.shape_hash))); + let numbers: Vec = p.function_numbers().iter().map(u16::to_string).collect(); + l.push(format!(" functions: &[{}],", numbers.join(", "))); + l.push("};".into()); + l.push(String::new()); } - let bytes: Vec = hello.iter().map(|b| format!("{b:#04x}")).collect(); - l.push("#[doc(hidden)]".into()); - l.push("pub const HELLO: &[u8] = &[".into()); - for chunk in bytes.chunks(12) { - l.push(format!(" {},", chunk.join(", "))); - } - l.push("];".into()); - l.push(String::new()); let variant = |v: &str| pascal(v); - l.push("/// The `comline@2` handshake, with [`HELLO`] and the parameters the package".into()); + l.push("/// The `comline@2` handshake, with the parameters the package states:".into()); l.push(format!( - "/// states: `scope = {}`, `newer_consumer = {}`, `same_version_differs = {}`, `exchange = {}`.", + "/// `scope = {}`, `newer_consumer = {}`, `same_version_differs = {}`, `exchange = {}`.", params.scope, params.newer_consumer, params.same_version_differs, params.exchange )); + l.push("/// Its Hello lists the protocols `provided` and `called` and no others: the".into()); + l.push("/// peer refuses a listed protocol it doesn't have, and a protocol left out is".into()); + l.push("/// neither provided nor called on the connection.".into()); l.push("#[doc(hidden)]".into()); - l.push("pub fn handshake() -> Comline2Handshake {".into()); - l.push(" use comline_runtime::handshake::comline2 as c2;".into()); - l.push(" let hello = match c2::Message::decode(HELLO) {".into()); - l.push(" $Ok(c2::Message::Hello(hello)) => hello,".into()); - l.push(" _ => unreachable!(\"HELLO is a Hello message\"),".into()); - l.push(" };".into()); + l.push("pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake {".into()); l.push(" let params = c2::Params {".into()); l.push(format!( " scope: c2::Scope::{},", @@ -1801,13 +2049,23 @@ fn comline2_items( variant(¶ms.exchange) )); l.push(" };".into()); - l.push(" c2::Comline2Handshake::new(params, hello)".into()); + l.push( + " c2::Comline2Handshake::new(params, c2::Hello::build(&HEADER, provided, called))" + .into(), + ); l.push("}".into()); l.push(String::new()); l.push("/// The package's protocols on the connection, by wire number.".into()); - let paths: Vec = protocols + let paths: Vec = parts + .protocols .iter() - .map(|p| format!("({}, \"{}\")", p.number, display_path(&p.namespace, &p.name))) + .map(|p| { + format!( + "({}, \"{}\")", + p.number, + display_path(&p.namespace, &p.name) + ) + }) .collect(); l.push(format!( "const PROTOCOLS: &[(u16, &str)] = &[{}];", @@ -2156,6 +2414,14 @@ fn format_of<'a>(parameters: &[FrozenUnit], encodings: &'a Encodings) -> &'a str } } +/// What a dispatcher's `provide_on` documents about its `Result`: the same on +/// every connection, blocking or async. +const PROVIDE_ERRORS: [&str; 3] = [ + " /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2`", + " /// handshake that didn't accept this protocol: the Hello didn't list it, or the", + " /// peer refused it. A connection opened without one accepts it.", +]; + #[allow(clippy::too_many_arguments)] fn protocol( proto: &str, @@ -2556,12 +2822,15 @@ fn protocol( l.push(String::new()); l.push(" /// Provide this protocol on `conn`: the peer's calls to it come here.".into()); l.push(format!(" /// Open `conn` with {open}.")); + l.push(" ///".into()); + l.extend(PROVIDE_ERRORS.map(String::from)); l.push( " pub fn provide_on(".into(), ); l.push(" self,".into()); l.push(" conn: &mut $Connection,".into()); - l.push(" ) where".into()); + l.push(" ) -> $Result<(), $RuntimeError>".into()); + l.push(" where".into()); l.push(" S: 'static,".into()); l.push(" {".into()); l.push(" conn.provide(Self::PROTOCOL, self)".into()); @@ -2857,7 +3126,12 @@ fn async_dispatcher( l.push(String::new()); l.push(" /// Provide this protocol on `conn`: the peer's calls to it come here.".into()); l.push(format!(" /// Open `conn` with {open}.")); - l.push(" pub fn provide_on(self, conn: &mut $AsyncConnection)".into()); + l.push(" ///".into()); + l.extend(PROVIDE_ERRORS.map(String::from)); + l.push(" pub fn provide_on(".into()); + l.push(" self,".into()); + l.push(" conn: &mut $AsyncConnection,".into()); + l.push(" ) -> $Result<(), $RuntimeError>".into()); l.push(" where".into()); l.push(" T: $AsyncTransport,".into()); l.push(" W: $WireFormat + Send + Sync + 'static,".into()); diff --git a/codegen/tests/compiles.rs b/codegen/tests/compiles.rs index 39ef1d2..ef0902c 100644 --- a/codegen/tests/compiles.rs +++ b/codegen/tests/compiles.rs @@ -2335,7 +2335,10 @@ fn check_comline2_crates(label: &str, async_api: bool, behaviour: &str) { } } let lib = fs::read_to_string(dir.join("new/src/lib.rs")).unwrap(); - assert!(lib.contains("pub const HELLO: &[u8] = &["), "{lib}"); + assert!( + lib.contains("pub const HEADER: c2::HelloHeader<'static>"), + "{lib}" + ); assert!(lib.contains("Datagram3Framing"), "{lib}"); let chat = fs::read_to_string(dir.join("new/src/chat.rs")).unwrap(); // `whisper` is called by its wire number, 2, though it's declared second. @@ -2632,6 +2635,7 @@ fn documented_crates_show_the_entry_points_and_hide_the_plumbing() { "fn.accept.html", "fn.connect.html", "struct.Services.html", + "struct.Absent.html", "type.Connection.html", "type.Framing.html", "type.Format.html", @@ -2644,7 +2648,9 @@ fn documented_crates_show_the_entry_points_and_hide_the_plumbing() { } for plumbing in [ "fn.handshake.html", - "constant.HELLO.html", + "constant.HEADER.html", + "constant.P_CHAT_ADMIN_ADMIN.html", + "trait.ProvideChatAdminAdmin.html", "fn.check_call.html", "chat/admin/struct.AdminDispatcher.html", "chat/admin/struct.AdminGreetParams.html", @@ -2698,6 +2704,7 @@ fn protocols_named_like_the_package_modules_types_build() { "Negotiation", "Comline2Handshake", "Unavailable", + "Absent", "Result", "Services", ]; @@ -2743,3 +2750,247 @@ fn protocols_named_like_the_package_modules_types_build() { } let _ = fs::remove_dir_all(&shared); } + +// ── a side that provides a subset (comline-rust#133) ──────────────────────── + +/// `connections_subset`: two applications in one package, `Chat` and `Admin` +/// the server's, `Events` and `Alerts` the client's, on `comline@2`. +fn subset_request(async_api: bool) -> GenerateRequest { + let mut req = common::request(&corpus_fixture("connections_subset"), Mode::Lib, async_api); + req.package.name = "subsettest".into(); + req +} + +/// `Services` and `ClientServices` take a subset: the Hello lists only what a +/// side provides and calls, so a protocol left out is neither served nor +/// reachable, and says so; and the all-provided literal is what it was. +#[test] +fn a_side_provides_a_subset_and_its_hello_lists_that() { + let req = subset_request(false); + let files = generate_rust(&req).unwrap(); + let lib = &files + .iter() + .find(|f| f.path.ends_with("src/lib.rs")) + .unwrap() + .contents; + assert!(lib.contains("pub struct Services {"), "{lib}"); + assert!( + lib.contains("pub struct ClientServices {"), + "{lib}" + ); + check_generated_crate("subset", &req, Some(SUBSET_BEHAVIOUR)); +} + +const SUBSET_BEHAVIOUR: &str = r##" +use std::thread; + +use comline_runtime::contract::{CallError, Fault, Peer, Reason, RuntimeError}; +use comline_runtime::transport::duplex; +use subsettest::conformance::admin::{Admin, AdminSender, Alerts, AlertsSender}; +use subsettest::conformance::{Chat, ChatSendError, ChatSender, Events, EventsShownError}; +use subsettest::{accept, connect, serve, unavailable, Absent, ClientServices, Services}; + +struct ChatImpl; +impl Chat for ChatImpl { + fn send(&self, _peer: &mut impl Peer, n: u32) -> Result> { + Ok(n + 1) + } + fn leave(&self, _peer: &mut impl Peer) {} +} + +struct AdminImpl; +impl Admin for AdminImpl { + fn kick(&self, _peer: &mut impl Peer, _user: u32) {} + fn ban(&self, _peer: &mut impl Peer, _user: u32) {} +} + +struct EventsImpl; +impl Events for EventsImpl { + fn shown(&self, _peer: &mut impl Peer, n: u32) -> Result> { + Ok(n > 0) + } +} + +struct AlertsImpl; +impl Alerts for AlertsImpl { + fn raised(&self, _peer: &mut impl Peer, _code: u32) {} +} + +#[test] +fn a_protocol_left_out_is_not_on_the_connection() { + let (a, b) = duplex(); + let server = thread::spawn(move || { + let mut conn = accept(b, Services::new().with_chat(ChatImpl)).unwrap(); + // The client left `Alerts` out of what it provides: the call isn't made. + let err = AlertsSender::new(&mut conn).raised(1).unwrap_err(); + assert_eq!(err, RuntimeError::Unavailable); + let why = unavailable(&mut conn).unwrap(); + assert_eq!( + (why.protocol, why.function, why.refused), + ("conformance::admin::Alerts", "raised", Some(Reason::UnknownProtocol)) + ); + conn.serve() + }); + let mut conn = connect(a, ClientServices::new().with_events(EventsImpl)).unwrap(); + assert_eq!(ChatSender::new(&mut conn).send(4).unwrap(), 5); + // And the server left `Admin` out of what it provides. + let err = AdminSender::new(&mut conn).kick(1).unwrap_err(); + assert_eq!(err, RuntimeError::Unavailable); + let why = unavailable(&mut conn).unwrap(); + assert_eq!( + (why.protocol, why.function, why.refused), + ("conformance::admin::Admin", "kick", Some(Reason::UnknownProtocol)) + ); + drop(conn); + let _ = server.join().unwrap(); +} + +#[test] +fn a_side_that_provides_nothing_lists_only_what_it_calls() { + let (a, b) = duplex(); + let server = thread::spawn(move || serve(b, Services::new())); + let mut conn = connect(a, ClientServices { events: EventsImpl, alerts: AlertsImpl }).unwrap(); + let err = ChatSender::new(&mut conn).send(1).unwrap_err(); + assert!(matches!(err, CallError::Runtime(RuntimeError::Unavailable)), "{err:?}"); + drop(conn); + let _ = server.join().unwrap(); +} + +#[test] +fn providing_every_protocol_is_the_struct_literal() { + let (a, b) = duplex(); + let server = thread::spawn(move || serve(b, Services { chat: ChatImpl, admin: AdminImpl })); + let mut conn = connect(a, ClientServices { events: EventsImpl, alerts: AlertsImpl }).unwrap(); + assert_eq!(ChatSender::new(&mut conn).send(1).unwrap(), 2); + AdminSender::new(&mut conn).kick(7).unwrap(); + drop(conn); + let _ = server.join().unwrap(); + + // A subset is the same literal with `Absent` in the fields left out. + let (a, b) = duplex(); + let server = thread::spawn(move || serve(b, Services { chat: ChatImpl, admin: Absent })); + let mut conn = connect(a, ClientServices { events: Absent, alerts: Absent }).unwrap(); + assert_eq!(ChatSender::new(&mut conn).send(2).unwrap(), 3); + drop(conn); + let _ = server.join().unwrap(); +} +"##; + +/// [`SUBSET_BEHAVIOUR`], async. +#[test] +fn an_async_side_provides_a_subset_and_its_hello_lists_that() { + check_generated_crate( + "async-subset", + &subset_request(true), + Some(ASYNC_SUBSET_BEHAVIOUR), + ); +} + +const ASYNC_SUBSET_BEHAVIOUR: &str = r##" +use comline_runtime::connection::AsyncPeer; +use comline_runtime::contract::{CallError, Fault, Reason, RuntimeError}; +use comline_runtime::transport::async_duplex; +use subsettest::conformance::admin::{Admin, AdminAsyncSender, Alerts, AlertsAsyncSender}; +use subsettest::conformance::{Chat, ChatAsyncSender, ChatSendError, Events, EventsShownError}; +use subsettest::{accept, connect, serve, unavailable, Absent, ClientServices, Services}; + +struct ChatImpl; +impl Chat for ChatImpl { + async fn send(&self, _peer: &impl AsyncPeer, n: u32) -> Result> { + Ok(n + 1) + } + async fn leave(&self, _peer: &impl AsyncPeer) {} +} + +struct AdminImpl; +impl Admin for AdminImpl { + async fn kick(&self, _peer: &impl AsyncPeer, _user: u32) {} + async fn ban(&self, _peer: &impl AsyncPeer, _user: u32) {} +} + +struct EventsImpl; +impl Events for EventsImpl { + async fn shown(&self, _peer: &impl AsyncPeer, n: u32) -> Result> { + Ok(n > 0) + } +} + +struct AlertsImpl; +impl Alerts for AlertsImpl { + async fn raised(&self, _peer: &impl AsyncPeer, _code: u32) {} +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_protocol_left_out_is_not_on_the_connection() { + let (dialler, acceptor) = async_duplex(); + let server = tokio::spawn(async move { + let conn = accept(acceptor, Services::new().with_chat(ChatImpl)).await.unwrap(); + let to_client = conn.handle(); + // The client left `Alerts` out of what it provides: the call isn't made. + let err = AlertsAsyncSender::new(&to_client).raised(1).unwrap_err(); + assert_eq!(err, RuntimeError::Unavailable); + let why = unavailable(&to_client).unwrap(); + assert_eq!( + (why.protocol, why.function, why.refused), + ("conformance::admin::Alerts", "raised", Some(Reason::UnknownProtocol)) + ); + conn.run().await + }); + let client = connect(dialler, ClientServices::new().with_events(EventsImpl)).await.unwrap(); + let to_server = client.handle(); + let client = tokio::spawn(client.run()); + + assert_eq!(ChatAsyncSender::new(&to_server).send(4).await.unwrap(), 5); + // And the server left `Admin` out of what it provides. + let err = AdminAsyncSender::new(&to_server).kick(1).unwrap_err(); + assert_eq!(err, RuntimeError::Unavailable); + let why = unavailable(&to_server).unwrap(); + assert_eq!( + (why.protocol, why.function, why.refused), + ("conformance::admin::Admin", "kick", Some(Reason::UnknownProtocol)) + ); + + to_server.close(); + client.await.unwrap().unwrap(); + let _ = server.await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_side_that_provides_nothing_lists_only_what_it_calls() { + let (dialler, acceptor) = async_duplex(); + let server = tokio::spawn(serve(acceptor, Services::new())); + let client = connect(dialler, ClientServices { events: EventsImpl, alerts: AlertsImpl }).await.unwrap(); + let to_server = client.handle(); + let client = tokio::spawn(client.run()); + let err = ChatAsyncSender::new(&to_server).send(1).await.unwrap_err(); + assert!(matches!(err, CallError::Runtime(RuntimeError::Unavailable)), "{err:?}"); + to_server.close(); + client.await.unwrap().unwrap(); + let _ = server.await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn providing_every_protocol_is_the_struct_literal() { + let (dialler, acceptor) = async_duplex(); + let server = tokio::spawn(serve(acceptor, Services { chat: ChatImpl, admin: AdminImpl })); + let client = connect(dialler, ClientServices { events: EventsImpl, alerts: AlertsImpl }).await.unwrap(); + let to_server = client.handle(); + let client = tokio::spawn(client.run()); + assert_eq!(ChatAsyncSender::new(&to_server).send(1).await.unwrap(), 2); + AdminAsyncSender::new(&to_server).kick(7).unwrap(); + to_server.close(); + client.await.unwrap().unwrap(); + let _ = server.await.unwrap(); + + // A subset is the same literal with `Absent` in the fields left out. + let (dialler, acceptor) = async_duplex(); + let server = tokio::spawn(serve(acceptor, Services { chat: ChatImpl, admin: Absent })); + let client = connect(dialler, ClientServices { events: Absent, alerts: Absent }).await.unwrap(); + let to_server = client.handle(); + let client = tokio::spawn(client.run()); + assert_eq!(ChatAsyncSender::new(&to_server).send(2).await.unwrap(), 3); + to_server.close(); + client.await.unwrap().unwrap(); + let _ = server.await.unwrap(); +} +"##; diff --git a/codegen/tests/dependency_protocols.rs b/codegen/tests/dependency_protocols.rs index 1f63f75..c3db6b8 100644 --- a/codegen/tests/dependency_protocols.rs +++ b/codegen/tests/dependency_protocols.rs @@ -87,7 +87,9 @@ fn a_package_using_only_a_dependencys_types_generates() { "{mode:?}" ); assert!( - files.iter().all(|f| !f.contents.contains("HELLO")), + files + .iter() + .all(|f| !f.contents.contains("HELLO") && !f.contents.contains("HEADER")), "{mode:?}" ); assert!( diff --git a/codegen/tests/entry_points.rs b/codegen/tests/entry_points.rs index 1d4e12e..973c74a 100644 --- a/codegen/tests/entry_points.rs +++ b/codegen/tests/entry_points.rs @@ -179,7 +179,13 @@ fn the_wire_plumbing_is_hidden_and_the_entry_points_are_not() { ), "{admin}" ); - for item in ["pub const HELLO", "pub fn handshake()", "pub fn check_call"] { + for item in [ + "pub const HEADER", + "pub const P_CHAT_ADMIN_ADMIN", + "pub trait ProvideChatAdminAdmin", + "pub fn handshake(", + "pub fn check_call", + ] { assert!(hidden(connection, item), "{item} is plumbing\n{connection}"); } // What a user touches stays in the docs. @@ -189,6 +195,7 @@ fn the_wire_plumbing_is_hidden_and_the_entry_points_are_not() { (admin, "pub struct Notice"), (admin, "pub type AdminGreetError"), (connection, "pub struct Services<"), + (connection, "pub struct Absent"), (connection, "pub fn serve<"), (connection, "pub fn accept<"), (connection, "pub fn connect<"), diff --git a/codegen/tests/golden/bounds/rust/conformance.rs b/codegen/tests/golden/bounds/rust/conformance.rs index 6360569..6966bed 100644 --- a/codegen/tests/golden/bounds/rust/conformance.rs +++ b/codegen/tests/golden/bounds/rust/conformance.rs @@ -1,5 +1,5 @@ // This file uses `comline_runtime` - add it to your Cargo.toml: -// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51" } +// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "e7362217e95f8d22bbce181746562054974e659a" } // Generated by Comline // For Rust 1.85.0 or later; verified up to 1.99. use serde::{Deserialize, Serialize}; diff --git a/codegen/tests/golden/connections/rust/conformance.rs b/codegen/tests/golden/connections/rust/conformance.rs index b5e3fc2..3ee813f 100644 --- a/codegen/tests/golden/connections/rust/conformance.rs +++ b/codegen/tests/golden/connections/rust/conformance.rs @@ -92,10 +92,15 @@ impl ChatDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) @@ -211,10 +216,15 @@ impl EventsDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/connections/rust/connection.rs b/codegen/tests/golden/connections/rust/connection.rs index 071340b..61668e5 100644 --- a/codegen/tests/golden/connections/rust/connection.rs +++ b/codegen/tests/golden/connections/rust/connection.rs @@ -6,6 +6,7 @@ //! - 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: .. })`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` or `ClientServices::new().with_events(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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(..)`. //! @@ -25,29 +26,124 @@ pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Events` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceEvents { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceEvents for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceEvents for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::EventsDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } } } -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + Ok(()) + } +} + +/// What the dialling side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `ClientServices::new()` has them all absent, and `with_` provides one. 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); +impl ClientServices { + /// Nothing provided yet. + pub fn new() -> Self { + ClientServices { + events: Absent, + } + } +} + +impl Default for ClientServices { + fn default() -> Self { + Self::new() + } +} + +impl ClientServices { + /// Provide `conformance::Events` with `provider`, in place of what was there. + pub fn with_events(self, provider: P) -> ClientServices

{ + ClientServices { + events: provider, + } + } +} + +impl ClientServices { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceEvents::provide(self.events, conn)?; + Ok(()) } } @@ -55,22 +151,22 @@ impl ClientServices { /// 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> { +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); + 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> { +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> { +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); + 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 index 11b4f9b..76fa733 100644 --- a/codegen/tests/golden/connections_async/rust/conformance.rs +++ b/codegen/tests/golden/connections_async/rust/conformance.rs @@ -1,5 +1,5 @@ // 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"] } +// comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "e7362217e95f8d22bbce181746562054974e659a", features = ["async"] } // Generated by Comline // For Rust 1.85.0 or later; verified up to 1.99. use serde::{Deserialize, Serialize}; @@ -74,7 +74,14 @@ impl ChatAsyncDispatcher { /// 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) + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut AsyncConnection, + ) -> Result<(), RuntimeError> where T: AsyncTransport, W: WireFormat + Send + Sync + 'static, @@ -176,7 +183,14 @@ impl EventsAsyncDispatcher { /// 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) + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut AsyncConnection, + ) -> Result<(), RuntimeError> where T: AsyncTransport, W: WireFormat + Send + Sync + 'static, diff --git a/codegen/tests/golden/connections_async/rust/connection.rs b/codegen/tests/golden/connections_async/rust/connection.rs index f130cbd..d987c56 100644 --- a/codegen/tests/golden/connections_async/rust/connection.rs +++ b/codegen/tests/golden/connections_async/rust/connection.rs @@ -6,6 +6,7 @@ //! - 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. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` or `ClientServices::new().with_events(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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`. //! @@ -25,29 +26,124 @@ pub const CONNECTION_IR_HASH: u64 = 0xb97e34b203ec1425; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatAsyncDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Events` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceEvents { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceEvents for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceEvents for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::EventsAsyncDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } } } -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + Ok(()) + } +} + +/// What the dialling side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `ClientServices::new()` has them all absent, and `with_` provides one. 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); +impl ClientServices { + /// Nothing provided yet. + pub fn new() -> Self { + ClientServices { + events: Absent, + } + } +} + +impl Default for ClientServices { + fn default() -> Self { + Self::new() + } +} + +impl ClientServices { + /// Provide `conformance::Events` with `provider`, in place of what was there. + pub fn with_events(self, provider: P) -> ClientServices

{ + ClientServices { + events: provider, + } + } +} + +impl ClientServices { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceEvents::provide(self.events, conn)?; + Ok(()) } } @@ -55,22 +151,22 @@ impl ClientServices { /// 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> { +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); + 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> { +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> { +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); + 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 index a6aa6f7..e85a212 100644 --- a/codegen/tests/golden/connections_default/rust/conformance.rs +++ b/codegen/tests/golden/connections_default/rust/conformance.rs @@ -96,10 +96,15 @@ impl ChatDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) @@ -220,10 +225,15 @@ impl EventsDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/connections_default/rust/connection.rs b/codegen/tests/golden/connections_default/rust/connection.rs index 0550366..b428ba7 100644 --- a/codegen/tests/golden/connections_default/rust/connection.rs +++ b/codegen/tests/golden/connections_default/rust/connection.rs @@ -6,13 +6,14 @@ //! - 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: .. })`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` or `ClientServices::new().with_events(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection. //! - 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::handshake::comline2::{self as c2, Comline2Handshake, Negotiated}; use comline_runtime::transport::Transport; /// The package's wire format (`wire.format`). @@ -29,42 +30,54 @@ pub type Framing = comline_runtime::contract::Datagram3Framing; /// 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 +/// What this end's `comline@2` Hello holds whichever protocols it lists: version 0.1.0 of +/// package `0123456789abcdef0123456789abcdef`, as its history records it, and the connection's encodings. +/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each. #[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`. +pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader { + exchange: c2::Exchange::Offer, + package_id: c2::Hash128([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), + version: c2::Release::new(0, 1, 0), + pre: "", + encodings: &[ + c2::Encoding { kind: c2::EncodingKind::Format, param_hash: c2::Hash128([0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4]) }, + c2::Encoding { kind: c2::EncodingKind::Framing, param_hash: c2::Hash128([0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2]) }, + c2::Encoding { kind: c2::EncodingKind::Handshake, param_hash: c2::Hash128([0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, 0xfc, 0x9d, 0x43, 0x30, 0xc1]) }, + ], +}; + +/// `conformance::Chat`, wire number 0, line 0.1.0: `send` 0 #[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"), - }; +pub const P_CONFORMANCE_CHAT: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 0, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0], +}; + +/// `conformance::Events`, wire number 1, line 0.1.0: `shown` 1, `ping` 0 +#[doc(hidden)] +pub const P_CONFORMANCE_EVENTS: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 1, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0, 1], +}; + +/// The `comline@2` handshake, with the parameters the package states: +/// `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. +/// Its Hello lists the protocols `provided` and `called` and no others: the +/// peer refuses a listed protocol it doesn't have, and a protocol left out is +/// neither provided nor called on the connection. +#[doc(hidden)] +pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake { 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) + c2::Comline2Handshake::new(params, c2::Hello::build(&HEADER, provided, called)) } /// The package's protocols on the connection, by wire number. @@ -154,29 +167,146 @@ pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'s Err(error) } -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the `comline@2` Hello doesn't list it unless this end calls it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + const ENTRY: Option> = Some(P_CONFORMANCE_CHAT); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Events` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceEvents { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceEvents for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceEvents for P { + const ENTRY: Option> = Some(P_CONFORMANCE_EVENTS); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::EventsDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } } } -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY].into_iter().flatten().collect() + } +} + +/// What the dialling side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `ClientServices::new()` has them all absent, and `with_` provides one. 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); +impl ClientServices { + /// Nothing provided yet. + pub fn new() -> Self { + ClientServices { + events: Absent, + } + } +} + +impl Default for ClientServices { + fn default() -> Self { + Self::new() + } +} + +impl ClientServices { + /// Provide `conformance::Events` with `provider`, in place of what was there. + pub fn with_events(self, provider: P) -> ClientServices

{ + ClientServices { + events: provider, + } + } +} + +impl ClientServices { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceEvents::provide(self.events, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY].into_iter().flatten().collect() } } @@ -184,26 +314,26 @@ impl ClientServices { /// 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(); +pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { + let mut handshake = handshake(&services.entries(), &[P_CONFORMANCE_EVENTS]); 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); + 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> { +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(); +pub fn connect(transport: T, services: ClientServices) -> Result, RuntimeError> { + let mut handshake = handshake(&services.entries(), &[P_CONFORMANCE_CHAT]); 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); + 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 index a9f2e75..10340a5 100644 --- a/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs +++ b/codegen/tests/golden/connections_jsonrpc/rust/conformance.rs @@ -92,10 +92,15 @@ impl ChatDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) @@ -211,10 +216,15 @@ impl EventsDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/connections_jsonrpc/rust/connection.rs b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs index 3c96bb7..3aaa670 100644 --- a/codegen/tests/golden/connections_jsonrpc/rust/connection.rs +++ b/codegen/tests/golden/connections_jsonrpc/rust/connection.rs @@ -6,6 +6,7 @@ //! - 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: .. })`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` or `ClientServices::new().with_events(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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(..)`. //! @@ -28,29 +29,124 @@ pub type Framing = comline_runtime::framing::JsonRpcFraming; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Events` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceEvents { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceEvents for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceEvents for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::EventsDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } } } -/// What the dialling side provides: one field per protocol, so leaving one out -/// doesn't compile. +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + Ok(()) + } +} + +/// What the dialling side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `ClientServices::new()` has them all absent, and `with_` provides one. 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); +impl ClientServices { + /// Nothing provided yet. + pub fn new() -> Self { + ClientServices { + events: Absent, + } + } +} + +impl Default for ClientServices { + fn default() -> Self { + Self::new() + } +} + +impl ClientServices { + /// Provide `conformance::Events` with `provider`, in place of what was there. + pub fn with_events(self, provider: P) -> ClientServices

{ + ClientServices { + events: provider, + } + } +} + +impl ClientServices { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceEvents::provide(self.events, conn)?; + Ok(()) } } @@ -58,22 +154,22 @@ impl ClientServices { /// 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> { +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); + 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> { +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> { +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); + services.provide_on(&mut conn)?; Ok(conn) } diff --git a/codegen/tests/golden/connections_subset/rust/conformance.rs b/codegen/tests/golden/connections_subset/rust/conformance.rs new file mode 100644 index 0000000..66a17d1 --- /dev/null +++ b/codegen/tests/golden/connections_subset/rust/conformance.rs @@ -0,0 +1,271 @@ +// 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 = 0x9449c3abfe37d1bd; + +#[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>; + 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.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.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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut Connection, + ) -> Result<(), RuntimeError> + 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, 1, "conformance::Chat", "send")?; + let (reply, fmt) = self.0.call(Self::PROTOCOL, Call::new(1, "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)), + } + } + + 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"), &()) + } +} + +#[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>; +} + +#[doc(hidden)] +pub const EVENTS_CALLS: &[&str] = &["shown"]; + +#[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 { + 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(()) + } + _ => 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut Connection, + ) -> Result<(), RuntimeError> + 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, 0, "conformance::Events", "shown")?; + 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)), + } + } +} + diff --git a/codegen/tests/golden/connections_subset/rust/conformance/admin.rs b/codegen/tests/golden/connections_subset/rust/conformance/admin.rs new file mode 100644 index 0000000..5003691 --- /dev/null +++ b/codegen/tests/golden/connections_subset/rust/conformance/admin.rs @@ -0,0 +1,241 @@ +// 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 = 0xcc4174b917e48376; + +#[doc(hidden)] +pub use crate::connection::{CONNECTION_IR_HASH, Format}; + +#[doc(hidden)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminKickParams { + pub user: u32, +} + +#[doc(hidden)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdminBanParams { + pub user: u32, +} + +pub type AdminError = ::core::convert::Infallible; + +pub trait Admin { + fn kick(&self, peer: &mut impl Peer, user: u32); + fn ban(&self, peer: &mut impl Peer, user: u32); +} + +#[doc(hidden)] +pub const ADMIN_CALLS: &[&str] = &["kick", "ban"]; + +#[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 { + 1 => { + let p: AdminKickParams = match peer.format().decode(params) { + Ok(p) => p, + Err(_) => return Ok(()), + }; + self.0.kick(peer, p.user); + Ok(()) + } + 0 => { + let p: AdminBanParams = match peer.format().decode(params) { + Ok(p) => p, + Err(_) => return Ok(()), + }; + self.0.ban(peer, p.user); + Ok(()) + } + _ => Err(RuntimeError::UnknownCall), + } + } +} + +impl AdminDispatcher { + /// This protocol's number on a connection. + #[doc(hidden)] + pub const PROTOCOL: ProtocolNumber = 2; + + /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut Connection, + ) -> Result<(), RuntimeError> + 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 = 2; + + pub fn new(peer: &'p mut P) -> Self { + Self(peer) + } + + pub fn kick(&mut self, user: u32) -> Result<(), RuntimeError> { + crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::admin::Admin", "kick")?; + self.0.notify(Self::PROTOCOL, Call::new(1, "kick"), &AdminKickParams { user }) + } + + pub fn ban(&mut self, user: u32) -> Result<(), RuntimeError> { + crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::admin::Admin", "ban")?; + self.0.notify(Self::PROTOCOL, Call::new(0, "ban"), &AdminBanParams { user }) + } +} + +#[doc(hidden)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AlertsRaisedParams { + pub code: u32, +} + +pub type AlertsError = ::core::convert::Infallible; + +pub trait Alerts { + fn raised(&self, peer: &mut impl Peer, code: u32); +} + +#[doc(hidden)] +pub const ALERTS_CALLS: &[&str] = &["raised"]; + +#[doc(hidden)] +pub struct AlertsDispatcher(pub S); + +impl Dispatch for AlertsDispatcher { + fn calls(&self) -> &'static [&'static str] { + ALERTS_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: AlertsRaisedParams = match peer.format().decode(params) { + Ok(p) => p, + Err(_) => return Ok(()), + }; + self.0.raised(peer, p.code); + Ok(()) + } + _ => Err(RuntimeError::UnknownCall), + } + } +} + +impl AlertsDispatcher { + /// This protocol's number on a connection. + #[doc(hidden)] + pub const PROTOCOL: ProtocolNumber = 3; + + /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. + pub fn provide_on( + self, + conn: &mut Connection, + ) -> Result<(), RuntimeError> + where + S: 'static, + { + conn.provide(Self::PROTOCOL, self) + } +} + +/// Calls protocol `Alerts` on the other end of a connection: the peer a +/// `Connection` reaches, or the one a handler was given. +pub struct AlertsSender<'p, P: Peer>(pub &'p mut P); + +impl<'p, P: Peer> AlertsSender<'p, P> { + /// This protocol's number on a connection. + #[doc(hidden)] + pub const PROTOCOL: ProtocolNumber = 3; + + pub fn new(peer: &'p mut P) -> Self { + Self(peer) + } + + pub fn raised(&mut self, code: u32) -> Result<(), RuntimeError> { + crate::connection::check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::admin::Alerts", "raised")?; + self.0.notify(Self::PROTOCOL, Call::new(0, "raised"), &AlertsRaisedParams { code }) + } +} + diff --git a/codegen/tests/golden/connections_subset/rust/connection.rs b/codegen/tests/golden/connections_subset/rust/connection.rs new file mode 100644 index 0000000..8a89a13 --- /dev/null +++ b/codegen/tests/golden/connections_subset/rust/connection.rs @@ -0,0 +1,423 @@ +// 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`, `conformance::admin::Admin`. +//! - Implement the trait of each protocol the client provides: `conformance::Events`, `conformance::admin::Alerts`. +//! - Serve with [`serve`]`(transport, Services { chat: .., 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, ClientServices { events: .., alerts: .. })`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` or `ClientServices::new().with_events(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection. +//! - 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::{self as c2, 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 = 0x25ae4da556bd5773; + +/// 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 this end's `comline@2` Hello holds whichever protocols it lists: version 0.1.0 of +/// package `0123456789abcdef0123456789abcdef`, as its history records it, and the connection's encodings. +/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each. +#[doc(hidden)] +pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader { + exchange: c2::Exchange::Offer, + package_id: c2::Hash128([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), + version: c2::Release::new(0, 1, 0), + pre: "", + encodings: &[ + c2::Encoding { kind: c2::EncodingKind::Format, param_hash: c2::Hash128([0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4]) }, + c2::Encoding { kind: c2::EncodingKind::Framing, param_hash: c2::Hash128([0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2]) }, + c2::Encoding { kind: c2::EncodingKind::Handshake, param_hash: c2::Hash128([0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, 0xfc, 0x9d, 0x43, 0x30, 0xc1]) }, + ], +}; + +/// `conformance::Chat`, wire number 0, line 0.1.0: `send` 1, `leave` 0 +#[doc(hidden)] +pub const P_CONFORMANCE_CHAT: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 0, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0, 1], +}; + +/// `conformance::Events`, wire number 1, line 0.1.0: `shown` 0 +#[doc(hidden)] +pub const P_CONFORMANCE_EVENTS: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 1, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0], +}; + +/// `conformance::admin::Admin`, wire number 2, line 0.1.0: `kick` 1, `ban` 0 +#[doc(hidden)] +pub const P_CONFORMANCE_ADMIN_ADMIN: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 2, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0, 1], +}; + +/// `conformance::admin::Alerts`, wire number 3, line 0.1.0: `raised` 0 +#[doc(hidden)] +pub const P_CONFORMANCE_ADMIN_ALERTS: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 3, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0], +}; + +/// The `comline@2` handshake, with the parameters the package states: +/// `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. +/// Its Hello lists the protocols `provided` and `called` and no others: the +/// peer refuses a listed protocol it doesn't have, and a protocol left out is +/// neither provided nor called on the connection. +#[doc(hidden)] +pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake { + 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, c2::Hello::build(&HEADER, provided, called)) +} + +/// The package's protocols on the connection, by wire number. +const PROTOCOLS: &[(u16, &str)] = &[(0, "conformance::Chat"), (1, "conformance::Events"), (2, "conformance::admin::Admin"), (3, "conformance::admin::Alerts")]; + +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) +} + +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the `comline@2` Hello doesn't list it unless this end calls it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + const ENTRY: Option> = Some(P_CONFORMANCE_CHAT); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::admin::Admin` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceAdminAdmin { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceAdminAdmin for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceAdminAdmin for P { + const ENTRY: Option> = Some(P_CONFORMANCE_ADMIN_ADMIN); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::admin::AdminDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Events` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceEvents { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceEvents for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceEvents for P { + const ENTRY: Option> = Some(P_CONFORMANCE_EVENTS); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::EventsDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::admin::Alerts` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceAdminAlerts { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceAdminAlerts for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceAdminAlerts for P { + const ENTRY: Option> = Some(P_CONFORMANCE_ADMIN_ALERTS); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::admin::AlertsDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. +pub struct Services { + pub chat: Chat, + pub admin: Admin, +} + +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + admin: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services { + Services { + chat: provider, + admin: self.admin, + } + } + /// Provide `conformance::admin::Admin` with `provider`, in place of what was there. + pub fn with_admin(self, provider: P) -> Services { + Services { + chat: self.chat, + admin: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + ProvideConformanceAdminAdmin::provide(self.admin, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY, ::ENTRY].into_iter().flatten().collect() + } +} + +/// What the dialling side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `ClientServices::new()` has them all absent, and `with_` provides one. +pub struct ClientServices { + pub events: Events, + pub alerts: Alerts, +} + +impl ClientServices { + /// Nothing provided yet. + pub fn new() -> Self { + ClientServices { + events: Absent, + alerts: Absent, + } + } +} + +impl Default for ClientServices { + fn default() -> Self { + Self::new() + } +} + +impl ClientServices { + /// Provide `conformance::Events` with `provider`, in place of what was there. + pub fn with_events(self, provider: P) -> ClientServices { + ClientServices { + events: provider, + alerts: self.alerts, + } + } + /// Provide `conformance::admin::Alerts` with `provider`, in place of what was there. + pub fn with_alerts(self, provider: P) -> ClientServices { + ClientServices { + events: self.events, + alerts: provider, + } + } +} + +impl ClientServices { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceEvents::provide(self.events, conn)?; + ProvideConformanceAdminAlerts::provide(self.alerts, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY, ::ENTRY].into_iter().flatten().collect() + } +} + +/// 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(&services.entries(), &[P_CONFORMANCE_EVENTS, P_CONFORMANCE_ADMIN_ALERTS]); + 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(&services.entries(), &[P_CONFORMANCE_CHAT, P_CONFORMANCE_ADMIN_ADMIN]); + 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/dependency_and_own_protocols/rust/api.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs index 80d4d08..e5fb886 100644 --- a/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/api.rs @@ -101,10 +101,15 @@ impl ChatDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs index bbeb477..30039bb 100644 --- a/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/connection.rs @@ -5,12 +5,13 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection. //! - 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::handshake::comline2::{self as c2, Comline2Handshake, Negotiated}; use comline_runtime::transport::Transport; /// The package's wire format (`wire.format`). @@ -27,39 +28,45 @@ pub type Framing = comline_runtime::contract::Datagram3Framing; /// 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 +/// What this end's `comline@2` Hello holds whichever protocols it lists: version 0.1.0 of +/// package `0123456789abcdef0123456789abcdef`, as its history records it, and the connection's encodings. +/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each. #[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`. +pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader { + exchange: c2::Exchange::Offer, + package_id: c2::Hash128([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), + version: c2::Release::new(0, 1, 0), + pre: "", + encodings: &[ + c2::Encoding { kind: c2::EncodingKind::Format, param_hash: c2::Hash128([0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4]) }, + c2::Encoding { kind: c2::EncodingKind::Framing, param_hash: c2::Hash128([0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2]) }, + c2::Encoding { kind: c2::EncodingKind::Handshake, param_hash: c2::Hash128([0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, 0xfc, 0x9d, 0x43, 0x30, 0xc1]) }, + ], +}; + +/// `api::Chat`, wire number 0, line 0.1.0: `greet` 0 #[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"), - }; +pub const P_API_CHAT: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 0, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0], +}; + +/// The `comline@2` handshake, with the parameters the package states: +/// `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. +/// Its Hello lists the protocols `provided` and `called` and no others: the +/// peer refuses a listed protocol it doesn't have, and a protocol left out is +/// neither provided nor called on the connection. +#[doc(hidden)] +pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake { 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) + c2::Comline2Handshake::new(params, c2::Hello::build(&HEADER, provided, called)) } /// The package's protocols on the connection, by wire number. @@ -149,16 +156,77 @@ pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'s Err(error) } -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the `comline@2` Hello doesn't list it unless this end calls it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `api::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideApiChat { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideApiChat for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideApiChat for P { + const ENTRY: Option> = Some(P_API_CHAT); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::api::ChatDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `api::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideApiChat::provide(self.chat, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY].into_iter().flatten().collect() } } @@ -166,23 +234,23 @@ impl Services { /// 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(); +pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { + let mut handshake = handshake(&services.entries(), &[]); 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); + 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> { +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 handshake = handshake(&[], &[P_API_CHAT]); 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 index 7a4d6a7..7388381 100644 --- a/codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs +++ b/codegen/tests/golden/dependency_and_own_protocols/rust/localdeps/greeting.rs @@ -100,10 +100,15 @@ impl FooDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs b/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs index 3c3caae..dc951d5 100644 --- a/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs +++ b/codegen/tests/golden/dependency_protocol/rust/localdeps/greeting.rs @@ -105,10 +105,15 @@ impl FooDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/error_shapes/rust/conformance.rs b/codegen/tests/golden/error_shapes/rust/conformance.rs index 6fe443c..59205db 100644 --- a/codegen/tests/golden/error_shapes/rust/conformance.rs +++ b/codegen/tests/golden/error_shapes/rust/conformance.rs @@ -166,10 +166,15 @@ impl MultiDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) @@ -287,10 +292,15 @@ impl QuietDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/error_shapes/rust/connection.rs b/codegen/tests/golden/error_shapes/rust/connection.rs index e8569c2..62a59b7 100644 --- a/codegen/tests/golden/error_shapes/rust/connection.rs +++ b/codegen/tests/golden/error_shapes/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_multi(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,18 +24,95 @@ pub const CONNECTION_IR_HASH: u64 = 0x6fc29e1014b9b9c8; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Multi` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceMulti { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceMulti for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceMulti for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::MultiDispatcher(self).provide_on(conn) + } +} + +/// What provides `conformance::Quiet` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceQuiet { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceQuiet for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceQuiet for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::QuietDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + multi: Absent, + quiet: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Multi` with `provider`, in place of what was there. + pub fn with_multi(self, provider: P) -> Services { + Services { + multi: provider, + quiet: self.quiet, + } + } + /// Provide `conformance::Quiet` with `provider`, in place of what was there. + pub fn with_quiet(self, provider: P) -> Services { + Services { + multi: self.multi, + quiet: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceMulti::provide(self.multi, conn)?; + ProvideConformanceQuiet::provide(self.quiet, conn)?; + Ok(()) } } @@ -42,14 +120,14 @@ impl(transport: T, services: Services) -> Result, RuntimeError> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/format_json/rust/conformance.rs b/codegen/tests/golden/format_json/rust/conformance.rs index ace4801..201bde4 100644 --- a/codegen/tests/golden/format_json/rust/conformance.rs +++ b/codegen/tests/golden/format_json/rust/conformance.rs @@ -185,10 +185,15 @@ impl ServiceDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/format_json/rust/connection.rs b/codegen/tests/golden/format_json/rust/connection.rs index 327827b..c68b14e 100644 --- a/codegen/tests/golden/format_json/rust/connection.rs +++ b/codegen/tests/golden/format_json/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_service(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Service` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceService { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceService for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceService for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ServiceDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + service: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Service` with `provider`, in place of what was there. + pub fn with_service(self, provider: P) -> Services

{ + Services { + service: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceService::provide(self.service, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/format_msgpack/rust/conformance.rs b/codegen/tests/golden/format_msgpack/rust/conformance.rs index ace4801..201bde4 100644 --- a/codegen/tests/golden/format_msgpack/rust/conformance.rs +++ b/codegen/tests/golden/format_msgpack/rust/conformance.rs @@ -185,10 +185,15 @@ impl ServiceDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/format_msgpack/rust/connection.rs b/codegen/tests/golden/format_msgpack/rust/connection.rs index 9c2f825..73bbbcd 100644 --- a/codegen/tests/golden/format_msgpack/rust/connection.rs +++ b/codegen/tests/golden/format_msgpack/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_service(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Service` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceService { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceService for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceService for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ServiceDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + service: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Service` with `provider`, in place of what was there. + pub fn with_service(self, provider: P) -> Services

{ + Services { + service: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceService::provide(self.service, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/framing_datagram3/rust/conformance.rs b/codegen/tests/golden/framing_datagram3/rust/conformance.rs index 3094b8a..104a3b2 100644 --- a/codegen/tests/golden/framing_datagram3/rust/conformance.rs +++ b/codegen/tests/golden/framing_datagram3/rust/conformance.rs @@ -105,10 +105,15 @@ impl CounterDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/framing_datagram3/rust/connection.rs b/codegen/tests/golden/framing_datagram3/rust/connection.rs index a73dbda..a26b9f9 100644 --- a/codegen/tests/golden/framing_datagram3/rust/connection.rs +++ b/codegen/tests/golden/framing_datagram3/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_counter(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -26,16 +27,66 @@ pub type Framing = comline_runtime::contract::Datagram3Framing; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Counter` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceCounter { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceCounter for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceCounter for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::CounterDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + counter: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Counter` with `provider`, in place of what was there. + pub fn with_counter(self, provider: P) -> Services

{ + Services { + counter: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceCounter::provide(self.counter, conn)?; + Ok(()) } } @@ -43,14 +94,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/handshake_comline2/rust/conformance.rs b/codegen/tests/golden/handshake_comline2/rust/conformance.rs index 81c80c2..726e464 100644 --- a/codegen/tests/golden/handshake_comline2/rust/conformance.rs +++ b/codegen/tests/golden/handshake_comline2/rust/conformance.rs @@ -105,10 +105,15 @@ impl ChatDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/handshake_comline2/rust/connection.rs b/codegen/tests/golden/handshake_comline2/rust/connection.rs index 9971097..402c6b7 100644 --- a/codegen/tests/golden/handshake_comline2/rust/connection.rs +++ b/codegen/tests/golden/handshake_comline2/rust/connection.rs @@ -5,12 +5,13 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_chat(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection. //! - 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::handshake::comline2::{self as c2, Comline2Handshake, Negotiated}; use comline_runtime::transport::Transport; /// The package's wire format (`wire.format`). @@ -27,39 +28,45 @@ pub type Framing = comline_runtime::contract::Datagram3Framing; /// 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 +/// What this end's `comline@2` Hello holds whichever protocols it lists: version 0.1.0 of +/// package `0123456789abcdef0123456789abcdef`, as its history records it, and the connection's encodings. +/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each. #[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`. +pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader { + exchange: c2::Exchange::Offer, + package_id: c2::Hash128([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), + version: c2::Release::new(0, 1, 0), + pre: "", + encodings: &[ + c2::Encoding { kind: c2::EncodingKind::Format, param_hash: c2::Hash128([0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4]) }, + c2::Encoding { kind: c2::EncodingKind::Framing, param_hash: c2::Hash128([0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2]) }, + c2::Encoding { kind: c2::EncodingKind::Handshake, param_hash: c2::Hash128([0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, 0xfc, 0x9d, 0x43, 0x30, 0xc1]) }, + ], +}; + +/// `conformance::Chat`, wire number 0, line 0.1.0: `send` 1, `leave` 0 #[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"), - }; +pub const P_CONFORMANCE_CHAT: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 0, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0, 1], +}; + +/// The `comline@2` handshake, with the parameters the package states: +/// `scope = protocol`, `newer_consumer = refuse`, `same_version_differs = refuse`, `exchange = offer`. +/// Its Hello lists the protocols `provided` and `called` and no others: the +/// peer refuses a listed protocol it doesn't have, and a protocol left out is +/// neither provided nor called on the connection. +#[doc(hidden)] +pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake { 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) + c2::Comline2Handshake::new(params, c2::Hello::build(&HEADER, provided, called)) } /// The package's protocols on the connection, by wire number. @@ -149,16 +156,77 @@ pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'s Err(error) } -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the `comline@2` Hello doesn't list it unless this end calls it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Chat` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceChat { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceChat for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceChat for P { + const ENTRY: Option> = Some(P_CONFORMANCE_CHAT); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ChatDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + chat: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Chat` with `provider`, in place of what was there. + pub fn with_chat(self, provider: P) -> Services

{ + Services { + chat: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceChat::provide(self.chat, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY].into_iter().flatten().collect() } } @@ -166,23 +234,23 @@ impl Services { /// 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(); +pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { + let mut handshake = handshake(&services.entries(), &[]); 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); + 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> { +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 handshake = handshake(&[], &[P_CONFORMANCE_CHAT]); 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 index 7eb2cb6..4c784be 100644 --- a/codegen/tests/golden/handshake_none/rust/conformance.rs +++ b/codegen/tests/golden/handshake_none/rust/conformance.rs @@ -94,10 +94,15 @@ impl GatewayDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/handshake_none/rust/connection.rs b/codegen/tests/golden/handshake_none/rust/connection.rs index 641f30c..59506b0 100644 --- a/codegen/tests/golden/handshake_none/rust/connection.rs +++ b/codegen/tests/golden/handshake_none/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_gateway(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0xb7e7d5c80c4d8287; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Gateway` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceGateway { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceGateway for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceGateway for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::GatewayDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + gateway: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Gateway` with `provider`, in place of what was there. + pub fn with_gateway(self, provider: P) -> Services

{ + Services { + gateway: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceGateway::provide(self.gateway, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/nested_protocol/rust/chat/admin.rs b/codegen/tests/golden/nested_protocol/rust/chat/admin.rs index 7e3beac..f26a39a 100644 --- a/codegen/tests/golden/nested_protocol/rust/chat/admin.rs +++ b/codegen/tests/golden/nested_protocol/rust/chat/admin.rs @@ -101,10 +101,15 @@ impl AdminDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/nested_protocol/rust/connection.rs b/codegen/tests/golden/nested_protocol/rust/connection.rs index 2e6af9c..57c5df9 100644 --- a/codegen/tests/golden/nested_protocol/rust/connection.rs +++ b/codegen/tests/golden/nested_protocol/rust/connection.rs @@ -5,12 +5,13 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_admin(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The `comline@2` Hello then lists what is provided and every protocol of the other side this end calls, and a protocol it doesn't list isn't on the connection. //! - 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::handshake::comline2::{self as c2, Comline2Handshake, Negotiated}; use comline_runtime::transport::Transport; /// The package's wire format (`wire.format`). @@ -27,39 +28,45 @@ pub type Framing = comline_runtime::contract::Datagram3Framing; /// 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 +/// What this end's `comline@2` Hello holds whichever protocols it lists: version 0.1.0 of +/// package `0123456789abcdef0123456789abcdef`, as its history records it, and the connection's encodings. +/// [`handshake`] adds the protocols this end provides and calls, one `P_` entry each. #[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`. +pub const HEADER: c2::HelloHeader<'static> = c2::HelloHeader { + exchange: c2::Exchange::Offer, + package_id: c2::Hash128([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]), + version: c2::Release::new(0, 1, 0), + pre: "", + encodings: &[ + c2::Encoding { kind: c2::EncodingKind::Format, param_hash: c2::Hash128([0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4]) }, + c2::Encoding { kind: c2::EncodingKind::Framing, param_hash: c2::Hash128([0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2]) }, + c2::Encoding { kind: c2::EncodingKind::Handshake, param_hash: c2::Hash128([0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, 0xfc, 0x9d, 0x43, 0x30, 0xc1]) }, + ], +}; + +/// `chat::admin::Admin`, wire number 0, line 0.1.0: `greet` 0 #[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"), - }; +pub const P_CHAT_ADMIN_ADMIN: c2::ProtocolEntry<'static> = c2::ProtocolEntry { + number: 0, + line: c2::Release::new(0, 1, 0), + shape_hash: c2::Hash128([0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]), + functions: &[0], +}; + +/// The `comline@2` handshake, with the parameters the package states: +/// `scope = protocol`, `newer_consumer = degrade`, `same_version_differs = refuse`, `exchange = offer`. +/// Its Hello lists the protocols `provided` and `called` and no others: the +/// peer refuses a listed protocol it doesn't have, and a protocol left out is +/// neither provided nor called on the connection. +#[doc(hidden)] +pub fn handshake(provided: &[c2::ProtocolEntry<'_>], called: &[c2::ProtocolEntry<'_>]) -> Comline2Handshake { 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) + c2::Comline2Handshake::new(params, c2::Hello::build(&HEADER, provided, called)) } /// The package's protocols on the connection, by wire number. @@ -149,16 +156,77 @@ pub fn check_call(peer: &mut P, protocol: u16, function: u16, path: &'s Err(error) } -/// What the accepting side provides: one field per protocol, so leaving one out -/// doesn't compile. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the `comline@2` Hello doesn't list it unless this end calls it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `chat::admin::Admin` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideChatAdminAdmin { + /// Its entry in the Hello, when something provides it. + const ENTRY: Option>; + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideChatAdminAdmin for Absent { + const ENTRY: Option> = None; + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideChatAdminAdmin for P { + const ENTRY: Option> = Some(P_CHAT_ADMIN_ADMIN); + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::chat::admin::AdminDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + admin: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `chat::admin::Admin` with `provider`, in place of what was there. + pub fn with_admin(self, provider: P) -> Services

{ + Services { + admin: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. Fails with + /// `RuntimeError::Unavailable` for a protocol the handshake didn't accept. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideChatAdminAdmin::provide(self.admin, conn)?; + Ok(()) + } + + /// The Hello entries of the protocols given. + #[doc(hidden)] + pub fn entries(&self) -> Vec> { + [::ENTRY].into_iter().flatten().collect() } } @@ -166,23 +234,23 @@ impl Services { /// 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(); +pub fn accept(transport: T, services: Services) -> Result, RuntimeError> { + let mut handshake = handshake(&services.entries(), &[]); 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); + 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> { +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 handshake = handshake(&[], &[P_CHAT_ADMIN_ADMIN]); 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/protocol/rust/conformance.rs b/codegen/tests/golden/protocol/rust/conformance.rs index ace4801..201bde4 100644 --- a/codegen/tests/golden/protocol/rust/conformance.rs +++ b/codegen/tests/golden/protocol/rust/conformance.rs @@ -185,10 +185,15 @@ impl ServiceDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/protocol/rust/connection.rs b/codegen/tests/golden/protocol/rust/connection.rs index db67fce..68da66b 100644 --- a/codegen/tests/golden/protocol/rust/connection.rs +++ b/codegen/tests/golden/protocol/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_service(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0x8ee00745c73a32b2; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Service` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceService { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceService for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceService for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::ServiceDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + service: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Service` with `provider`, in place of what was there. + pub fn with_service(self, provider: P) -> Services

{ + Services { + service: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceService::provide(self.service, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/validators/rust/conformance.rs b/codegen/tests/golden/validators/rust/conformance.rs index d4ff3c3..bb58948 100644 --- a/codegen/tests/golden/validators/rust/conformance.rs +++ b/codegen/tests/golden/validators/rust/conformance.rs @@ -266,10 +266,15 @@ impl SocialDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/validators/rust/connection.rs b/codegen/tests/golden/validators/rust/connection.rs index fb3ce3a..ea39b30 100644 --- a/codegen/tests/golden/validators/rust/connection.rs +++ b/codegen/tests/golden/validators/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_social(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0xf9d255a977b3b030; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Social` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceSocial { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceSocial for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceSocial for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::SocialDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + social: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Social` with `provider`, in place of what was there. + pub fn with_social(self, provider: P) -> Services

{ + Services { + social: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceSocial::provide(self.social, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/golden/validators_on_decode/rust/conformance.rs b/codegen/tests/golden/validators_on_decode/rust/conformance.rs index 0b4bf93..8d2d71c 100644 --- a/codegen/tests/golden/validators_on_decode/rust/conformance.rs +++ b/codegen/tests/golden/validators_on_decode/rust/conformance.rs @@ -320,10 +320,15 @@ impl SocialDispatcher { /// 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. + /// + /// Fails with `RuntimeError::Unavailable` when the connection ran a `comline@2` + /// handshake that didn't accept this protocol: the Hello didn't list it, or the + /// peer refused it. A connection opened without one accepts it. pub fn provide_on( self, conn: &mut Connection, - ) where + ) -> Result<(), RuntimeError> + where S: 'static, { conn.provide(Self::PROTOCOL, self) diff --git a/codegen/tests/golden/validators_on_decode/rust/connection.rs b/codegen/tests/golden/validators_on_decode/rust/connection.rs index fb3ce3a..ea39b30 100644 --- a/codegen/tests/golden/validators_on_decode/rust/connection.rs +++ b/codegen/tests/golden/validators_on_decode/rust/connection.rs @@ -5,6 +5,7 @@ //! - 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)`. +//! - To provide only some of a side's protocols, start from `Services::new().with_social(..)` and add each with its `with_` method, or write [`Absent`] in the fields left out. The connection then has a dispatcher for those only. //! - 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. @@ -23,16 +24,66 @@ pub const CONNECTION_IR_HASH: u64 = 0xf9d255a977b3b030; /// 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. +/// A protocol left out of [`Services`] or [`ClientServices`]: it isn't provided, +/// and the connection has no dispatcher for it. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Absent; + +/// What provides `conformance::Social` in [`Services`] or [`ClientServices`]: its trait's implementor, or [`Absent`]. +#[doc(hidden)] +pub trait ProvideConformanceSocial { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError>; +} + +impl ProvideConformanceSocial for Absent { + fn provide(self, _conn: &mut Connection) -> Result<(), RuntimeError> { + Ok(()) + } +} + +impl ProvideConformanceSocial for P { + fn provide(self, conn: &mut Connection) -> Result<(), RuntimeError> { + crate::conformance::SocialDispatcher(self).provide_on(conn) + } +} + +/// What the accepting side provides: one field per protocol. Every field is a +/// protocol's implementation, or [`Absent`] to leave the protocol out; +/// `Services::new()` has them all absent, and `with_` provides one. 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); +impl Services { + /// Nothing provided yet. + pub fn new() -> Self { + Services { + social: Absent, + } + } +} + +impl Default for Services { + fn default() -> Self { + Self::new() + } +} + +impl Services { + /// Provide `conformance::Social` with `provider`, in place of what was there. + pub fn with_social(self, provider: P) -> Services

{ + Services { + social: provider, + } + } +} + +impl Services { + /// Provide every protocol given on `conn`: the peer's calls to them come here. + /// The protocols left [`Absent`] aren't provided. + pub fn provide_on(self, conn: &mut Connection) -> Result<(), RuntimeError> { + ProvideConformanceSocial::provide(self.social, conn)?; + Ok(()) } } @@ -40,14 +91,14 @@ impl Services { /// 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> { +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); + 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> { +pub fn serve(transport: T, services: Services) -> Result<(), RuntimeError> { accept(transport, services)?.serve() } diff --git a/codegen/tests/wire_invariants.rs b/codegen/tests/wire_invariants.rs index 62e3a0b..3131b75 100644 --- a/codegen/tests/wire_invariants.rs +++ b/codegen/tests/wire_invariants.rs @@ -20,9 +20,124 @@ use comline_conformance::{corpus, Fixture}; mod common; use common::{lockstep, request}; +/// Shortest-form unsigned LEB128, as the wire writes a number. +fn varint(mut value: u32, out: &mut Vec) { + while value >= 0x80 { + out.push((value as u8 & 0x7f) | 0x80); + value >>= 7; + } + out.push(value as u8); +} + +/// The bytes of the `Hash128([0x.., ..])` written on `line`. +fn hash_on(line: &str) -> Vec { + let inner = line + .split("Hash128([") + .nth(1) + .and_then(|rest| rest.split("])").next()) + .unwrap_or_else(|| panic!("no hash on `{line}`")); + inner + .split(", ") + .map(|byte| u8::from_str_radix(byte.trim_start_matches("0x"), 16).unwrap()) + .collect() +} + +/// The numbers in the parentheses or brackets that follow `marker` on `line`. +fn numbers_after(line: &str, marker: &str, close: char) -> Vec { + let rest = line + .split(marker) + .nth(1) + .unwrap_or_else(|| panic!("no `{marker}` on `{line}`")); + let inner = rest.split(close).next().unwrap(); + inner + .split(',') + .filter(|n| !n.trim().is_empty()) + .map(|n| n.trim().parse().unwrap()) + .collect() +} + +/// A release written `c2::Release::new(0, 1, 0)` on `line`, as the wire has it. +fn release_on(line: &str, out: &mut Vec) { + for part in numbers_after(line, "Release::new(", ')') { + varint(part, out); + } +} + +/// The Hello of the package's whole connection, put together from the header +/// and the protocol entries the package module holds: what its `HELLO` constant +/// was before a Hello was built at runtime, from the same bytes. `lines` +/// starts after the header's opening line. +fn header_bytes<'a>(lines: &mut impl Iterator) -> Vec { + let (mut flag, mut id, mut version, mut pre) = (0u8, vec![], vec![], String::new()); + let mut encodings = Vec::new(); + for line in lines.by_ref() { + let line = line.trim(); + if line == "};" { + break; + } + if line.starts_with("exchange: ") { + flag = u8::from(line.contains("Symmetric")); + } else if line.starts_with("package_id: ") { + id = hash_on(line); + } else if line.starts_with("version: ") { + release_on(line, &mut version); + } else if let Some(rest) = line.strip_prefix("pre: \"") { + pre = rest.trim_end_matches("\",").to_string(); + } else if line.starts_with("c2::Encoding {") { + let kind = ["Format", "Framing", "Handshake"] + .iter() + .position(|k| line.contains(&format!("EncodingKind::{k},"))) + .unwrap(); + encodings.push((kind as u8, hash_on(line))); + } + } + let mut out = vec![b'C', b'O', 2, 1, flag]; + out.extend(id); + out.extend(version); + varint(pre.len() as u32, &mut out); + out.extend(pre.bytes()); + varint(encodings.len() as u32, &mut out); + for (kind, hash) in encodings { + out.push(kind); + out.extend(hash); + } + out +} + +/// One protocol's entry, as the Hello lists it. `lines` starts after the +/// entry's opening line. +fn entry_bytes<'a>(lines: &mut impl Iterator) -> Vec { + let mut out = Vec::new(); + for line in lines.by_ref() { + let line = line.trim(); + if line == "};" { + break; + } + if line.starts_with("number: ") { + varint(numbers_after(line, "number: ", ',')[0], &mut out); + } else if line.starts_with("line: ") { + release_on(line, &mut out); + } else if line.starts_with("shape_hash: ") { + out.extend(hash_on(line)); + } else if line.starts_with("functions: ") { + let functions = numbers_after(line, "functions: &[", ']'); + varint(functions.len() as u32, &mut out); + for f in functions { + varint(f, &mut out); + } + } + } + out +} + /// Everything in `files` that is a wire value, one per line. Each is read /// off the generated text where it's written: nothing here depends on how /// the rest of a file is laid out. +/// +/// A package's Hello is built at runtime from the header and the entries its +/// module holds, so the whole connection's Hello (`HELLO = ..`) is put +/// together here from them: the bytes the pinned file has held since before +/// that, so any change to a value in the header or an entry shows as one. fn wire_values(files: &[GeneratedFile]) -> String { let mut out = String::new(); // Every file's own digest, and the package's, which a protocol file may @@ -34,21 +149,29 @@ fn wire_values(files: &[GeneratedFile]) -> String { for file in files { let path = file.path.display(); let mut lines = file.contents.lines(); + let mut header: Option> = None; + let mut entries: Vec> = Vec::new(); while let Some(line) = lines.next() { let line = line.trim(); if let Some(rest) = line.strip_prefix("pub const IR_HASH: u64 = ") { writeln!(out, "{path}: IR_HASH = {}", rest.trim_end_matches(';')).unwrap(); } else if let Some(rest) = line.strip_prefix("pub const CONNECTION_IR_HASH: u64 = ") { package_hashes.insert(rest.trim_end_matches(';').to_string()); - } else if line.starts_with("pub const HELLO: &[u8] = &[") { - let mut bytes = String::new(); - for line in lines.by_ref() { - if line.trim() == "];" { - break; - } - bytes.push_str(line.trim()); - } + } else if line.starts_with("pub const HEADER: c2::HelloHeader") { + header = Some(header_bytes(&mut lines)); + } else if line.starts_with("pub const P_") && line.contains(": c2::ProtocolEntry") { + entries.push(entry_bytes(&mut lines)); + } else if line.starts_with("const PROTOCOLS: ") && header.is_some() { + let mut hello = header.take().unwrap_or_default(); + varint(entries.len() as u32, &mut hello); + hello.extend(entries.drain(..).flatten()); + let bytes: Vec = hello.iter().map(|b| format!("{b:#04x}")).collect(); + let bytes: String = bytes + .chunks(12) + .map(|chunk| format!("{},", chunk.join(", "))) + .collect(); writeln!(out, "{path}: HELLO = {bytes}").unwrap(); + writeln!(out, "{path}: {}", line.trim_start_matches("pub ")).unwrap(); } else if line.contains("PROTOCOL: ") && line.contains("ProtocolNumber = ") { writeln!(out, "{path}: {}", line.trim_start_matches("pub ")).unwrap(); } else if line.contains("_CALLS: &[&str] = ") || line.starts_with("const PROTOCOLS: ") { diff --git a/codegen/tests/wire_invariants.txt b/codegen/tests/wire_invariants.txt index d211546..d36c1c5 100644 --- a/codegen/tests/wire_invariants.txt +++ b/codegen/tests/wire_invariants.txt @@ -404,6 +404,37 @@ src/lib.rs: HELLO = 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, src/lib.rs: const PROTOCOLS: &[(u16, &str)] = &[(0, "chat::admin::Admin")]; src/lib.rs: check_call(protocol, function CONNECTION_IR_HASH = 0xa6f61afefe65d74a +== connections_subset (code) +conformance/admin.rs: IR_HASH = 0xcc4174b917e48376 +conformance/admin.rs: const ADMIN_CALLS: &[&str] = &["kick", "ban"]; +conformance/admin.rs: const PROTOCOL: ProtocolNumber = 2; +conformance/admin.rs: const PROTOCOL: ProtocolNumber = 2; +conformance/admin.rs: check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::admin::Admin", "kick" +conformance/admin.rs: Call::new(1, "kick" +conformance/admin.rs: check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::admin::Admin", "ban" +conformance/admin.rs: Call::new(0, "ban" +conformance/admin.rs: const ALERTS_CALLS: &[&str] = &["raised"]; +conformance/admin.rs: const PROTOCOL: ProtocolNumber = 3; +conformance/admin.rs: const PROTOCOL: ProtocolNumber = 3; +conformance/admin.rs: check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::admin::Alerts", "raised" +conformance/admin.rs: Call::new(0, "raised" +conformance.rs: IR_HASH = 0x9449c3abfe37d1bd +conformance.rs: const CHAT_CALLS: &[&str] = &["send", "leave"]; +conformance.rs: const PROTOCOL: ProtocolNumber = 0; +conformance.rs: const PROTOCOL: ProtocolNumber = 0; +conformance.rs: check_call(&mut *self.0, Self::PROTOCOL, 1, "conformance::Chat", "send" +conformance.rs: Call::new(1, "send" +conformance.rs: check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Chat", "leave" +conformance.rs: Call::new(0, "leave" +conformance.rs: const EVENTS_CALLS: &[&str] = &["shown"]; +conformance.rs: const PROTOCOL: ProtocolNumber = 1; +conformance.rs: const PROTOCOL: ProtocolNumber = 1; +conformance.rs: check_call(&mut *self.0, Self::PROTOCOL, 0, "conformance::Events", "shown" +conformance.rs: Call::new(0, "shown" +connection.rs: HELLO = 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, 0x04, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a,0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,0x5a, 0x5a, 0x02, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a,0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,0x5a, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x02,0x00, 0x01, 0x03, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, +connection.rs: const PROTOCOLS: &[(u16, &str)] = &[(0, "conformance::Chat"), (1, "conformance::Events"), (2, "conformance::admin::Admin"), (3, "conformance::admin::Alerts")]; +connection.rs: check_call(protocol, function +CONNECTION_IR_HASH = 0x25ae4da556bd5773 == protocol async (code) conformance.rs: IR_HASH = 0x8ee00745c73a32b2 conformance.rs: const SERVICE_CALLS: &[&str] = &["lookup", "count", "notify"]; diff --git a/features.json b/features.json index 9743a19..ad3ec52 100644 --- a/features.json +++ b/features.json @@ -211,7 +211,8 @@ "format_msgpack", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", @@ -303,7 +304,8 @@ "connections_default", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", @@ -317,7 +319,8 @@ "connections_default", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", @@ -340,7 +343,8 @@ "connections_default", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", @@ -400,7 +404,8 @@ "validators_on_decode", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", @@ -441,7 +446,8 @@ "format_msgpack", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", diff --git a/std-extra/Cargo.toml b/std-extra/Cargo.toml index eb70d0d..7442606 100644 --- a/std-extra/Cargo.toml +++ b/std-extra/Cargo.toml @@ -12,4 +12,4 @@ autobins = false [dependencies] serde = { version = "1", features = ["derive"] } -comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "3b9cc9dc53a83fb2830d91b267bd5f477f0a1e51" } +comline-runtime = { git = "https://github.com/ComlineProject/runtime", rev = "e7362217e95f8d22bbce181746562054974e659a" } diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 4c3f48b..e77df92 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 = "37ed342faf04d1fe2665724b3e11e7edc172af94" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "99187d77f16827b5c159c5a91da8aa66f74864ed" } comline-codegen-rust = { path = "../codegen" } eyre = "0.6.8"