diff --git a/FEATURES.md b/FEATURES.md index e859d24..a2dade2 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -15,22 +15,22 @@ What the typescript generator implements, and the conformance fixtures that prov | unions
`unions` | ✅ supported
proven by `unions` | | type aliases
`type-aliases` | ✅ supported
proven by `validators`, `validators_on_decode`, `unions` +1 more | | constants
`constants` | ✅ supported
proven by `constant`, `shapes`, `validators` +1 more | -| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +14 more | +| protocols
`protocols` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +15 more | | errors
`errors` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | | functions that throw
`throws` | ✅ supported
proven by `protocol`, `error_shapes`, `lockstep` +1 more | | validators
`validators` | ⚪ ignored: the types are generated; the checks aren't run yet (core#96)
proven by `validators`, `validators_on_decode` | | imports between schemas
`imports` | ✅ supported
proven by `cross_schema`, `import_alias`, `import_glob` +6 more | -| 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` | ⚪ ignored: no checks are generated to run on decode yet (core#96)
proven by `validators_on_decode` | | JSON-RPC framing
`framing-jsonrpc` | ✅ supported
proven by `framing_jsonrpc`, `connections_jsonrpc` | | 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` +12 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` +13 more | | `async`
`async` | ⚪ ignored: handlers and senders always return Promises: the output is async either way
proven by `connections_async` | -| the `packed@1` format
`format-packed` | ✅ supported
proven by `protocol`, `error_shapes`, `validators` +11 more | +| 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` | ❌ unsupported: `@comline/runtime` has no MessagePack codec yet
proven by `format_msgpack` | | bounds
`bounds` | ✅ supported
proven by `bounds` | diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 13da79b..f2c1d24 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -8,7 +8,7 @@ license = "GPL-3.0-only" # Consumed by git rev (see ComlineProject/docs → Design → Runtime & generation # repository structure — no crates.io publishing at this stage). 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" @@ -22,6 +22,6 @@ path = "src/bin/comline-gen-typescript.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 0049fab..f18da2d 100644 --- a/codegen/src/generator.rs +++ b/codegen/src/generator.rs @@ -1321,7 +1321,12 @@ fn package_module( } if comline2 { values.push("Negotiated"); + values.push("buildHello"); + values.push("providedEntries"); } + // What `hello_parts` has vouched for: every protocol the package's `Services` + // provide has its entry, from which each end's Hello is built. + let parts = if comline2 { Some(comline_codegen::facts::hello_parts(req, package).ok()?) } else { None }; let mut s = format!("{header}\n{}\nimport {{\n", entry_doc(&connection_entry(req, connection, Spelling::Beside), false)); for v in &values { s.push_str(&format!(" {v},\n")); @@ -1330,7 +1335,7 @@ fn package_module( s.push_str(" type Codec,\n"); } if comline2 { - s.push_str(" type Peer,\n"); + s.push_str(" type Peer,\n type ProtocolEntry,\n"); } s.push_str(" type Transport,\n} from \"@comline/runtime\";\n"); s.push_str(external_imports(&external, str::to_string).trim_end_matches('\n')); @@ -1365,44 +1370,53 @@ fn package_module( connections::connection_ir_hash(&req.schemas) )); } - if comline2 { - // `facts::check` has vouched for the facts. - let items = comline2_items(req, package, type_of(encodings, &package.handshake)).ok()?; - s.push_str(&items); + if let Some(parts) = &parts { + s.push_str(&comline2_items(req, parts, package, type_of(encodings, &package.handshake))); } - let mut side = |ty: &str, provide: &str, provided: &[connections::Provided], who: &str| { + let mut side = |ty: &str, provide: &str, table: &str, provided: &[connections::Provided], who: &str| -> Option { if provided.is_empty() { - return false; + return Some(false); } + let hello = if comline2 { + format!( + " * The Hello lists the ones given, and the protocols the {other} provides, which this side calls.\n", + other = if ty == "Services" { "dialling side" } else { "accepting side" } + ) + } else { + String::new() + }; s.push_str(&format!( - "/** What {who} provides: one field per protocol, so leaving one out doesn't type-check. */\n\ + "/**\n * What {who} provides, a field per protocol: leave one out to not provide it.\n{hello} */\n\ export interface {ty} {{\n" )); for p in provided { - s.push_str(&format!(" {}: {}.{};\n", camel(&p.field), module(&p.namespace), ident(&p.name))); + s.push_str(&format!(" {}?: {}.{};\n", camel(&p.field), module(&p.namespace), ident(&p.name))); } s.push_str("}\n\n"); + if let Some(parts) = &parts { + s.push_str(&hello_table(table, ty, who, provided, parts)?); + } s.push_str(&format!( "/**\n\ - \x20* Provide every protocol in `services` on `conn`: the peer's calls to them come here.\n\ + \x20* Provide each protocol `services` holds on `conn`: the peer's calls to them come here.\n\ \x20* @internal\n\ \x20*/\n\ export function {provide}(conn: Connection, services: {ty}): void {{\n" )); for p in provided { s.push_str(&format!( - " new {}.{}Dispatcher(services.{}).provideOn(conn);\n", + " if (services.{field} !== undefined) new {}.{}Dispatcher(services.{field}).provideOn(conn);\n", module(&p.namespace), p.name, - camel(&p.field) + field = camel(&p.field) )); } s.push_str("}\n\n"); - true + Some(true) }; - let has_server = side("Services", "provideServices", server, "the accepting side"); - let has_client = side("ClientServices", "provideClientServices", client, "the dialling side"); + let has_server = side("Services", "provideServices", "SERVICES_HELLO", server, "the accepting side")?; + let has_client = side("ClientServices", "provideClientServices", "CLIENT_SERVICES_HELLO", client, "the dialling side")?; let datagram3_framing = format!(", new {}()", type_of(encodings, &package.framing)); let framing_arg = if jsonrpc { @@ -1431,14 +1445,29 @@ fn package_module( open } }; - let opening = if comline2 { " const agreed = handshake();\n" } else { "" }; + // The Hello lists what this end provides, given in `services`, and every + // protocol of the other side, which it may call. + let hello = |provides: bool, table: &str, called: bool, called_table: &str| { + let provided = if provides { format!("providedEntries({table}, services)") } else { "[]".to_string() }; + let called = if called { format!("Object.values({called_table})") } else { "[]".to_string() }; + format!(" const agreed = handshake({provided}, {called});\n") + }; + let (accept_opening, connect_opening) = if comline2 { + ( + hello(has_server, "SERVICES_HELLO", has_client, "CLIENT_SERVICES_HELLO"), + hello(has_client, "CLIENT_SERVICES_HELLO", has_server, "SERVICES_HELLO"), + ) + } else { + (String::new(), String::new()) + }; let (server_params, server_provide) = if has_server { ("transport: Transport, services: Services", " provideServices(conn, services);\n") } else { ("transport: Transport", "") }; + // Dialling without providing anything is a subset too, and the usual one. let (client_params, client_provide) = if has_client { - ("transport: Transport, services: ClientServices", " provideClientServices(conn, services);\n") + ("transport: Transport, services: ClientServices = {}", " provideClientServices(conn, services);\n") } else { ("transport: Transport", "") }; @@ -1446,7 +1475,7 @@ fn package_module( // Only a package whose dialling side provides something takes `services`. let dial_doc = if has_client { "/**\n\ - * Dial over `transport`: run the handshake, then provide every protocol in\n\ + * Dial over `transport`: run the handshake, then provide the protocols in\n\ * `services`, which the server calls. Call the server's protocols through\n\ * their senders.\n\ */\n" @@ -1459,11 +1488,11 @@ fn package_module( s.push_str(&format!( "/**\n\ * Accept a connection over `transport`: run the handshake, then provide\n\ - * every protocol in `services` on it. The connection comes back serving,\n\ + * the protocols in `services` on it. The connection comes back serving,\n\ * so the server can call the client through it.\n\ */\n\ export async function accept({server_params}): Promise {{\n\ - {opening}\ + {accept_opening}\ \x20 const conn = {};\n\ {server_provide}\ \x20 return conn;\n\ @@ -1474,7 +1503,7 @@ fn package_module( }}\n\n\ {dial_doc}\ export async function connect({client_params}): Promise {{\n\ - {opening}\ + {connect_opening}\ \x20 const conn = {};\n\ {client_provide}\ \x20 return conn;\n\ @@ -1629,62 +1658,103 @@ fn display_path(namespace: &str, name: &str) -> String { path } -/// 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 -/// `negotiated` / `warnings` for what a connection agreed. +/// A Hello entry's line in a doc comment: its wire number, path, line and +/// the numbers of its functions. +fn hello_entry_doc(p: &comline_codegen::facts::HelloEntry) -> String { + let functions: Vec = p.functions.iter().map(|(f, n)| format!("`{f}` {n}")).collect(); + format!("{} `{}`, line {}: {}", p.number, display_path(&p.namespace, &p.name), p.line, functions.join(", ")) +} + +/// `bytes` as the rows of a `Uint8Array` literal, twelve to a row. +fn byte_rows(bytes: &[u8], indent: &str) -> String { + let mut s = String::new(); + for chunk in bytes.chunks(12) { + let row: Vec = chunk.iter().map(|b| format!("{b:#04x}")).collect(); + s.push_str(&format!("{indent}{},\n", row.join(", "))); + } + s +} + +/// What a Hello holds whichever protocols it lists, as the runtime's +/// `buildHello` takes it: the bytes up to the list of protocols. +fn hello_header(parts: &comline_codegen::facts::HelloParts) -> Vec { + // The Hello of no protocol ends with its count, a single zero byte. + let mut header = parts.assemble([]); + assert_eq!(header.pop(), Some(0), "an empty protocol list is the byte 0"); + header +} + +/// A side's protocols as a Hello lists each, by the `Services` field that +/// provides it: `name` is the constant, `interface` the `Services` type its +/// keys are the fields of. `None` where a protocol has no entry on the package's +/// connection, which `hello_parts` says is every one it provides. +fn hello_table( + name: &str, + interface: &str, + who: &str, + provided: &[connections::Provided], + parts: &comline_codegen::facts::HelloParts, +) -> Option { + let mut doc = format!( + "/**\n * The protocols {who} provides, as a Hello lists each, by their field in `{interface}`:\n *\n" + ); + let mut rows = String::new(); + for p in provided { + let entry = parts.protocols.iter().find(|e| e.namespace == p.namespace && e.name == p.name)?; + doc.push_str(&format!(" * - `{}`: {}\n", camel(&p.field), hello_entry_doc(entry))); + let mut bytes = vec![]; + entry.encode(&mut bytes); + rows.push_str(&format!( + " {}: {{\n number: {},\n bytes: new Uint8Array([\n{} ]),\n }},\n", + camel(&p.field), + entry.number, + byte_rows(&bytes, " ") + )); + } + Some(format!( + "{doc} *\n * @internal\n */\nexport const {name}: Record = {{\n{rows}}};\n\n" + )) +} + +/// The package module's `comline@2` items: the Hello's header (the facts it +/// was generated from, which every end shares), `handshake()` with the +/// protocols an end provides and calls and the parameters the package states, +/// and `negotiated` / `warnings` for what a connection agreed. Each side's +/// protocols, as a Hello lists them, are emitted with its `Services`. fn comline2_items( req: &GenerateRequest, + parts: &comline_codegen::facts::HelloParts, package: &connections::PackageConnection, class: &str, -) -> Result { - let (hello, protocols) = comline_codegen::facts::hello(req, package)?; +) -> String { + // `hello_parts` had facts. + let facts = req.facts.as_ref().expect("hello_parts had facts"); let params = comline_codegen::facts::Comline2Params::of(&package.handshake_value); - let facts = req.facts.as_ref().expect("hello() had facts"); let mut s = format!( - "/**\n * This end's `comline@2` Hello: version {} of package `{}`, as its history\n * records it. Its protocols, by wire number:\n *\n", + "/**\n * This package's `comline@2` Hello up to its list of protocols: version {} of package\n * `{}`, as its history records it. {{@link buildHello}} adds the protocols an end\n * provides and calls.\n *\n * @internal\n */\nexport const HELLO_HEADER = new Uint8Array([\n", facts.version, facts.id.as_deref().unwrap_or_default() ); - for p in &protocols { - let functions: Vec = p - .functions - .iter() - .map(|(f, n)| format!("`{f}` {n}")) - .collect(); - s.push_str(&format!( - " * - {} `{}`, line {}: {}\n", - p.number, - display_path(&p.namespace, &p.name), - p.line, - functions.join(", ") - )); - } - s.push_str(" *\n * @internal\n */\nexport const HELLO = new Uint8Array([\n"); - for chunk in hello.chunks(12) { - let bytes: Vec = chunk.iter().map(|b| format!("{b:#04x}")).collect(); - s.push_str(&format!(" {},\n", bytes.join(", "))); - } + s.push_str(&byte_rows(&hello_header(parts), " ")); s.push_str("]);\n\n"); - let camel_value = |v: &str| v.to_string(); s.push_str(&format!( "/**\n\ - \x20* The `comline@2` handshake, with {{@link HELLO}} and the parameters the package states.\n\ + \x20* The `comline@2` handshake of an end that provides `provided` and calls `called`, with their\n\ + \x20* Hello ({{@link HELLO_HEADER}}, then those protocols) and the parameters the package states.\n\ \x20* @internal\n\ \x20*/\n\ - export function handshake(): {class} {{\n\ - \x20 return new {class}(HELLO, {{\n\ + export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): {class} {{\n\ + \x20 return new {class}(buildHello(HELLO_HEADER, provided, called), {{\n\ \x20 scope: \"{}\",\n\ \x20 newerConsumer: \"{}\",\n\ \x20 sameVersionDiffers: \"{}\",\n\ \x20 exchange: \"{}\",\n\ \x20 }});\n\ }}\n\n", - camel_value(¶ms.scope), - camel_value(¶ms.newer_consumer), - camel_value(¶ms.same_version_differs), - camel_value(¶ms.exchange), + params.scope, params.newer_consumer, params.same_version_differs, params.exchange, )); - let paths: Vec = protocols + let paths: Vec = parts + .protocols .iter() .map(|p| format!("[{}, \"{}\"]", p.number, display_path(&p.namespace, &p.name))) .collect(); @@ -1704,7 +1774,7 @@ fn comline2_items( }}\n\n", paths.join(", ") )); - Ok(s) + s } // ── protocol ─────────────────────────────────────────────────────────────── diff --git a/codegen/tests/dependency_protocols.rs b/codegen/tests/dependency_protocols.rs index 2773983..6304a53 100644 --- a/codegen/tests/dependency_protocols.rs +++ b/codegen/tests/dependency_protocols.rs @@ -95,13 +95,13 @@ fn a_package_using_only_a_dependencys_types_has_no_connection() { fn a_dependencys_protocol_is_not_in_services_or_the_hello() { let files = generated(&dependency_and_own_protocols(), "own"); let connection = file(&files, "connection.ts"); - assert!(connection.contains("export interface Services {\n chat: ns_api.Chat;\n}"), "{connection}"); + assert!(connection.contains("export interface Services {\n chat?: ns_api.Chat;\n}"), "{connection}"); assert!(!connection.contains("Foo"), "{connection}"); assert!(!connection.contains("localdeps"), "{connection}"); assert!(!connection.contains("ns_localdeps"), "{connection}"); // The Hello and the protocols by number name only `Chat`. - assert!(connection.contains(" * - 0 `api::Chat`, line 0.1.0: `greet` 0\n"), "{connection}"); + assert!(connection.contains(" * - `chat`: 0 `api::Chat`, line 0.1.0: `greet` 0\n"), "{connection}"); assert!(connection.contains("new Map([[0, \"api::Chat\"]])"), "{connection}"); // The dependency's protocol is still generated, with no wire numbers of the diff --git a/codegen/tests/generate.rs b/codegen/tests/generate.rs index 1beecb2..cd6f846 100644 --- a/codegen/tests/generate.rs +++ b/codegen/tests/generate.rs @@ -1778,9 +1778,9 @@ fn the_package_connection_gets_services_and_serve() { "import * as ns_game from \"./game.js\";", // The package's constants are defined once, in the module its files share. "export { CONNECTION_IR_HASH, Format } from \"./wire.js\";", - "export interface Services {\n account: ns_game.Account;\n player: ns_game.Player;\n inventory: ns_items.Inventory;\n}", - "export interface ClientServices {\n events: ns_items.Events;\n}", - " new ns_items.InventoryDispatcher(services.inventory).provideOn(conn);", + "export interface Services {\n account?: ns_game.Account;\n player?: ns_game.Player;\n inventory?: ns_items.Inventory;\n}", + "export interface ClientServices {\n events?: ns_items.Events;\n}", + " if (services.inventory !== undefined) new ns_items.InventoryDispatcher(services.inventory).provideOn(conn);", "export async function serve(transport: Transport, services: Services): Promise {", "const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH);", ] { @@ -2169,6 +2169,80 @@ fn generated_comline2_matches_the_runtime_test_fixture() { ); } +/// Two applications in one package, a protocol per side in each: `Chat` and +/// `Events` in `public`, `Admin` and `Alerts` in `admin`. +const PUBLIC: &str = "@framing = \"datagram@3\"\n@handshake = \"comline@2\"\n\ + protocol Chat {\n function send(text: string) -> u32;\n}\n\n\ + @framing = \"datagram@3\"\n@handshake = \"comline@2\"\n@provider = Client\n\ + protocol Events {\n function shown(n: u32) -> bool;\n}\n"; +const ADMIN: &str = "@framing = \"datagram@3\"\n@handshake = \"comline@2\"\n\ + protocol Admin {\n function kick(user: u32);\n}\n\n\ + @framing = \"datagram@3\"\n@handshake = \"comline@2\"\n@provider = Client\n\ + protocol Alerts {\n function raised(code: u32);\n}\n"; + +/// The request for the two applications, with the facts core's history would +/// give: four protocols, wire numbers 0 to 3, one function each. +fn subset_req() -> GenerateRequest { + use comline_codegen::facts::{EncodingFacts, FunctionFacts, PackageFacts, ProtocolFacts}; + use comline_core::schema::ir::compiler::interpreter::incremental::IncrementalInterpreter; + use comline_core::schema::ir::compiler::Compile; + let encoding = |kind: &str, name: &str| { + let e = comline_core::compat::encoding(kind, name, Default::default()); + EncodingFacts { kind: e.kind, name: e.name, params: e.params, param_hash: e.param_hash } + }; + let protocol = |namespace: &str, name: &str, number: u16, shape: &str, function: &str| ProtocolFacts { + path: format!("{namespace}::{name}"), + namespace: namespace.into(), + name: name.into(), + line: "0.1.0".into(), + number, + shape_hash: shape.repeat(32), + functions: vec![FunctionFacts { name: function.into(), since: "0.1.0".into(), number: 0 }], + }; + let facts = PackageFacts { + id: Some("0123456789abcdef0123456789abcdef".into()), + version: "0.1.0".into(), + protocols: vec![ + protocol("public", "Chat", 0, "aa", "send"), + protocol("public", "Events", 1, "bb", "shown"), + protocol("admin", "Admin", 2, "cc", "kick"), + protocol("admin", "Alerts", 3, "dd", "raised"), + ], + encodings: vec![ + encoding("format", "packed@1"), + encoding("framing", "datagram@3"), + encoding("handshake", "comline@2"), + ], + }; + let mut req = code_req(&[ + ("public".to_string(), IncrementalInterpreter::from_source(PUBLIC)), + ("admin".to_string(), IncrementalInterpreter::from_source(ADMIN)), + ]); + req.package.version = facts.version.clone(); + req.facts = Some(facts); + req +} + +/// A side takes a subset of the protocols it provides, and the Hello lists +/// that and what the side calls. Kept in `runtime/test/generated/subset/` so +/// the Node job runs it (`generated-subset.test.ts`). Regenerate with +/// `TS_BLESS=1`. +#[test] +fn generated_subset_matches_the_runtime_test_fixture() { + let files = generate_typescript(&subset_req()).unwrap(); + bless_fixture("subset", &files); + let module = &files.iter().find(|f| f.path.to_str() == Some("connection.ts")).unwrap().contents; + for expected in [ + "export interface Services {\n chat?: ns_public.Chat;\n admin?: ns_admin.Admin;\n}", + "export interface ClientServices {\n events?: ns_public.Events;\n alerts?: ns_admin.Alerts;\n}", + " const agreed = handshake(providedEntries(SERVICES_HELLO, services), Object.values(CLIENT_SERVICES_HELLO));", + " const agreed = handshake(providedEntries(CLIENT_SERVICES_HELLO, services), Object.values(SERVICES_HELLO));", + "export async function connect(transport: Transport, services: ClientServices = {}): Promise {", + ] { + assert!(module.contains(expected), "missing `{expected}` in:\n{module}"); + } +} + /// Wire numbers come from the facts or not at all. #[test] fn datagram3_without_its_facts_is_refused() { diff --git a/codegen/tests/golden/connections/typescript/connection.ts b/codegen/tests/golden/connections/typescript/connection.ts index 18b3931..988e70a 100644 --- a/codegen/tests/golden/connections/typescript/connection.ts +++ b/codegen/tests/golden/connections/typescript/connection.ts @@ -23,35 +23,39 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - chat: ns_conformance.Chat; + chat?: ns_conformance.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_conformance.Events; + events?: ns_conformance.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_conformance.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -66,11 +70,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); provideClientServices(conn, services); return conn; diff --git a/codegen/tests/golden/connections_async/typescript/connection.ts b/codegen/tests/golden/connections_async/typescript/connection.ts index 18b3931..988e70a 100644 --- a/codegen/tests/golden/connections_async/typescript/connection.ts +++ b/codegen/tests/golden/connections_async/typescript/connection.ts @@ -23,35 +23,39 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - chat: ns_conformance.Chat; + chat?: ns_conformance.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_conformance.Events; + events?: ns_conformance.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_conformance.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -66,11 +70,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); provideClientServices(conn, services); return conn; diff --git a/codegen/tests/golden/connections_default/typescript/connection.ts b/codegen/tests/golden/connections_default/typescript/connection.ts index 64218a9..fe06590 100644 --- a/codegen/tests/golden/connections_default/typescript/connection.ts +++ b/codegen/tests/golden/connections_default/typescript/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_conformance from "./conformance.js"; @@ -28,34 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `conformance::Chat`, line 0.1.0: `send` 0 - * - 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x02, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x02, 0x00, 0x01, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -79,39 +77,79 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_conformance.Chat; + chat?: ns_conformance.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `conformance::Chat`, line 0.1.0: `send` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the accepting side provides, which this side calls. + */ export interface ClientServices { - events: ns_conformance.Events; + events?: ns_conformance.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the dialling side provides, as a Hello lists each, by their field in `ClientServices`: + * + * - `events`: 1 `conformance::Events`, line 0.1.0: `shown` 1, `ping` 0 + * + * @internal + */ +export const CLIENT_SERVICES_HELLO: Record = { + events: { + number: 1, + bytes: new Uint8Array([ + 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x02, 0x00, 0x01, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_conformance.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), Object.values(CLIENT_SERVICES_HELLO)); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -124,12 +162,12 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); +export async function connect(transport: Transport, services: ClientServices = {}): Promise { + const agreed = handshake(providedEntries(CLIENT_SERVICES_HELLO, services), Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideClientServices(conn, services); diff --git a/codegen/tests/golden/connections_jsonrpc/typescript/connection.ts b/codegen/tests/golden/connections_jsonrpc/typescript/connection.ts index c6942d9..5e2f905 100644 --- a/codegen/tests/golden/connections_jsonrpc/typescript/connection.ts +++ b/codegen/tests/golden/connections_jsonrpc/typescript/connection.ts @@ -25,35 +25,39 @@ import { CONNECTION_IR_HASH } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - chat: ns_conformance.Chat; + chat?: ns_conformance.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_conformance.Events; + events?: ns_conformance.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_conformance.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_conformance.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -68,11 +72,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); provideClientServices(conn, services); return conn; diff --git a/codegen/tests/golden/connections_subset/typescript/conformance.ts b/codegen/tests/golden/connections_subset/typescript/conformance.ts new file mode 100644 index 0000000..65d1f02 --- /dev/null +++ b/codegen/tests/golden/connections_subset/typescript/conformance.ts @@ -0,0 +1,188 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0x9449c3abfe37d1bdn; + +export interface ChatSendParams { + n: number; +} + +/** @internal */ +export const ChatSendParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Chat { + send(peer: Peer, params: ChatSendParams): Promise; + leave(peer: Peer): Promise; +} + +/** @internal */ +export const CHAT_CALLS = ["send", "leave"] as const; + +/** @internal */ +export class ChatDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Chat; + + constructor(impl: Chat) { + this.impl = impl; + } + + calls(): readonly string[] { + return CHAT_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 1: { + try { + const p = codec.decode(params, ChatSendParamsLayout); + reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + case 0: { + try { + await this.impl.leave(peer); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(ChatDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class ChatSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async send(params: ChatSendParams): Promise { + checkCall(this.peer, ChatSender.PROTOCOL, 1, "conformance::Chat", "send"); + const env = await this.peer.call(ChatSender.PROTOCOL, { id: 1, name: "send" }, params, { layout: ChatSendParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } + + async leave(): Promise { + checkCall(this.peer, ChatSender.PROTOCOL, 0, "conformance::Chat", "leave"); + await this.peer.notify(ChatSender.PROTOCOL, { id: 0, name: "leave" }, null, { layout: "unit" }); + } +} + +export interface EventsShownParams { + n: number; +} + +/** @internal */ +export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Events { + shown(peer: Peer, params: EventsShownParams): Promise; +} + +/** @internal */ +export const EVENTS_CALLS = ["shown"] as const; + +/** @internal */ +export class EventsDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly impl: Events; + + constructor(impl: Events) { + this.impl = impl; + } + + calls(): readonly string[] { + return EVENTS_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, EventsShownParamsLayout); + reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(EventsDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class EventsSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async shown(params: EventsShownParams): Promise { + checkCall(this.peer, EventsSender.PROTOCOL, 0, "conformance::Events", "shown"); + const env = await this.peer.call(EventsSender.PROTOCOL, { id: 0, name: "shown" }, params, { layout: EventsShownParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + diff --git a/codegen/tests/golden/connections_subset/typescript/conformance/admin.ts b/codegen/tests/golden/connections_subset/typescript/conformance/admin.ts new file mode 100644 index 0000000..ad49706 --- /dev/null +++ b/codegen/tests/golden/connections_subset/typescript/conformance/admin.ts @@ -0,0 +1,190 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0xcc4174b917e48376n; + +export interface AdminKickParams { + user: number; +} + +/** @internal */ +export const AdminKickParamsLayout: Layout = { struct: [["user", "u32"]] }; + +export interface AdminBanParams { + user: number; +} + +/** @internal */ +export const AdminBanParamsLayout: Layout = { struct: [["user", "u32"]] }; + +export interface Admin { + kick(peer: Peer, params: AdminKickParams): Promise; + ban(peer: Peer, params: AdminBanParams): Promise; +} + +/** @internal */ +export const ADMIN_CALLS = ["kick", "ban"] as const; + +/** @internal */ +export class AdminDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 2; + + private readonly impl: Admin; + + constructor(impl: Admin) { + this.impl = impl; + } + + calls(): readonly string[] { + return ADMIN_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 1: { + try { + const p = codec.decode(params, AdminKickParamsLayout); + await this.impl.kick(peer, p); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + case 0: { + try { + const p = codec.decode(params, AdminBanParamsLayout); + await this.impl.ban(peer, p); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(AdminDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Admin` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class AdminSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 2; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async kick(params: AdminKickParams): Promise { + checkCall(this.peer, AdminSender.PROTOCOL, 1, "conformance::admin::Admin", "kick"); + await this.peer.notify(AdminSender.PROTOCOL, { id: 1, name: "kick" }, params, { layout: AdminKickParamsLayout }); + } + + async ban(params: AdminBanParams): Promise { + checkCall(this.peer, AdminSender.PROTOCOL, 0, "conformance::admin::Admin", "ban"); + await this.peer.notify(AdminSender.PROTOCOL, { id: 0, name: "ban" }, params, { layout: AdminBanParamsLayout }); + } +} + +export interface AlertsRaisedParams { + code: number; +} + +/** @internal */ +export const AlertsRaisedParamsLayout: Layout = { struct: [["code", "u32"]] }; + +export interface Alerts { + raised(peer: Peer, params: AlertsRaisedParams): Promise; +} + +/** @internal */ +export const ALERTS_CALLS = ["raised"] as const; + +/** @internal */ +export class AlertsDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 3; + + private readonly impl: Alerts; + + constructor(impl: Alerts) { + this.impl = impl; + } + + calls(): readonly string[] { + return ALERTS_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, AlertsRaisedParamsLayout); + await this.impl.raised(peer, p); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(AlertsDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Alerts` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class AlertsSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 3; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async raised(params: AlertsRaisedParams): Promise { + checkCall(this.peer, AlertsSender.PROTOCOL, 0, "conformance::admin::Alerts", "raised"); + await this.peer.notify(AlertsSender.PROTOCOL, { id: 0, name: "raised" }, params, { layout: AlertsRaisedParamsLayout }); + } +} + diff --git a/codegen/tests/golden/connections_subset/typescript/connection.ts b/codegen/tests/golden/connections_subset/typescript/connection.ts new file mode 100644 index 0000000..3b9194f --- /dev/null +++ b/codegen/tests/golden/connections_subset/typescript/connection.ts @@ -0,0 +1,196 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./conformance.js`); `Admin`, `Alerts` (in `./conformance/admin.js`). + * - Serve with `serve(transport, { chat, admin })`; `accept(transport, { chat, admin })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events, alerts })`. + * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + Datagram3Framing, + Comline2Handshake, + Negotiated, + buildHello, + providedEntries, + type Peer, + type ProtocolEntry, + type Transport, +} from "@comline/runtime"; +import * as ns_conformance from "./conformance.js"; +import * as ns_conformance_admin from "./conformance/admin.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. + * + * @internal + */ +export const HELLO_HEADER = new Uint8Array([ + 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, + 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, + 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, + 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, + 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, + 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, +]); + +/** + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. + * @internal + */ +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { + scope: "protocol", + newerConsumer: "degrade", + sameVersionDiffers: "refuse", + exchange: "offer", + }); +} + +/** The package's protocols on the connection, by wire number. */ +const PROTOCOLS = new Map([[0, "conformance::Chat"], [1, "conformance::Events"], [2, "conformance::admin::Admin"], [3, "conformance::admin::Alerts"]]); + +/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ +export function negotiated(conn: Peer): Negotiated | undefined { + return conn.extensions.get(Negotiated); +} + +/** + * The protocols that connected although their wire shape differs from the + * peer's at the same version (`same_version_differs = warn`), by path. + */ +export function warnings(conn: Peer): string[] { + return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); +} + +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ +export interface Services { + chat?: ns_conformance.Chat; + admin?: ns_conformance_admin.Admin; +} + +/** + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `conformance::Chat`, line 0.1.0: `send` 1, `leave` 0 + * - `admin`: 2 `conformance::admin::Admin`, line 0.1.0: `kick` 1, `ban` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x02, 0x00, 0x01, + ]), + }, + admin: { + number: 2, + bytes: new Uint8Array([ + 0x02, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x02, 0x00, 0x01, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.admin !== undefined) new ns_conformance_admin.AdminDispatcher(services.admin).provideOn(conn); +} + +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the accepting side provides, which this side calls. + */ +export interface ClientServices { + events?: ns_conformance.Events; + alerts?: ns_conformance_admin.Alerts; +} + +/** + * The protocols the dialling side provides, as a Hello lists each, by their field in `ClientServices`: + * + * - `events`: 1 `conformance::Events`, line 0.1.0: `shown` 0 + * - `alerts`: 3 `conformance::admin::Alerts`, line 0.1.0: `raised` 0 + * + * @internal + */ +export const CLIENT_SERVICES_HELLO: Record = { + events: { + number: 1, + bytes: new Uint8Array([ + 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, + alerts: { + number: 3, + bytes: new Uint8Array([ + 0x03, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideClientServices(conn: Connection, services: ClientServices): void { + if (services.events !== undefined) new ns_conformance.EventsDispatcher(services.events).provideOn(conn); + if (services.alerts !== undefined) new ns_conformance_admin.AlertsDispatcher(services.alerts).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* the protocols in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const agreed = handshake(providedEntries(SERVICES_HELLO, services), Object.values(CLIENT_SERVICES_HELLO)); + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake, then provide the protocols in +* `services`, which the server calls. Call the server's protocols through +* their senders. +*/ +export async function connect(transport: Transport, services: ClientServices = {}): Promise { + const agreed = handshake(providedEntries(CLIENT_SERVICES_HELLO, services), Object.values(SERVICES_HELLO)); + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideClientServices(conn, services); + return conn; +} diff --git a/codegen/tests/golden/connections_subset/typescript/wire.ts b/codegen/tests/golden/connections_subset/typescript/wire.ts new file mode 100644 index 0000000..00237ad --- /dev/null +++ b/codegen/tests/golden/connections_subset/typescript/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x25ae4da556bd5773n; diff --git a/codegen/tests/golden/dependency_and_own_protocols/typescript/connection.ts b/codegen/tests/golden/dependency_and_own_protocols/typescript/connection.ts index 7f6dd4c..7dd5f93 100644 --- a/codegen/tests/golden/dependency_and_own_protocols/typescript/connection.ts +++ b/codegen/tests/golden/dependency_and_own_protocols/typescript/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_api from "./api.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `api::Chat`, line 0.1.0: `greet` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_api.Chat; + chat?: ns_api.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `api::Chat`, line 0.1.0: `greet` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_api.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_api.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/codegen/tests/golden/error_shapes/typescript/connection.ts b/codegen/tests/golden/error_shapes/typescript/connection.ts index 7fb3179..548103c 100644 --- a/codegen/tests/golden/error_shapes/typescript/connection.ts +++ b/codegen/tests/golden/error_shapes/typescript/connection.ts @@ -23,24 +23,26 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - multi: ns_conformance.Multi; - quiet: ns_conformance.Quiet; + multi?: ns_conformance.Multi; + quiet?: ns_conformance.Quiet; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.MultiDispatcher(services.multi).provideOn(conn); - new ns_conformance.QuietDispatcher(services.quiet).provideOn(conn); + if (services.multi !== undefined) new ns_conformance.MultiDispatcher(services.multi).provideOn(conn); + if (services.quiet !== undefined) new ns_conformance.QuietDispatcher(services.quiet).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/format_json/typescript/connection.ts b/codegen/tests/golden/format_json/typescript/connection.ts index 1a1cedb..f0cdfd2 100644 --- a/codegen/tests/golden/format_json/typescript/connection.ts +++ b/codegen/tests/golden/format_json/typescript/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - service: ns_conformance.Service; + service?: ns_conformance.Service; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); + if (services.service !== undefined) new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/framing_datagram3/typescript/connection.ts b/codegen/tests/golden/framing_datagram3/typescript/connection.ts index 0d1f323..5ae1228 100644 --- a/codegen/tests/golden/framing_datagram3/typescript/connection.ts +++ b/codegen/tests/golden/framing_datagram3/typescript/connection.ts @@ -24,22 +24,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - counter: ns_conformance.Counter; + counter?: ns_conformance.Counter; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.CounterDispatcher(services.counter).provideOn(conn); + if (services.counter !== undefined) new ns_conformance.CounterDispatcher(services.counter).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/handshake_comline2/typescript/connection.ts b/codegen/tests/golden/handshake_comline2/typescript/connection.ts index 23e9a02..1de158e 100644 --- a/codegen/tests/golden/handshake_comline2/typescript/connection.ts +++ b/codegen/tests/golden/handshake_comline2/typescript/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_conformance from "./conformance.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `conformance::Chat`, line 0.1.0: `send` 1, `leave` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x02, 0x00, 0x01, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "refuse", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_conformance.Chat; + chat?: ns_conformance.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `conformance::Chat`, line 0.1.0: `send` 1, `leave` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x02, 0x00, 0x01, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_conformance.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/codegen/tests/golden/handshake_none/typescript/connection.ts b/codegen/tests/golden/handshake_none/typescript/connection.ts index 91d1b57..29de8d3 100644 --- a/codegen/tests/golden/handshake_none/typescript/connection.ts +++ b/codegen/tests/golden/handshake_none/typescript/connection.ts @@ -24,22 +24,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - gateway: ns_conformance.Gateway; + gateway?: ns_conformance.Gateway; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.GatewayDispatcher(services.gateway).provideOn(conn); + if (services.gateway !== undefined) new ns_conformance.GatewayDispatcher(services.gateway).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/nested_protocol/typescript/connection.ts b/codegen/tests/golden/nested_protocol/typescript/connection.ts index 82a2972..dfd10ce 100644 --- a/codegen/tests/golden/nested_protocol/typescript/connection.ts +++ b/codegen/tests/golden/nested_protocol/typescript/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_chat_admin from "./chat/admin.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - admin: ns_chat_admin.Admin; + admin?: ns_chat_admin.Admin; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `admin`: 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + admin: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); + if (services.admin !== undefined) new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/codegen/tests/golden/protocol/typescript/connection.ts b/codegen/tests/golden/protocol/typescript/connection.ts index 1a1cedb..f0cdfd2 100644 --- a/codegen/tests/golden/protocol/typescript/connection.ts +++ b/codegen/tests/golden/protocol/typescript/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - service: ns_conformance.Service; + service?: ns_conformance.Service; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); + if (services.service !== undefined) new ns_conformance.ServiceDispatcher(services.service).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/validators/typescript/connection.ts b/codegen/tests/golden/validators/typescript/connection.ts index abe85a9..78b4dba 100644 --- a/codegen/tests/golden/validators/typescript/connection.ts +++ b/codegen/tests/golden/validators/typescript/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - social: ns_conformance.Social; + social?: ns_conformance.Social; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.SocialDispatcher(services.social).provideOn(conn); + if (services.social !== undefined) new ns_conformance.SocialDispatcher(services.social).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/golden/validators_on_decode/typescript/connection.ts b/codegen/tests/golden/validators_on_decode/typescript/connection.ts index abe85a9..78b4dba 100644 --- a/codegen/tests/golden/validators_on_decode/typescript/connection.ts +++ b/codegen/tests/golden/validators_on_decode/typescript/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - social: ns_conformance.Social; + social?: ns_conformance.Social; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_conformance.SocialDispatcher(services.social).provideOn(conn); + if (services.social !== undefined) new ns_conformance.SocialDispatcher(services.social).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/codegen/tests/nested_namespaces.rs b/codegen/tests/nested_namespaces.rs index c0990cc..d148602 100644 --- a/codegen/tests/nested_namespaces.rs +++ b/codegen/tests/nested_namespaces.rs @@ -83,7 +83,7 @@ fn a_nested_protocols_path_is_spelled_with_colons() { let files = generated(&request(&nested_protocol()), "nested"); let connection = file(&files, "connection.ts"); - assert!(connection.contains(" * - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0\n"), "{connection}"); + assert!(connection.contains(" * - `admin`: 0 `chat::admin::Admin`, line 0.1.0: `greet` 0\n"), "{connection}"); assert!(connection.contains("new Map([[0, \"chat::admin::Admin\"]])"), "{connection}"); let admin = file(&files, "chat/admin.ts"); @@ -153,8 +153,8 @@ fn a_dependencys_jsonrpc_method_name_does_not_refuse_generation() { let files = generated(&req, "clash"); assert!(file(&files, "localdeps/greeting.ts").contains("export interface Foo")); let connection = file(&files, "connection.ts"); - assert!(connection.contains("chat: ns_api.Chat;"), "{connection}"); - assert!(connection.contains("events: ns_api.Events;"), "{connection}"); + assert!(connection.contains("chat?: ns_api.Chat;"), "{connection}"); + assert!(connection.contains("events?: ns_api.Events;"), "{connection}"); assert!(!connection.contains("Foo"), "{connection}"); // Two of the package's own still clash, the dependency or not. diff --git a/features.json b/features.json index 57b947a..d42dc3b 100644 --- a/features.json +++ b/features.json @@ -211,7 +211,8 @@ "format_json", "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_json", "dependency_protocol", "dependency_and_own_protocols", - "nested_protocol" + "nested_protocol", + "connections_subset" ], "since": null, "state": "supported", diff --git a/runtime/core/CORE_REV b/runtime/core/CORE_REV index 8c41d4f..0ade478 100644 --- a/runtime/core/CORE_REV +++ b/runtime/core/CORE_REV @@ -1 +1 @@ -8f8c0cb6fb0bc3a734aafbdbbf187fb9da73e00d +e7362217e95f8d22bbce181746562054974e659a diff --git a/runtime/core/SHA256SUMS b/runtime/core/SHA256SUMS index 3016504..740a982 100644 --- a/runtime/core/SHA256SUMS +++ b/runtime/core/SHA256SUMS @@ -1,3 +1,3 @@ -f66b1b675e498295bdd198fff1b1c0eafc2d8d01333562cfb6e7d32df5b98521 comline_runtime_ffi.wasm +3b1912e029766d2b4391451061bb0c48b924c85c22b7086dc8e84d9273cce20a comline_runtime_ffi.wasm db8f8870b5a3e05da2c24378379346dd1629de6c459a5ccfaf5dfdda377ee819 comline.mjs f08ea7adc65102f2d9e9dab5ea82cef6d168373bc088f3886017a40c368315cb comline.d.mts diff --git a/runtime/core/comline_runtime_ffi.wasm b/runtime/core/comline_runtime_ffi.wasm index b709602..8be8cbb 100644 Binary files a/runtime/core/comline_runtime_ffi.wasm and b/runtime/core/comline_runtime_ffi.wasm differ diff --git a/runtime/src/comline2.ts b/runtime/src/comline2.ts index a8feddc..06b9956 100644 --- a/runtime/src/comline2.ts +++ b/runtime/src/comline2.ts @@ -10,7 +10,9 @@ * messages and every decision are the core's, so both runtimes agree byte * for byte. * - * Generated code embeds this end's Hello (its facts, encoded) and the + * Generated code embeds this package's Hello as parts (the header and one + * entry per protocol, its facts encoded), builds this end's Hello from the + * protocols it provides and calls ({@link buildHello}) and the * parameters its package states, runs a {@link Comline2Handshake} when a * connection opens, and keeps what it agreed ({@link Negotiated}) in the * connection's extensions, where each sender checks a call against it before @@ -70,6 +72,36 @@ export class Negotiated { readonly warnings: readonly number[], ) {} + /** + * Whether the handshake accepted `protocol` on this connection: this end's + * Hello listed it and neither end refused it. A protocol this end's result + * doesn't hold (a Hello for a subset leaves protocols out) isn't accepted, + * nor is one it holds as refused. Those are the protocols whose calls fail + * locally ({@link checkCall}) and that a connection won't + * {@link checkProvide}. + */ + accepts(protocol: number): boolean { + return this.protocols.get(protocol)?.accepted === true; + } + + /** + * Throws `RuntimeError("unavailable")` unless this end may provide + * `protocol`: the handshake accepted it ({@link accepts}). The error names + * the protocol by its wire number (`#1`) and why, as {@link checkCall}'s + * does: `unknown_protocol` for one this end's Hello didn't list, the + * refusal's reason for one it holds as refused. A connection's `provide` + * runs this on what its handshake agreed. + * + * It doesn't know direction: a Hello entry says nothing about who implements + * the protocol, so that a side provides only what it provides is for the + * generated code, which knows `@provider`. + */ + checkProvide(protocol: number): void { + const state = this.protocols.get(protocol); + if (state === undefined) throw RuntimeError.unavailable({ protocol: `#${protocol}`, refused: "unknown_protocol" }); + if (!state.accepted) throw RuntimeError.unavailable({ protocol: `#${protocol}`, refused: state.reason }); + } + /** * Throws `RuntimeError("unavailable")`, naming `path` and `name`, unless * this end may call `fn` of `protocol`: the peer lacks the function, or the @@ -95,6 +127,76 @@ export function checkCall(peer: Peer, protocol: number, fn: number, path: string peer.extensions.get(Negotiated)?.checkCall(protocol, fn, path, name); } +/** + * One protocol's entry of a Hello, encoded as the Hello carries it: its wire + * number, the release it last broke at, its shape hash and its function + * numbers, ascending. It carries no direction: an end lists a protocol it + * provides and one it calls the same way, and which is which is for the + * generated code, which knows `@provider`. A generator emits one per protocol. + */ +export interface ProtocolEntry { + /** The protocol's wire number: what orders a Hello's entries. */ + readonly number: number; + /** The entry's bytes, in the Hello's protocol list. */ + readonly bytes: Uint8Array; +} + +/** + * Put together the `comline@2` Hello of one end that provides `provided` and + * calls `called`, mirroring `Hello::build` in the Rust runtime: `header` (the + * Hello up to its protocol list: magic, version, exchange, the package's id + * and version, the encodings) and exactly those protocols' entries, ascending + * by wire number. + * + * - **Union.** The two sets are listed together, as the wire has one list. A + * protocol in both, or an entry given twice, is listed once (the first entry + * given for a number). + * - **Called.** A generator passes every protocol of the other side unless the + * application narrowed what it calls: the peer refuses the ones it doesn't + * have (`unknown_protocol`), and calls to them fail locally. + * - **Everything.** With every protocol of the package's connection among the + * two, the result is the Hello a generator used to embed whole, byte for + * byte. + */ +export function buildHello( + header: Uint8Array, + provided: readonly ProtocolEntry[], + called: readonly ProtocolEntry[], +): Uint8Array { + const listed = new Map(); + for (const entry of [...provided, ...called]) { + if (!listed.has(entry.number)) listed.set(entry.number, entry); + } + const entries = [...listed.values()].sort((a, b) => a.number - b.number); + const count: number[] = []; + for (let n = entries.length; ; n >>>= 7) { + count.push(n > 0x7f ? (n & 0x7f) | 0x80 : n); + if (n <= 0x7f) break; + } + const out = new Uint8Array(header.length + count.length + entries.reduce((n, e) => n + e.bytes.length, 0)); + out.set(header); + out.set(count, header.length); + let at = header.length + count.length; + for (const entry of entries) { + out.set(entry.bytes, at); + at += entry.bytes.length; + } + return out; +} + +/** + * The entries of `table` that `services` holds a value for: `table` maps each + * field of a generated `Services` to its protocol's entry, and a field left + * out (or `undefined`) is a protocol this end doesn't provide. What generated + * `accept` / `connect` give {@link buildHello} as `provided`. + */ +export function providedEntries( + table: Readonly>, + services: Readonly>>, +): ProtocolEntry[] { + return (Object.keys(table) as Field[]).flatMap((field) => (services[field] === undefined ? [] : [table[field]])); +} + const CAP = 1 << 16; /** @@ -107,7 +209,7 @@ export class Comline2Handshake implements Handshake { readonly name = HANDSHAKE_COMLINE2; #negotiated: Negotiated | undefined; - /** `hello` is this end's encoded Hello message, as generated code embeds it. */ + /** `hello` is this end's encoded Hello message: {@link buildHello}'s, from what generated code embeds. */ constructor( readonly hello: Uint8Array, readonly params: Comline2Params = {}, @@ -118,6 +220,11 @@ export class Comline2Handshake implements Handshake { return this.#negotiated; } + /** {@link negotiated}, as a connection asks a handshake for it ({@link Handshake.agreed}). */ + agreed(): Negotiated | undefined { + return this.#negotiated; + } + initiate(transport: Transport, local: Facts): Promise { return this.run(transport, local, 0); } diff --git a/runtime/src/connection.ts b/runtime/src/connection.ts index d2d0ff8..abd8ab1 100644 --- a/runtime/src/connection.ts +++ b/runtime/src/connection.ts @@ -14,6 +14,7 @@ import type { Peer, } from "./contract.js"; import { Extensions, Reply, RuntimeError, resolveKind } from "./contract.js"; +import type { Negotiated } from "./comline2.js"; import { ComlineHandshake, type Handshake } from "./handshake.js"; import type { Transport } from "./transport.js"; import { Datagram2Framing } from "./framing/datagram2.js"; @@ -57,6 +58,11 @@ export class Connection implements Peer { readonly closed: Promise; private readonly providers = new Map(); + /** + * What the connection's handshake agreed, when it negotiated protocol by + * protocol (`comline@2`): what {@link provide} checks against. + */ + private agreed: Negotiated | undefined; private readonly waiting = new Map(); private readonly queue: { protocol: number | undefined; request: DecodedRequest; oneWay: boolean }[] = []; private nextId = 0n; @@ -104,7 +110,9 @@ export class Connection implements Peer { ): Promise { const core = await coreFor(framing); await handshake.initiate(transport, { irHash, wireFormat: codec.name, framing: framing.name }); - return new Connection(transport, codec, framing, core); + const conn = new Connection(transport, codec, framing, core); + conn.agreed = handshake.agreed?.(); + return conn; } /** Answer: run `handshake`'s provider side (`comline@1` unless given). */ @@ -117,11 +125,28 @@ export class Connection implements Peer { ): Promise { const core = await coreFor(framing); await handshake.respond(transport, { irHash, wireFormat: codec.name, framing: framing.name }); - return new Connection(transport, codec, framing, core); + const conn = new Connection(transport, codec, framing, core); + conn.agreed = handshake.agreed?.(); + return conn; } - /** Provide `protocol` on this connection: the peer's requests to it go to `dispatcher`. */ + /** + * Provide `protocol` on this connection: the peer's requests to it go to `dispatcher`. + * + * On a connection whose handshake ran `comline@2`, a protocol the handshake + * didn't accept is refused with `RuntimeError("unavailable")`, and nothing is + * registered: one this end's Hello didn't list (a Hello for a subset leaves + * protocols out), or one the peer refused ({@link Negotiated.checkProvide}). + * A connection with no such handshake (`comline@1`, `none`, or + * {@link Connection.unverified}) has nothing to check against and takes any + * protocol. + * + * Direction isn't checked here: a Hello entry says nothing about who + * implements a protocol, so the generated code checks that a side provides + * only what it provides. + */ provide(protocol: number, dispatcher: Dispatch): void { + this.agreed?.checkProvide(protocol); this.providers.set(protocol, dispatcher); } diff --git a/runtime/src/contract.ts b/runtime/src/contract.ts index 6f49fd7..9255465 100644 --- a/runtime/src/contract.ts +++ b/runtime/src/contract.ts @@ -50,11 +50,15 @@ export type RefusalReason = | "newer_consumer" | "unknown_protocol"; -/** A call `comline@2` stopped before it was sent: which, and why. */ +/** + * A call `comline@2` stopped before it was sent, or a protocol it wouldn't + * let this end provide: which, and why. + */ export interface Unavailable { - /** `namespace::Protocol`. */ + /** `namespace::Protocol`; `#n` for a protocol known only by its wire number (a refused `provide`). */ readonly protocol: string; - readonly function: string; + /** The call; absent when it's the protocol that was refused to be provided. */ + readonly function?: string; /** Why the connection refused the protocol; absent when the peer lacks the function. */ readonly refused?: RefusalReason; } @@ -137,9 +141,17 @@ export class RuntimeError extends Error { e.message = `the ${refusal.side} refused the connection: ${refusal.reason}`; return Object.assign(e, { refusal }); } - /** A call that wasn't sent because the peer can't take it. */ + /** + * A call that wasn't sent because the peer can't take it, or (no `function`) + * a protocol that wasn't provided because the handshake didn't accept it. + */ static unavailable(unavailable: Unavailable): RuntimeError { const e = new RuntimeError("unavailable"); + if (unavailable.function === undefined) { + const why = unavailable.refused === undefined ? "" : ` (${unavailable.refused})`; + e.message = `\`${unavailable.protocol}\` wasn't provided: the handshake didn't accept it${why}`; + return Object.assign(e, { unavailable }); + } const call = `\`${unavailable.protocol}.${unavailable.function}\``; e.message = unavailable.refused === undefined diff --git a/runtime/src/handshake.ts b/runtime/src/handshake.ts index ffb0ce8..4c3beb9 100644 --- a/runtime/src/handshake.ts +++ b/runtime/src/handshake.ts @@ -11,6 +11,7 @@ */ import { RuntimeError } from "./contract.js"; +import type { Negotiated } from "./comline2.js"; import { currentCore } from "./core/core.js"; import type { Transport } from "./transport.js"; @@ -241,6 +242,15 @@ export interface Handshake { initiate(transport: Transport, local: Facts): Promise; /** Run the provider's side over `transport`. */ respond(transport: Transport, local: Facts): Promise; + /** + * What the handshake agreed protocol by protocol, once it has run and + * succeeded: only `comline@2` negotiates that way, so a handshake without + * this has nothing to give. A connection opened with this handshake + * (`Connection.connect`, `accept`) keeps it, and its `provide` refuses a + * protocol the handshake didn't accept. Without one there is nothing to + * check against, and `provide` takes any protocol. + */ + agreed?(): Negotiated | undefined; } /** diff --git a/runtime/src/index.ts b/runtime/src/index.ts index 8f4137b..cbecb88 100644 --- a/runtime/src/index.ts +++ b/runtime/src/index.ts @@ -85,6 +85,9 @@ export { type Comline2Params, Negotiated, type ProtocolState, + type ProtocolEntry, + buildHello, + providedEntries, checkCall, } from "./comline2.js"; export { JsonRpcConnectionFraming, JsonRpcFraming } from "./framing/jsonrpc.js"; diff --git a/runtime/test/conformance/SPEC_REV b/runtime/test/conformance/SPEC_REV index 6857159..75adb03 100644 --- a/runtime/test/conformance/SPEC_REV +++ b/runtime/test/conformance/SPEC_REV @@ -1 +1 @@ -69882e92971e243b6b74a539a13b534d95b3abf7 +3254e0ea0edc8537df453db5ee647cd63715ffe2 diff --git a/runtime/test/conformance/VERSION b/runtime/test/conformance/VERSION index 51176c7..c43e105 100644 --- a/runtime/test/conformance/VERSION +++ b/runtime/test/conformance/VERSION @@ -1 +1 @@ -0.11 +0.12 diff --git a/runtime/test/conformance/vectors/handshake-comline2.json b/runtime/test/conformance/vectors/handshake-comline2.json index 848264f..4b320a9 100644 --- a/runtime/test/conformance/vectors/handshake-comline2.json +++ b/runtime/test/conformance/vectors/handshake-comline2.json @@ -133,6 +133,52 @@ }, "bytes": "434f0201010123456789abcdef0123456789abcdef01c801f0a204056465762e320300111111111111111111111111111111110122222222222222222222222222222222023333333333333333333333333333333303000100000101010101010101010101010101010100ac0201c801000202020202020202020202020202020204007f8001ffff03ffff03000001030303030303030303030303030303030105" }, + { + "id": "handshake-comline2/hello-subset", + "op": "comline2_message", + "input": { + "message": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" + }, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "offer", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1 + ], + "line": { + "major": 0, + "minor": 1, + "patch": 0 + }, + "number": 1, + "shape_hash": "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "type": "hello" + }, + "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330101000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" + }, { "id": "handshake-comline2/hello-empty", "op": "comline2_message", @@ -1728,7 +1774,7 @@ "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330107000300c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c00100" }, { - "id": "handshake-comline2/offer-package-mismatch", + "id": "handshake-comline2/offer-subset-offered", "op": "comline2_negotiate", "input": { "local": { @@ -1791,25 +1837,60 @@ }, "reply": { "message": { - "refuse": { - "reason": "package_mismatch", - "side": "responder" + "accept": { + "protocols": [ + { + "number": 0, + "status": { + "accepted": { + "missing": [], + "shape_differs": false + } + } + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } } }, "type": "answer" }, "result": { - "refused": { - "reason": "package_mismatch", - "side": "responder" + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + }, + { + "number": 1, + "state": { + "refused": { + "reason": "unknown_protocol" + } + } + } + ] } }, "step": "answer_offer" }, - "bytes": "434f020100eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" + "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330100000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a003000102" }, { - "id": "handshake-comline2/offer-encoding-mismatch", + "id": "handshake-comline2/offer-subset-local", "op": "comline2_negotiate", "input": { "local": { @@ -1830,20 +1911,6 @@ "exchange": "offer", "package_id": "0123456789abcdef0123456789abcdef", "protocols": [ - { - "functions": [ - 0, - 1, - 2 - ], - "line": { - "major": 0, - "minor": 2, - "patch": 0 - }, - "number": 0, - "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" - }, { "functions": [ 0, @@ -1872,25 +1939,60 @@ }, "reply": { "message": { - "refuse": { - "reason": "encoding_mismatch", - "side": "responder" + "accept": { + "protocols": [ + { + "number": 0, + "status": { + "refused": { + "reason": "unknown_protocol" + } + } + }, + { + "number": 1, + "status": { + "accepted": { + "missing": [], + "shape_differs": false + } + } + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } } }, "type": "answer" }, "result": { - "refused": { - "reason": "encoding_mismatch", - "side": "responder" + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 1, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] } }, "step": "answer_offer" }, - "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030012121212121212121212121212121212012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" + "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" }, { - "id": "handshake-comline2/offer-exchange-mismatch", + "id": "handshake-comline2/offer-package-mismatch", "op": "comline2_negotiate", "input": { "local": { @@ -1954,7 +2056,7 @@ "reply": { "message": { "refuse": { - "reason": "exchange_mismatch", + "reason": "package_mismatch", "side": "responder" } }, @@ -1962,16 +2064,16 @@ }, "result": { "refused": { - "reason": "exchange_mismatch", + "reason": "package_mismatch", "side": "responder" } }, "step": "answer_offer" }, - "bytes": "434f0201010123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" + "bytes": "434f020100eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" }, { - "id": "handshake-comline2/offer-malformed", + "id": "handshake-comline2/offer-encoding-mismatch", "op": "comline2_negotiate", "input": { "local": { @@ -2035,7 +2137,7 @@ "reply": { "message": { "refuse": { - "reason": "malformed", + "reason": "encoding_mismatch", "side": "responder" } }, @@ -2043,16 +2145,16 @@ }, "result": { "refused": { - "reason": "malformed", + "reason": "encoding_mismatch", "side": "responder" } }, "step": "answer_offer" }, - "bytes": "68656c6c6f" + "bytes": "434f0201000123456789abcdef0123456789abcdef00030000030012121212121212121212121212121212012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" }, { - "id": "handshake-comline2/offer-handshake-version", + "id": "handshake-comline2/offer-exchange-mismatch", "op": "comline2_negotiate", "input": { "local": { @@ -2116,7 +2218,7 @@ "reply": { "message": { "refuse": { - "reason": "handshake_version", + "reason": "exchange_mismatch", "side": "responder" } }, @@ -2124,16 +2226,16 @@ }, "result": { "refused": { - "reason": "handshake_version", + "reason": "exchange_mismatch", "side": "responder" } }, "step": "answer_offer" }, - "bytes": "434f010100000000000000e6960a06851063366b50a199ba43a44400000000" + "bytes": "434f0201010123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" }, { - "id": "handshake-comline2/conclude-accept", + "id": "handshake-comline2/offer-malformed", "op": "comline2_negotiate", "input": { "local": { @@ -2196,45 +2298,25 @@ }, "reply": { "message": { - "accept": { - "refused": [] + "refuse": { + "reason": "malformed", + "side": "responder" } }, - "type": "verdict" + "type": "answer" }, "result": { - "accepted": { - "peer_version": { - "major": 0, - "minor": 3, - "patch": 0 - }, - "protocols": [ - { - "number": 0, - "state": { - "accepted": { - "peer_lacks": [] - } - } - }, - { - "number": 1, - "state": { - "accepted": { - "peer_lacks": [] - } - } - } - ] + "refused": { + "reason": "malformed", + "side": "responder" } }, - "step": "conclude_answer" + "step": "answer_offer" }, - "bytes": "434f0202000003000002000000010000" + "bytes": "68656c6c6f" }, { - "id": "handshake-comline2/conclude-degrade", + "id": "handshake-comline2/offer-handshake-version", "op": "comline2_negotiate", "input": { "local": { @@ -2297,22 +2379,204 @@ }, "reply": { "message": { - "accept": { - "refused": [] + "refuse": { + "reason": "handshake_version", + "side": "responder" } }, - "type": "verdict" + "type": "answer" }, "result": { - "accepted": { - "peer_version": { - "major": 0, - "minor": 2, - "patch": 1 + "refused": { + "reason": "handshake_version", + "side": "responder" + } + }, + "step": "answer_offer" + }, + "bytes": "434f010100000000000000e6960a06851063366b50a199ba43a44400000000" + }, + { + "id": "handshake-comline2/conclude-accept", + "op": "comline2_negotiate", + "input": { + "local": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" }, - "protocols": [ - { - "number": 0, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "offer", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1, + 2 + ], + "line": { + "major": 0, + "minor": 2, + "patch": 0 + }, + "number": 0, + "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" + }, + { + "functions": [ + 0, + 1 + ], + "line": { + "major": 0, + "minor": 1, + "patch": 0 + }, + "number": 1, + "shape_hash": "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "params": { + "exchange": "offer", + "newer_consumer": "degrade", + "same_version_differs": "refuse", + "scope": "protocol" + }, + "reply": { + "message": { + "accept": { + "refused": [] + } + }, + "type": "verdict" + }, + "result": { + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + }, + { + "number": 1, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] + } + }, + "step": "conclude_answer" + }, + "bytes": "434f0202000003000002000000010000" + }, + { + "id": "handshake-comline2/conclude-degrade", + "op": "comline2_negotiate", + "input": { + "local": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" + }, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "offer", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1, + 2 + ], + "line": { + "major": 0, + "minor": 2, + "patch": 0 + }, + "number": 0, + "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" + }, + { + "functions": [ + 0, + 1 + ], + "line": { + "major": 0, + "minor": 1, + "patch": 0 + }, + "number": 1, + "shape_hash": "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "params": { + "exchange": "offer", + "newer_consumer": "degrade", + "same_version_differs": "refuse", + "scope": "protocol" + }, + "reply": { + "message": { + "accept": { + "refused": [] + } + }, + "type": "verdict" + }, + "result": { + "accepted": { + "peer_version": { + "major": 0, + "minor": 2, + "patch": 1 + }, + "protocols": [ + { + "number": 0, "state": { "accepted": { "peer_lacks": [ @@ -2909,6 +3173,154 @@ }, "bytes": "434f0202010501" }, + { + "id": "handshake-comline2/conclude-subset", + "op": "comline2_negotiate", + "input": { + "local": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" + }, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "offer", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1, + 2 + ], + "line": { + "major": 0, + "minor": 2, + "patch": 0 + }, + "number": 0, + "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "params": { + "exchange": "offer", + "newer_consumer": "degrade", + "same_version_differs": "refuse", + "scope": "protocol" + }, + "reply": { + "message": { + "accept": { + "refused": [] + } + }, + "type": "verdict" + }, + "result": { + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] + } + }, + "step": "conclude_answer" + }, + "bytes": "434f0202000003000001000000" + }, + { + "id": "handshake-comline2/conclude-answer-beyond-offer", + "op": "comline2_negotiate", + "input": { + "local": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" + }, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "offer", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1, + 2 + ], + "line": { + "major": 0, + "minor": 2, + "patch": 0 + }, + "number": 0, + "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "params": { + "exchange": "offer", + "newer_consumer": "degrade", + "same_version_differs": "refuse", + "scope": "protocol" + }, + "reply": { + "message": { + "refuse": { + "reason": "malformed", + "side": "initiator" + } + }, + "type": "verdict" + }, + "result": { + "refused": { + "reason": "malformed", + "side": "initiator" + } + }, + "step": "conclude_answer" + }, + "bytes": "434f0202000003000002000000010000" + }, { "id": "handshake-comline2/conclude-malformed", "op": "comline2_negotiate", @@ -3598,6 +4010,92 @@ }, "bytes": "434f0201010123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330100000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a003000102" }, + { + "id": "handshake-comline2/symmetric-subset-local", + "op": "comline2_negotiate", + "input": { + "local": { + "encodings": [ + { + "kind": "format", + "param_hash": "11111111111111111111111111111111" + }, + { + "kind": "framing", + "param_hash": "22222222222222222222222222222222" + }, + { + "kind": "handshake", + "param_hash": "33333333333333333333333333333333" + } + ], + "exchange": "symmetric", + "package_id": "0123456789abcdef0123456789abcdef", + "protocols": [ + { + "functions": [ + 0, + 1, + 2 + ], + "line": { + "major": 0, + "minor": 2, + "patch": 0 + }, + "number": 0, + "shape_hash": "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0" + } + ], + "version": { + "major": 0, + "minor": 3, + "patch": 0 + } + }, + "params": { + "exchange": "symmetric", + "newer_consumer": "degrade", + "same_version_differs": "refuse", + "scope": "protocol" + }, + "reply": { + "message": { + "accept": { + "refused": [ + { + "number": 1, + "reason": "unknown_protocol" + } + ] + } + }, + "type": "verdict" + }, + "result": { + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] + } + }, + "side": "initiator", + "step": "judge_hello" + }, + "bytes": "434f0201010123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001" + }, { "id": "handshake-comline2/symmetric-same-version-differs-warn", "op": "comline2_negotiate", @@ -3987,6 +4485,51 @@ }, "bytes": "434f020300010008" }, + { + "id": "handshake-comline2/finish-refused-unlisted", + "op": "comline2_negotiate", + "input": { + "pending": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] + }, + "result": { + "accepted": { + "peer_version": { + "major": 0, + "minor": 3, + "patch": 0 + }, + "protocols": [ + { + "number": 0, + "state": { + "accepted": { + "peer_lacks": [] + } + } + } + ] + } + }, + "side": "initiator", + "step": "finish" + }, + "bytes": "434f020300010109" + }, { "id": "handshake-comline2/finish-refused", "op": "comline2_negotiate", diff --git a/runtime/test/generated-subset.test.ts b/runtime/test/generated-subset.test.ts new file mode 100644 index 0000000..b7ebf35 --- /dev/null +++ b/runtime/test/generated-subset.test.ts @@ -0,0 +1,139 @@ +// Exercises a side that provides a subset: the package from +// `generated/subset/`, written by `comline-codegen-typescript`'s +// `generated_subset_matches_the_runtime_test_fixture` test. Two applications +// in one package: `Chat` (0) and `Admin` (2) are the server's, `Events` (1) +// and `Alerts` (3) the client's. +// +// The Hello each end sends lists what it provides and what it calls, so what +// an end leaves out is out of its Hello, and a connection provides nothing the +// handshake didn't accept. + +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { Connection, Datagram3Framing, duplex, RuntimeError, type Peer } from "../src/index.js"; +import { + CONNECTION_IR_HASH, + Format, + SERVICES_HELLO, + accept, + connect, + handshake, + negotiated, + provideServices, +} from "./generated/subset/connection.js"; +import { AdminDispatcher, AdminSender, type Admin } from "./generated/subset/admin.js"; +import { ChatSender, type Chat } from "./generated/subset/public.js"; + +const chat: Chat = { + async send(_peer: Peer, { text }): Promise { + return text.length; + }, +}; + +const admin: Admin = { + async kick(): Promise {}, +}; + +const framing = () => new Datagram3Framing(); + +/** The protocols the handshake of `conn` accepted, by wire number. */ +const accepted = (conn: Peer, numbers: number[]): number[] => { + const agreed = negotiated(conn); + assert.ok(agreed); + return numbers.filter((n) => agreed.accepts(n)); +}; + +test("a server provides a subset, and the client calls the rest in vain", async () => { + const [dialler, acceptor] = duplex(); + const served = accept(acceptor, { chat }); + const conn = await connect(dialler); + const server = await served; + + // The client lists `Chat` and `Admin` (what it calls), the server `Chat` + // (what it provides) and the client's `Events` and `Alerts` (what it calls). + // `Admin` isn't in the server's Hello, and `Alerts` isn't in the client's. + assert.deepEqual(accepted(conn, [0, 1, 2, 3]), [0]); + assert.deepEqual(accepted(server, [0, 1, 2, 3]), [0]); + assert.deepEqual(negotiated(conn)?.protocols.get(2), { accepted: false, reason: "unknown_protocol" }); + + assert.equal(await new ChatSender(conn).send({ text: "hey" }), 3); + await assert.rejects(new AdminSender(conn).kick({ user: 1 }), (e: unknown) => { + assert.ok(e instanceof RuntimeError && e.is("unavailable")); + assert.deepEqual(e.unavailable, { protocol: "admin::Admin", function: "kick", refused: "unknown_protocol" }); + return true; + }); + + dialler.close(); + await server.closed; +}); + +test("every protocol provided is the package's whole Hello", async () => { + const [dialler, acceptor] = duplex(); + const served = accept(acceptor, { chat, admin }); + const conn = await connect(dialler, { events: { async shown() { return true; } }, alerts: { async raised() {} } }); + const server = await served; + assert.deepEqual(accepted(conn, [0, 1, 2, 3]), [0, 1, 2, 3]); + assert.deepEqual(accepted(server, [0, 1, 2, 3]), [0, 1, 2, 3]); + await new AdminSender(conn).kick({ user: 7 }); + dialler.close(); + await server.closed; +}); + +test("dialling with nothing provided takes no services", async () => { + const [dialler, acceptor] = duplex(); + const served = accept(acceptor, { chat }); + await connect(dialler); + const server = await served; + dialler.close(); + await server.closed; +}); + +test("provide refuses a protocol the Hello didn't list", async () => { + // An end whose Hello lists `Chat` alone, as a hand-written one might. + const [dialler, acceptor] = duplex(); + const served = Connection.accept(acceptor, Format, CONNECTION_IR_HASH, framing(), handshake([SERVICES_HELLO.chat], [])); + const dialled = connect(dialler); + const server = await served; + await dialled; + + assert.throws( + () => new AdminDispatcher(admin).provideOn(server), + (e: unknown) => { + assert.ok(e instanceof RuntimeError && e.is("unavailable")); + assert.deepEqual(e.unavailable, { protocol: "#2", refused: "unknown_protocol" }); + assert.equal(e.message, "`#2` wasn't provided: the handshake didn't accept it (unknown_protocol)"); + return true; + }, + ); + // What it listed goes through, and nothing was registered for `Admin`. + assert.doesNotThrow(() => server.provide(0, { calls: () => [], dispatch: async () => {} })); + dialler.close(); +}); + +test("provide refuses a protocol the peer refused", async () => { + // The client's Hello leaves `Admin` out, so the server's `Admin` is refused. + const [dialler, acceptor] = duplex(); + const dialled = Connection.connect(dialler, Format, CONNECTION_IR_HASH, framing(), handshake([], [SERVICES_HELLO.chat])); + const served = accept(acceptor, { chat, admin }); + // Settled as it rejects, which may be before the client is done. + const refused = assert.rejects(served, (e: unknown) => { + assert.ok(e instanceof RuntimeError && e.is("unavailable")); + assert.deepEqual(e.unavailable, { protocol: "#2", refused: "unknown_protocol" }); + return true; + }); + await dialled; + await refused; + dialler.close(); +}); + +test("a connection with no Hello provides anything", async () => { + const [dialler, acceptor] = duplex(); + const served = Connection.accept(acceptor, Format, CONNECTION_IR_HASH); + const dialled = Connection.connect(dialler, Format, CONNECTION_IR_HASH); + const server = await served; + await dialled; + // `comline@1` carries no Hello: there's nothing to check against. + assert.doesNotThrow(() => provideServices(server, { chat, admin })); + dialler.close(); +}); diff --git a/runtime/test/generated/bounds/connection.ts b/runtime/test/generated/bounds/connection.ts index 0751cec..0ba865e 100644 --- a/runtime/test/generated/bounds/connection.ts +++ b/runtime/test/generated/bounds/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - directory: ns_account.Directory; + directory?: ns_account.Directory; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_account.DirectoryDispatcher(services.directory).provideOn(conn); + if (services.directory !== undefined) new ns_account.DirectoryDispatcher(services.directory).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/runtime/test/generated/clash/connection.ts b/runtime/test/generated/clash/connection.ts index a19b5c9..5f41652 100644 --- a/runtime/test/generated/clash/connection.ts +++ b/runtime/test/generated/clash/connection.ts @@ -19,7 +19,10 @@ import { JsonRpcConnectionFraming, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_api from "./api.js"; @@ -29,34 +32,29 @@ import { CONNECTION_IR_HASH } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `api::Chat`, line 0.1.0: `greet` 0 - * - 1 `api::Events`, line 0.1.0: `notify` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0xff, 0xa1, 0x4e, 0xb2, 0xbc, 0x0a, 0xe6, 0x18, 0x4d, 0x69, 0xb5, 0xac, 0xc5, 0x70, 0x91, 0x7e, 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, - 0x01, 0x00, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -80,39 +78,79 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_api.Chat; + chat?: ns_api.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `api::Chat`, line 0.1.0: `greet` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_api.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_api.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the accepting side provides, which this side calls. + */ export interface ClientServices { - events: ns_api.Events; + events?: ns_api.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the dialling side provides, as a Hello lists each, by their field in `ClientServices`: + * + * - `events`: 1 `api::Events`, line 0.1.0: `notify` 0 + * + * @internal + */ +export const CLIENT_SERVICES_HELLO: Record = { + events: { + number: 1, + bytes: new Uint8Array([ + 0x01, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_api.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_api.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), Object.values(CLIENT_SERVICES_HELLO)); const conn = await Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -125,12 +163,12 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); +export async function connect(transport: Transport, services: ClientServices = {}): Promise { + const agreed = handshake(providedEntries(CLIENT_SERVICES_HELLO, services), Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming(), agreed); conn.extensions.set(agreed.negotiated!); provideClientServices(conn, services); diff --git a/runtime/test/generated/collisions/connection.ts b/runtime/test/generated/collisions/connection.ts index 5a4e02c..785aca0 100644 --- a/runtime/test/generated/collisions/connection.ts +++ b/runtime/test/generated/collisions/connection.ts @@ -24,24 +24,26 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - wire: ns_shapes.Wire; - again: ns_user.Again; + wire?: ns_shapes.Wire; + again?: ns_user.Again; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_shapes.WireDispatcher(services.wire).provideOn(conn); - new ns_user.AgainDispatcher(services.again).provideOn(conn); + if (services.wire !== undefined) new ns_shapes.WireDispatcher(services.wire).provideOn(conn); + if (services.again !== undefined) new ns_user.AgainDispatcher(services.again).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/runtime/test/generated/comline2/alien/connection.ts b/runtime/test/generated/comline2/alien/connection.ts index 4be8eea..4930e63 100644 --- a/runtime/test/generated/comline2/alien/connection.ts +++ b/runtime/test/generated/comline2/alien/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `fedcba9876543210fedcba9876543210`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `fedcba9876543210fedcba9876543210`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 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, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0x02, 0x00, 0x01, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_chat.Chat; + chat?: ns_chat.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x02, 0x00, 0x01, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_chat.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/runtime/test/generated/comline2/new/connection.ts b/runtime/test/generated/comline2/new/connection.ts index 90aff57..9617f16 100644 --- a/runtime/test/generated/comline2/new/connection.ts +++ b/runtime/test/generated/comline2/new/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.2.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::Chat`, line 0.1.0: `shout` 1, `whisper` 2, `hello` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.2.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x02, 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, 0xbb, 0xbb, - 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, - 0xbb, 0xbb, 0x03, 0x00, 0x01, 0x02, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_chat.Chat; + chat?: ns_chat.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `chat::Chat`, line 0.1.0: `shout` 1, `whisper` 2, `hello` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, + 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0x03, 0x00, 0x01, 0x02, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_chat.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/runtime/test/generated/comline2/old/connection.ts b/runtime/test/generated/comline2/old/connection.ts index 1268d00..9474253 100644 --- a/runtime/test/generated/comline2/old/connection.ts +++ b/runtime/test/generated/comline2/old/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0x02, 0x00, 0x01, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_chat.Chat; + chat?: ns_chat.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x02, 0x00, 0x01, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_chat.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/runtime/test/generated/dependency/own/connection.ts b/runtime/test/generated/dependency/own/connection.ts index 7f6dd4c..7dd5f93 100644 --- a/runtime/test/generated/dependency/own/connection.ts +++ b/runtime/test/generated/dependency/own/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_api from "./api.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `api::Chat`, line 0.1.0: `greet` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - chat: ns_api.Chat; + chat?: ns_api.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `api::Chat`, line 0.1.0: `greet` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_api.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_api.ChatDispatcher(services.chat).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/runtime/test/generated/hello/connection.ts b/runtime/test/generated/hello/connection.ts index 0f8f42d..4cb6d28 100644 --- a/runtime/test/generated/hello/connection.ts +++ b/runtime/test/generated/hello/connection.ts @@ -24,22 +24,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - link: ns_hello.Link; + link?: ns_hello.Link; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_hello.LinkDispatcher(services.link).provideOn(conn); + if (services.link !== undefined) new ns_hello.LinkDispatcher(services.link).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/runtime/test/generated/link/connection.ts b/runtime/test/generated/link/connection.ts index e290d9d..48e2d8f 100644 --- a/runtime/test/generated/link/connection.ts +++ b/runtime/test/generated/link/connection.ts @@ -23,35 +23,39 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - chat: ns_link.Chat; + chat?: ns_link.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_link.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_link.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_link.Events; + events?: ns_link.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_link.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_link.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -66,11 +70,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); provideClientServices(conn, services); return conn; diff --git a/runtime/test/generated/link_jsonrpc/connection.ts b/runtime/test/generated/link_jsonrpc/connection.ts index cb521da..705d64e 100644 --- a/runtime/test/generated/link_jsonrpc/connection.ts +++ b/runtime/test/generated/link_jsonrpc/connection.ts @@ -25,35 +25,39 @@ import { CONNECTION_IR_HASH } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - chat: ns_link.Chat; + chat?: ns_link.Chat; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_link.ChatDispatcher(services.chat).provideOn(conn); + if (services.chat !== undefined) new ns_link.ChatDispatcher(services.chat).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_link.Events; + events?: ns_link.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_link.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_link.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -68,11 +72,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); provideClientServices(conn, services); return conn; diff --git a/runtime/test/generated/nested/connection.ts b/runtime/test/generated/nested/connection.ts index 82a2972..dfd10ce 100644 --- a/runtime/test/generated/nested/connection.ts +++ b/runtime/test/generated/nested/connection.ts @@ -18,7 +18,10 @@ import { Datagram3Framing, Comline2Handshake, Negotiated, + buildHello, + providedEntries, type Peer, + type ProtocolEntry, type Transport, } from "@comline/runtime"; import * as ns_chat_admin from "./chat/admin.js"; @@ -28,31 +31,29 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** - * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history - * records it. Its protocols, by wire number: - * - * - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. * * @internal */ -export const HELLO = new Uint8Array([ +export const HELLO_HEADER = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, - 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x01, 0x00, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, ]); /** - * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. * @internal */ -export function handshake(): Comline2Handshake { - return new Comline2Handshake(HELLO, { +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { scope: "protocol", newerConsumer: "degrade", sameVersionDiffers: "refuse", @@ -76,26 +77,46 @@ export function warnings(conn: Peer): string[] { return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); } -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ export interface Services { - admin: ns_chat_admin.Admin; + admin?: ns_chat_admin.Admin; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `admin`: 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + admin: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); + if (services.admin !== undefined) new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake(providedEntries(SERVICES_HELLO, services), []); const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); provideServices(conn, services); @@ -112,7 +133,7 @@ export async function serve(transport: Transport, services: Services): Promise { - const agreed = handshake(); + const agreed = handshake([], Object.values(SERVICES_HELLO)); const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); conn.extensions.set(agreed.negotiated!); return conn; diff --git a/runtime/test/generated/reserved/connection.ts b/runtime/test/generated/reserved/connection.ts index 01b5cac..7906cb9 100644 --- a/runtime/test/generated/reserved/connection.ts +++ b/runtime/test/generated/reserved/connection.ts @@ -23,22 +23,24 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - static: ns_names.static_; + static?: ns_names.static_; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_names.staticDispatcher(services.static).provideOn(conn); + if (services.static !== undefined) new ns_names.staticDispatcher(services.static).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { diff --git a/runtime/test/generated/services/connection.ts b/runtime/test/generated/services/connection.ts index b120e5b..2c338a1 100644 --- a/runtime/test/generated/services/connection.ts +++ b/runtime/test/generated/services/connection.ts @@ -24,39 +24,43 @@ import { CONNECTION_IR_HASH, Format } from "./wire.js"; /** The package's wire format and the digest of every schema in it, which every file of the package shares. */ export { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + */ export interface Services { - account: ns_game.Account; - player: ns_game.Player; - inventory: ns_items.Inventory; + account?: ns_game.Account; + player?: ns_game.Player; + inventory?: ns_items.Inventory; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideServices(conn: Connection, services: Services): void { - new ns_game.AccountDispatcher(services.account).provideOn(conn); - new ns_game.PlayerDispatcher(services.player).provideOn(conn); - new ns_items.InventoryDispatcher(services.inventory).provideOn(conn); + if (services.account !== undefined) new ns_game.AccountDispatcher(services.account).provideOn(conn); + if (services.player !== undefined) new ns_game.PlayerDispatcher(services.player).provideOn(conn); + if (services.inventory !== undefined) new ns_items.InventoryDispatcher(services.inventory).provideOn(conn); } -/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + */ export interface ClientServices { - events: ns_items.Events; + events?: ns_items.Events; } /** - * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. * @internal */ export function provideClientServices(conn: Connection, services: ClientServices): void { - new ns_items.EventsDispatcher(services.events).provideOn(conn); + if (services.events !== undefined) new ns_items.EventsDispatcher(services.events).provideOn(conn); } /** * Accept a connection over `transport`: run the handshake, then provide -* every protocol in `services` on it. The connection comes back serving, +* the protocols in `services` on it. The connection comes back serving, * so the server can call the client through it. */ export async function accept(transport: Transport, services: Services): Promise { @@ -71,11 +75,11 @@ export async function serve(transport: Transport, services: Services): Promise { +export async function connect(transport: Transport, services: ClientServices = {}): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); provideClientServices(conn, services); return conn; diff --git a/runtime/test/generated/subset/admin.ts b/runtime/test/generated/subset/admin.ts new file mode 100644 index 0000000..6712b02 --- /dev/null +++ b/runtime/test/generated/subset/admin.ts @@ -0,0 +1,168 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0x3bc15e97071208ean; + +export interface AdminKickParams { + user: number; +} + +/** @internal */ +export const AdminKickParamsLayout: Layout = { struct: [["user", "u32"]] }; + +export interface Admin { + kick(peer: Peer, params: AdminKickParams): Promise; +} + +/** @internal */ +export const ADMIN_CALLS = ["kick"] as const; + +/** @internal */ +export class AdminDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 2; + + private readonly impl: Admin; + + constructor(impl: Admin) { + this.impl = impl; + } + + calls(): readonly string[] { + return ADMIN_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, AdminKickParamsLayout); + await this.impl.kick(peer, p); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(AdminDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Admin` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class AdminSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 2; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async kick(params: AdminKickParams): Promise { + checkCall(this.peer, AdminSender.PROTOCOL, 0, "admin::Admin", "kick"); + await this.peer.notify(AdminSender.PROTOCOL, { id: 0, name: "kick" }, params, { layout: AdminKickParamsLayout }); + } +} + +export interface AlertsRaisedParams { + code: number; +} + +/** @internal */ +export const AlertsRaisedParamsLayout: Layout = { struct: [["code", "u32"]] }; + +export interface Alerts { + raised(peer: Peer, params: AlertsRaisedParams): Promise; +} + +/** @internal */ +export const ALERTS_CALLS = ["raised"] as const; + +/** @internal */ +export class AlertsDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 3; + + private readonly impl: Alerts; + + constructor(impl: Alerts) { + this.impl = impl; + } + + calls(): readonly string[] { + return ALERTS_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, AlertsRaisedParamsLayout); + await this.impl.raised(peer, p); + } catch { + /* one-way: nowhere to report this */ + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(AlertsDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Alerts` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class AlertsSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 3; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async raised(params: AlertsRaisedParams): Promise { + checkCall(this.peer, AlertsSender.PROTOCOL, 0, "admin::Alerts", "raised"); + await this.peer.notify(AlertsSender.PROTOCOL, { id: 0, name: "raised" }, params, { layout: AlertsRaisedParamsLayout }); + } +} + diff --git a/runtime/test/generated/subset/connection.ts b/runtime/test/generated/subset/connection.ts new file mode 100644 index 0000000..530e466 --- /dev/null +++ b/runtime/test/generated/subset/connection.ts @@ -0,0 +1,196 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./public.js`); `Admin`, `Alerts` (in `./admin.js`). + * - Serve with `serve(transport, { chat, admin })`; `accept(transport, { chat, admin })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events, alerts })`. + * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + Datagram3Framing, + Comline2Handshake, + Negotiated, + buildHello, + providedEntries, + type Peer, + type ProtocolEntry, + type Transport, +} from "@comline/runtime"; +import * as ns_admin from "./admin.js"; +import * as ns_public from "./public.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** + * This package's `comline@2` Hello up to its list of protocols: version 0.1.0 of package + * `0123456789abcdef0123456789abcdef`, as its history records it. {@link buildHello} adds the protocols an end + * provides and calls. + * + * @internal + */ +export const HELLO_HEADER = new Uint8Array([ + 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, + 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, + 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, + 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, + 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, + 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, +]); + +/** + * The `comline@2` handshake of an end that provides `provided` and calls `called`, with their + * Hello ({@link HELLO_HEADER}, then those protocols) and the parameters the package states. + * @internal + */ +export function handshake(provided: readonly ProtocolEntry[], called: readonly ProtocolEntry[]): Comline2Handshake { + return new Comline2Handshake(buildHello(HELLO_HEADER, provided, called), { + scope: "protocol", + newerConsumer: "degrade", + sameVersionDiffers: "refuse", + exchange: "offer", + }); +} + +/** The package's protocols on the connection, by wire number. */ +const PROTOCOLS = new Map([[0, "public::Chat"], [1, "public::Events"], [2, "admin::Admin"], [3, "admin::Alerts"]]); + +/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ +export function negotiated(conn: Peer): Negotiated | undefined { + return conn.extensions.get(Negotiated); +} + +/** + * The protocols that connected although their wire shape differs from the + * peer's at the same version (`same_version_differs = warn`), by path. + */ +export function warnings(conn: Peer): string[] { + return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); +} + +/** + * What the accepting side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the dialling side provides, which this side calls. + */ +export interface Services { + chat?: ns_public.Chat; + admin?: ns_admin.Admin; +} + +/** + * The protocols the accepting side provides, as a Hello lists each, by their field in `Services`: + * + * - `chat`: 0 `public::Chat`, line 0.1.0: `send` 0 + * - `admin`: 2 `admin::Admin`, line 0.1.0: `kick` 0 + * + * @internal + */ +export const SERVICES_HELLO: Record = { + chat: { + number: 0, + bytes: new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x01, 0x00, + ]), + }, + admin: { + number: 2, + bytes: new Uint8Array([ + 0x02, 0x00, 0x01, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, + 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + if (services.chat !== undefined) new ns_public.ChatDispatcher(services.chat).provideOn(conn); + if (services.admin !== undefined) new ns_admin.AdminDispatcher(services.admin).provideOn(conn); +} + +/** + * What the dialling side provides, a field per protocol: leave one out to not provide it. + * The Hello lists the ones given, and the protocols the accepting side provides, which this side calls. + */ +export interface ClientServices { + events?: ns_public.Events; + alerts?: ns_admin.Alerts; +} + +/** + * The protocols the dialling side provides, as a Hello lists each, by their field in `ClientServices`: + * + * - `events`: 1 `public::Events`, line 0.1.0: `shown` 0 + * - `alerts`: 3 `admin::Alerts`, line 0.1.0: `raised` 0 + * + * @internal + */ +export const CLIENT_SERVICES_HELLO: Record = { + events: { + number: 1, + bytes: new Uint8Array([ + 0x01, 0x00, 0x01, 0x00, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, + 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0x01, 0x00, + ]), + }, + alerts: { + number: 3, + bytes: new Uint8Array([ + 0x03, 0x00, 0x01, 0x00, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, + 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0x01, 0x00, + ]), + }, +}; + +/** + * Provide each protocol `services` holds on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideClientServices(conn: Connection, services: ClientServices): void { + if (services.events !== undefined) new ns_public.EventsDispatcher(services.events).provideOn(conn); + if (services.alerts !== undefined) new ns_admin.AlertsDispatcher(services.alerts).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* the protocols in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const agreed = handshake(providedEntries(SERVICES_HELLO, services), Object.values(CLIENT_SERVICES_HELLO)); + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake, then provide the protocols in +* `services`, which the server calls. Call the server's protocols through +* their senders. +*/ +export async function connect(transport: Transport, services: ClientServices = {}): Promise { + const agreed = handshake(providedEntries(CLIENT_SERVICES_HELLO, services), Object.values(SERVICES_HELLO)); + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + provideClientServices(conn, services); + return conn; +} diff --git a/runtime/test/generated/subset/public.ts b/runtime/test/generated/subset/public.ts new file mode 100644 index 0000000..c878ab0 --- /dev/null +++ b/runtime/test/generated/subset/public.ts @@ -0,0 +1,174 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** Canonical digest of the frozen IR this file was generated from — the +* two ends of a connection must agree on it. */ +export const IR_HASH = 0x73062149064e1bebn; + +export interface ChatSendParams { + text: string; +} + +/** @internal */ +export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; + +export interface Chat { + send(peer: Peer, params: ChatSendParams): Promise; +} + +/** @internal */ +export const CHAT_CALLS = ["send"] as const; + +/** @internal */ +export class ChatDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Chat; + + constructor(impl: Chat) { + this.impl = impl; + } + + calls(): readonly string[] { + return CHAT_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, ChatSendParamsLayout); + reply.ok(codec.encode((await this.impl.send(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(ChatDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class ChatSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async send(params: ChatSendParams): Promise { + checkCall(this.peer, ChatSender.PROTOCOL, 0, "public::Chat", "send"); + const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "send" }, params, { layout: ChatSendParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + +export interface EventsShownParams { + n: number; +} + +/** @internal */ +export const EventsShownParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Events { + shown(peer: Peer, params: EventsShownParams): Promise; +} + +/** @internal */ +export const EVENTS_CALLS = ["shown"] as const; + +/** @internal */ +export class EventsDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly impl: Events; + + constructor(impl: Events) { + this.impl = impl; + } + + calls(): readonly string[] { + return EVENTS_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, EventsShownParamsLayout); + reply.ok(codec.encode((await this.impl.shown(peer, p)) ?? null, "bool")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(EventsDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Events` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class EventsSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 1; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async shown(params: EventsShownParams): Promise { + checkCall(this.peer, EventsSender.PROTOCOL, 0, "public::Events", "shown"); + const env = await this.peer.call(EventsSender.PROTOCOL, { id: 0, name: "shown" }, params, { layout: EventsShownParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "bool"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + diff --git a/runtime/test/generated/subset/wire.ts b/runtime/test/generated/subset/wire.ts new file mode 100644 index 0000000..8916ec9 --- /dev/null +++ b/runtime/test/generated/subset/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x572df8ce2206ff29n; diff --git a/runtime/test/hello-build.test.ts b/runtime/test/hello-build.test.ts new file mode 100644 index 0000000..31a7d14 --- /dev/null +++ b/runtime/test/hello-build.test.ts @@ -0,0 +1,84 @@ +// `buildHello` against the specification's `comline@2` Hello cases: a Hello +// put together from a header and protocol entries is the `hello` case's bytes +// with every protocol among them, and `hello-subset`'s with one (spec 0.12). + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { buildHello, type ProtocolEntry } from "../src/index.js"; +import { unhex } from "./ops.js"; + +const CORPUS = new URL("../../test/conformance/vectors/", import.meta.url); + +interface Message { + protocols: { number: number; line: { major: number; minor: number; patch: number }; shape_hash: string; functions: number[] }[]; +} + +const varint = (n: number): number[] => (n > 0x7f ? [(n & 0x7f) | 0x80, ...varint(n >>> 7)] : [n]); + +/** The case's Hello, as the header and the entries `buildHello` takes, written from its facts. */ +function parts(id: string): { header: Uint8Array; entries: ProtocolEntry[]; bytes: Uint8Array } { + const { cases } = JSON.parse(readFileSync(new URL("handshake-comline2.json", CORPUS), "utf8")) as { + cases: { id: string; bytes: string; input: { message: Message } }[]; + }; + const found = cases.find((c) => c.id === `handshake-comline2/${id}`); + assert.ok(found, id); + const entries = found.input.message.protocols.map(({ number, line, shape_hash, functions }) => ({ + number, + bytes: Uint8Array.from([ + ...varint(number), + ...varint(line.major), + ...varint(line.minor), + ...varint(line.patch), + ...unhex(shape_hash), + ...varint(functions.length), + ...functions.flatMap(varint), + ]), + })); + const bytes = unhex(found.bytes); + // The header is what precedes the protocol list: its count, then the entries. + const list = entries.reduce((n, e) => n + e.bytes.length, varint(entries.length).length); + return { header: bytes.slice(0, bytes.length - list), entries, bytes }; +} + +const hex = (bytes: Uint8Array): string => Buffer.from(bytes).toString("hex"); + +test("every protocol, however it is split between provided and called, is the whole Hello", () => { + const { header, entries, bytes } = parts("hello"); + const [zero, one] = entries as [ProtocolEntry, ProtocolEntry]; + for (const [provided, called] of [ + [[zero, one], []], + [[], [zero, one]], + [[zero], [one]], + [[one], [zero]], + [[one, zero], [one, zero]], + [[zero, zero], [one]], + ] as const) { + assert.equal(hex(buildHello(header, provided, called)), hex(bytes)); + } +}); + +test("a subset is the Hello that lists those protocols", () => { + const { header, entries } = parts("hello"); + const subset = parts("hello-subset"); + assert.deepEqual([...subset.header], [...header]); + const one = entries[1]!; + assert.deepEqual([...subset.entries[0]!.bytes], [...one.bytes]); + for (const [provided, called] of [[[one], []], [[], [one]], [[one], [one]]] as const) { + assert.equal(hex(buildHello(header, provided, called)), hex(subset.bytes)); + } +}); + +test("the first entry given for a number is the one listed", () => { + const { header, entries } = parts("hello"); + const [zero] = entries as [ProtocolEntry]; + const other = { number: zero.number, bytes: Uint8Array.from([0xff]) }; + assert.equal(hex(buildHello(header, [zero], [other])), hex(buildHello(header, [zero], []))); + assert.equal(hex(buildHello(header, [other], [zero])), hex(buildHello(header, [other], []))); +}); + +test("a Hello that lists nothing has a zero count", () => { + const { header } = parts("hello"); + assert.deepEqual([...buildHello(header, [], [])], [...header, 0]); +}); diff --git a/runtime/test/wire-invariance.json b/runtime/test/wire-invariance.json index edd14bd..7d2c239 100644 --- a/runtime/test/wire-invariance.json +++ b/runtime/test/wire-invariance.json @@ -645,5 +645,68 @@ "format": [ "PackedCodec" ] + }, + "subset/": { + "files": { + "subset/admin.ts": { + "irHash": "0x3bc15e97071208ea", + "protocolNumbers": [ + 2, + 2, + 3, + 3 + ], + "callTables": { + "ADMIN_CALLS": [ + "kick" + ], + "ALERTS_CALLS": [ + "raised" + ] + }, + "callsWritten": [ + "0 kick", + "0 raised" + ], + "callsTaken": [ + 0, + 0 + ] + }, + "subset/public.ts": { + "irHash": "0x73062149064e1beb", + "protocolNumbers": [ + 0, + 0, + 1, + 1 + ], + "callTables": { + "CHAT_CALLS": [ + "send" + ], + "EVENTS_CALLS": [ + "shown" + ] + }, + "callsWritten": [ + "0 send", + "0 shown" + ], + "callsTaken": [ + 0, + 0 + ] + } + }, + "connectionIrHash": [ + "0x572df8ce2206ff29" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00010000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c10400000100aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa010001000100bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb010002000100cccccccccccccccccccccccccccccccc010003000100dddddddddddddddddddddddddddddddd0100" + ], + "format": [ + "PackedCodec" + ] } } diff --git a/runtime/test/wire-invariance.test.ts b/runtime/test/wire-invariance.test.ts index c14fd2b..8c0f380 100644 --- a/runtime/test/wire-invariance.test.ts +++ b/runtime/test/wire-invariance.test.ts @@ -16,6 +16,8 @@ import assert from "node:assert/strict"; import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { test } from "node:test"; +import { buildHello } from "../src/index.js"; + const RUNTIME = new URL("../../", import.meta.url); const GENERATED = new URL("test/generated/", RUNTIME); const RECORD = new URL("test/wire-invariance.json", RUNTIME); @@ -39,7 +41,7 @@ interface ShapeFacts { files: Record; /** Every distinct `CONNECTION_IR_HASH` the shape defines: one, the package's. */ connectionIrHash: string[]; - /** Every distinct `HELLO`, as hex. */ + /** Every distinct Hello of the package's whole connection, as hex: its header with every protocol's entry. */ hello: string[]; /** Every distinct codec `Format` is built from. */ format: string[]; @@ -78,8 +80,18 @@ function factsOf(text: string): { file: FileFacts; connectionIrHash: string[]; h const taken = all(text, /^\s+case (\d+): \{$/gm).map((m) => Number(m[1])); if (taken.length) file.callsTaken = taken; - const hello = all(text, /export const HELLO = new Uint8Array\(\[([^\]]*)\]\);/g).map((m) => - [...m[1]!.matchAll(/0x([0-9a-f]{2})/g)].map((b) => b[1]).join(""), + // The Hello is emitted as parts, a header and an entry per protocol, which an + // end puts together from what it provides and calls; with every protocol it + // is the whole connection's Hello, the one the package used to embed. + const bytesOf = (list: string): Uint8Array => + Uint8Array.from([...list.matchAll(/0x([0-9a-f]{2})/g)].map((b) => parseInt(b[1]!, 16))); + const headers = all(text, /export const HELLO_HEADER = new Uint8Array\(\[([^\]]*)\]\);/g).map((m) => bytesOf(m[1]!)); + const entries = all(text, /number: (\d+),\s+bytes: new Uint8Array\(\[([^\]]*)\]\),/g).map((m) => ({ + number: Number(m[1]), + bytes: bytesOf(m[2]!), + })); + const hello = headers.map((header) => + [...buildHello(header, entries, [])].map((b) => b.toString(16).padStart(2, "0")).join(""), ); return { file, diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 1c1eeca..eded0b1 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -8,7 +8,7 @@ publish = false # Same revs `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-typescript = { path = "../codegen" } eyre = "0.6.8"