diff --git a/runtime/conformance/reports/rust.json b/runtime/conformance/reports/rust.json index 9c41c53..e47c56d 100644 --- a/runtime/conformance/reports/rust.json +++ b/runtime/conformance/reports/rust.json @@ -487,6 +487,7 @@ "proven_by": [ "handshake-comline2/hello", "handshake-comline2/hello-symmetric-wide", + "handshake-comline2/hello-subset", "handshake-comline2/hello-empty", "handshake-comline2/answer-accept", "handshake-comline2/answer-refuse", @@ -525,6 +526,8 @@ "handshake-comline2/offer-same-version-differs-warn", "handshake-comline2/offer-unknown-protocol", "handshake-comline2/offer-only-unknown-protocols", + "handshake-comline2/offer-subset-offered", + "handshake-comline2/offer-subset-local", "handshake-comline2/offer-package-mismatch", "handshake-comline2/offer-encoding-mismatch", "handshake-comline2/offer-exchange-mismatch", @@ -538,6 +541,8 @@ "handshake-comline2/conclude-same-version-differs-warn", "handshake-comline2/conclude-protocol-refused", "handshake-comline2/conclude-refused", + "handshake-comline2/conclude-subset", + "handshake-comline2/conclude-answer-beyond-offer", "handshake-comline2/conclude-malformed", "handshake-comline2/conclude-exchange-mismatch", "handshake-comline2/symmetric-accept", @@ -545,11 +550,13 @@ "handshake-comline2/symmetric-responder-newer-consumer-refuse", "handshake-comline2/symmetric-line-mismatch", "handshake-comline2/symmetric-unknown-protocol", + "handshake-comline2/symmetric-subset-local", "handshake-comline2/symmetric-same-version-differs-warn", "handshake-comline2/symmetric-exchange-mismatch", "handshake-comline2/symmetric-peer-refused", "handshake-comline2/finish-accept", "handshake-comline2/finish-accept-refusing", + "handshake-comline2/finish-refused-unlisted", "handshake-comline2/finish-refused" ] }, diff --git a/runtime/conformance/spec/README.md b/runtime/conformance/spec/README.md index 542b501..9e30e07 100644 --- a/runtime/conformance/spec/README.md +++ b/runtime/conformance/spec/README.md @@ -6,7 +6,7 @@ proven, the formats of these files, and the catalog of names they share. A runti tool implements against this repository, and pins it like any other dependency. Comline's own runtimes do the same. -Version: **0.11** ([`VERSION`](VERSION)). While Comline is in its early days +Version: **0.12** ([`VERSION`](VERSION)). While Comline is in its early days (0.x), a minor version may change anything, and the change is named in the pull request that makes it and in [the changes](#changes) below. @@ -229,6 +229,38 @@ What an implementation answers, and how its answers are judged: ### Changes +- **0.12:** `comline@2` cases for a Hello that lists a subset of the package's + protocols (named connections, specification#13): an end provides some of the + package's protocols and calls some of the other side's, and its Hello lists + exactly those. No existing case changes. New cases, all in + `handshake-comline2`: + - `hello-subset`: the `hello` case's bytes with protocol 0's entry gone and + the count one. `hello` is the default, a Hello that lists every protocol on + the package's connection: its bytes are what they were. + - `offer-subset-offered`: the offer lists protocol 0 alone, and the responder, + which also has protocol 1, answers only what was offered. Under + `scope = protocol` its result has protocol 1 refused on its own + (`unknown_protocol`): calls to it fail locally. + - `offer-subset-local`: the responder lists protocol 1 alone and the offer + both, so protocol 0 is refused (`unknown_protocol`) in the answer and the + responder's result has no protocol 0. + - `conclude-subset`: the initiator offered protocol 0 alone and the answer + takes it. `conclude-answer-beyond-offer`: an answer that also names + protocol 1, which the offer didn't list, is `malformed`. + - `symmetric-subset-local`: an end listing protocol 0 alone, against a peer + that lists both: its verdict refuses protocol 1, and its result has no + protocol 1. + - `finish-refused-unlisted`: the peer's verdict refuses protocol 1, which this + end never listed, and what this end agreed doesn't change. + + A protocol a result doesn't hold, and one it holds as refused, are the ones + whose calls fail locally (`Unavailable`) and that `provide` refuses on a + connection that ran a Hello. That behaviour is the runtime's, not a message or + a negotiation step, so no case states it: the ops have nothing to ask a + runtime about a call or about providing (runtime#124 holds it in the + runtime's own tests, and + [specification#13](https://github.com/ComlineProject/specification/issues/13) + the question of whether the corpus should). - **0.11:** a framing states `protocol`: `named`, when a request's frame names the protocol it calls into, by number or wire id, so several protocols can share one transport, or `unnamed`, when it doesn't and a call names only its function. A diff --git a/runtime/conformance/spec/REV b/runtime/conformance/spec/REV index 6857159..75adb03 100644 --- a/runtime/conformance/spec/REV +++ b/runtime/conformance/spec/REV @@ -1 +1 @@ -69882e92971e243b6b74a539a13b534d95b3abf7 +3254e0ea0edc8537df453db5ee647cd63715ffe2 diff --git a/runtime/conformance/spec/VERSION b/runtime/conformance/spec/VERSION index 51176c7..c43e105 100644 --- a/runtime/conformance/spec/VERSION +++ b/runtime/conformance/spec/VERSION @@ -1 +1 @@ -0.11 +0.12 diff --git a/runtime/conformance/spec/catalog/encodings.cue b/runtime/conformance/spec/catalog/encodings.cue index b7d5fe8..5b11f33 100644 --- a/runtime/conformance/spec/catalog/encodings.cue +++ b/runtime/conformance/spec/catalog/encodings.cue @@ -266,7 +266,7 @@ encodings: { } "datagram@1": { kind: "framing" - title: "datagram" + title: "datagram@1" description: "Comline's own binary framing of requests and responses." aliases: ["datagram", "comline.datagram"] frozen_as: "datagram" diff --git a/runtime/conformance/spec/catalog/gen/catalog.json b/runtime/conformance/spec/catalog/gen/catalog.json index 5aeb4dc..69d7218 100644 --- a/runtime/conformance/spec/catalog/gen/catalog.json +++ b/runtime/conformance/spec/catalog/gen/catalog.json @@ -871,7 +871,7 @@ "datagram@1": { "kind": "framing", "status": "stable", - "title": "datagram", + "title": "datagram@1", "description": "Comline's own binary framing of requests and responses.", "aliases": [ "datagram", diff --git a/runtime/conformance/spec/compiler/cases/bounded.json b/runtime/conformance/spec/compiler/cases/bounded.json index 41da32b..86a8f45 100644 --- a/runtime/conformance/spec/compiler/cases/bounded.json +++ b/runtime/conformance/spec/compiler/cases/bounded.json @@ -264,7 +264,7 @@ }, { "path": "src/api.ids", - "text": "use models::Blob\n\nprotocol Orders {\n function send(b: Blob);\n}\n" + "text": "use package::models::Blob\n\nprotocol Orders {\n function send(b: Blob);\n}\n" } ], "dependencies": [] @@ -295,7 +295,7 @@ }, { "path": "src/api.ids", - "text": "use models::Blob\n\n@unverified = \"orders carry the upload\"\nprotocol Orders {\n function send(b: Blob);\n}\n" + "text": "use package::models::Blob\n\n@unverified = \"orders carry the upload\"\nprotocol Orders {\n function send(b: Blob);\n}\n" } ], "dependencies": [] @@ -354,7 +354,7 @@ }, { "path": "src/api.ids", - "text": "use models::Blob\n\nprotocol Orders {\n function send(b: Blob);\n}\n" + "text": "use package::models::Blob\n\nprotocol Orders {\n function send(b: Blob);\n}\n" } ], "dependencies": [] @@ -371,6 +371,110 @@ "builds": true, "diagnostics": [] } + }, + { + "id": "bounded/unreached-unmarked", + "description": "a struct no protocol reaches, with a string without a maximum, is an error: it is a type another package can use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-list-unmarked", + "description": "a struct no protocol reaches, with a list without a maximum, is an error too", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: u8[]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-allowed-still-unmarked", + "description": "allowing @unverified in the package doesn't cover a type no protocol reaches: nothing marked it", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-bounded", + "description": "a struct no protocol reaches, bounded, gives nothing up and builds", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: char[max 64]\n tags: u8[max 16]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } } ] } diff --git a/runtime/conformance/spec/compiler/cases/imports.json b/runtime/conformance/spec/compiler/cases/imports.json new file mode 100644 index 0000000..11e918f --- /dev/null +++ b/runtime/conformance/spec/compiler/cases/imports.json @@ -0,0 +1,646 @@ +{ + "$schema": "../../specs/gen/compiler.schema.json", + "group": "imports", + "cases": [ + { + "id": "imports/bare-own-item", + "description": "a bare path to an item of the package's own schema is an error", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::bare-own-schema-path", + "severity": "error" + } + ] + } + }, + { + "id": "imports/bare-own-namespace", + "description": "a bare path to the package's own schema as a whole is an error, and so is the bare Blob after it, as a whole-namespace use brings in only its name: every error is reported", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use models\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::bare-own-schema-path", + "severity": "error" + }, + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "imports/bare-own-multi", + "description": "a bare path with {...} to the package's own schema is an error", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use models::{Blob, Tag}\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::bare-own-schema-path", + "severity": "error" + } + ] + } + }, + { + "id": "imports/bare-own-glob", + "description": "a bare path with * to the package's own schema is an error", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use models::*\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::bare-own-schema-path", + "severity": "error" + } + ] + } + }, + { + "id": "imports/bare-own-nested", + "description": "a bare path to a schema in a directory of the package is an error, whatever the importing schema's own place", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "use shapes::models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::bare-own-schema-path", + "severity": "error" + } + ] + } + }, + { + "id": "imports/package-item", + "description": "package:: reaches an item of the package's own schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/package-namespace", + "description": "package:: reaches the package's own schema as a whole", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models\n\nstruct Upload {\n blob: models::Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/package-multi", + "description": "package:: with {...} reaches several items of the package's own schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models::{Blob, Tag}\n\nstruct Upload {\n blob: Blob\n tag: Tag\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/package-glob", + "description": "package:: with * reaches every item of the package's own schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models::*\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/package-nested", + "description": "package:: reaches a schema in a directory of the package from one beside it", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "use package::shapes::models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/parent-item", + "description": "parent:: reaches a schema one level up from the importing schema's namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "use parent::models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/self-item", + "description": "self:: reaches a schema under the importing schema's own namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use self::models::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + }, + { + "path": "src/api/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/dependency-path", + "description": "a bare path whose first segment is a dependency reaches the dependency's schema", + "packages": [ + { + "name": "models", + "config": "congregation models\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n models = {\n path = \"../models\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use models::api::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [ + { + "name": "models" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/std-path", + "description": "a bare path whose first segment is std reaches the standard library's schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use std::http::Request\n\nstruct Call {\n request: Request\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "imports/unknown-first-segment", + "description": "a bare path that is neither a dependency, std nor one of the package's schemas is unresolved, not this error; the use still brings Blob into scope, so the bare Blob after it is no second error, as in Rust", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use modles::Blob\n\nstruct Upload {\n blob: Blob\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "import::unresolved", + "severity": "error" + } + ] + } + }, + { + "id": "imports/own-schema-named-like-dependency", + "description": "a package's own schema named like one of its dependencies is refused, so a first segment is never both", + "packages": [ + { + "name": "models", + "config": "congregation models\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n models = {\n path = \"../models\"\n }\n}\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [ + { + "name": "models" + } + ] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [], + "error_contains": [ + "schema 'models.ids' is named like the dependency 'models'" + ] + } + }, + { + "id": "imports/dependency-named-std", + "description": "std can't be a dependency's name", + "packages": [ + { + "name": "std", + "config": "congregation std\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n std = {\n path = \"../std\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Upload {\n size: u32\n}\n" + } + ], + "dependencies": [ + { + "name": "std" + } + ] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [], + "error_contains": [ + "reserved" + ] + } + }, + { + "id": "imports/dependency-named-package", + "description": "package can't be a dependency's name", + "packages": [ + { + "name": "package", + "config": "congregation package\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n package = {\n path = \"../package\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Upload {\n size: u32\n}\n" + } + ], + "dependencies": [ + { + "name": "package" + } + ] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [], + "error_contains": [ + "reserved" + ] + } + }, + { + "id": "imports/dependency-named-parent", + "description": "parent can't be a dependency's name", + "packages": [ + { + "name": "parent", + "config": "congregation parent\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n parent = {\n path = \"../parent\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Upload {\n size: u32\n}\n" + } + ], + "dependencies": [ + { + "name": "parent" + } + ] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [], + "error_contains": [ + "reserved" + ] + } + }, + { + "id": "imports/dependency-named-self", + "description": "self can't be a dependency's name", + "packages": [ + { + "name": "self", + "config": "congregation self\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Blob {\n size: u32\n}\n\nstruct Tag {\n id: u32\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n self = {\n path = \"../self\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Upload {\n size: u32\n}\n" + } + ], + "dependencies": [ + { + "name": "self" + } + ] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [], + "error_contains": [ + "reserved" + ] + } + } + ] +} diff --git a/runtime/conformance/spec/compiler/cases/references.json b/runtime/conformance/spec/compiler/cases/references.json new file mode 100644 index 0000000..8e7a4f4 --- /dev/null +++ b/runtime/conformance/spec/compiler/cases/references.json @@ -0,0 +1,1269 @@ +{ + "$schema": "../../specs/gen/compiler.schema.json", + "group": "references", + "cases": [ + { + "id": "references/namespace-qualified", + "description": "after use package::types, types::User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/namespace-bare-refused", + "description": "after use package::types a bare User is not in scope: the use brings in only types (fix, offered because User is declared in types: add use package::types::User, or write types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/namespace-alias-qualified", + "description": "after use package::types as t, t::User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types as t\n\nstruct Account {\n owner: t::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/namespace-alias-original-refused", + "description": "after use package::types as t only the alias t is in scope, not types, which the alias replaces (fix: write t::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types as t\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/item-bare", + "description": "after use package::types::User, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::User\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/item-qualified-refused", + "description": "after use package::types::User, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::User\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/braces-bare", + "description": "after use package::types::{User, Order}, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::{User, Order}\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/braces-qualified-refused", + "description": "after use package::types::{User, Order}, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::{User, Order}\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/glob-bare", + "description": "after use package::types::*, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::*\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/glob-qualified-refused", + "description": "after use package::types::*, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::*\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/no-use-bare-refused", + "description": "a bare User with no use is not in scope (fix, offered because User is declared in package::types: add use package::types::User, or write package::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/no-use-qualified-refused", + "description": "types::User with no use is not rooted in a name in scope (fix, offered because the package declares types::User: add use package::types, or write package::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/nowhere-bare-refused", + "description": "a bare Nowhere that no schema of the package or its dependencies declares is not in scope (no fix that adds a use is offered: nothing declares it)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: Nowhere\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/nowhere-qualified-refused", + "description": "nope::types::User, whose first segment matches no name in scope, root or schema, is not in scope (no fix that adds a use is offered: nothing is named nope)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: nope::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/defined-twice-local-and-use", + "description": "use package::billing::Invoice and struct Invoice in the same schema define Invoice twice (fix: rename one, or import with an alias: use package::billing::Invoice as BillingInvoice)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice\n\nstruct Invoice {\n data: char[max 64]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::defined-twice", + "severity": "error" + } + ] + } + }, + { + "id": "references/defined-twice-two-uses", + "description": "use package::a::User and use package::b::User bring in User twice (fix: rename one, or import with an alias: use package::b::User as BUser)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/a.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/b.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::a::User\nuse package::b::User\n\nstruct Account {\n id: u32\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::defined-twice", + "severity": "error" + } + ] + } + }, + { + "id": "references/alias-resolves-local-clash", + "description": "use package::billing::api::Invoice as BillingInvoice beside a local Invoice defines each name once", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice as BillingInvoice\n\nstruct Invoice {\n data: char[max 64]\n}\n\nstruct Account {\n billed: BillingInvoice\n own: Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/alias-resolves-two-uses", + "description": "use package::a::User beside use package::b::User as BUser defines each name once", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/a.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/b.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::a::User\nuse package::b::User as BUser\n\nstruct Account {\n first: User\n second: BUser\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-package", + "description": "package::types::User in a field needs no use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: package::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-package-nested", + "description": "package:: reaches a schema in a directory from one beside it, in a field", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "struct Account {\n owner: package::shapes::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-parent", + "description": "parent::common::Error in a field reaches a schema one level up from the importing schema's namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/common.ids", + "text": "struct Error {\n code: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "struct Account {\n owner: parent::common::Error\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-self", + "description": "self::nested::Type in a field reaches a schema under the importing schema's own namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: self::nested::Type\n}\n" + }, + { + "path": "src/api/nested.ids", + "text": "struct Type {\n id: u32\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-std", + "description": "std::http::Request in a field needs no use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: std::http::Request\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-dependency", + "description": "a dependency's greeting::hello::Greeting in a field needs no use", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: greeting::hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-own-schema-unrooted-refused", + "description": "a full path to the package's own schema that doesn't start at package, parent or self is not rooted (fix, offered because the schema exists: write package::shapes::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: shapes::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/descend-namespace", + "description": "after use package::billing, billing::api::Invoice reaches the nested schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nstruct Account {\n owner: billing::api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-alias", + "description": "after use package::billing as b, b::api::Invoice reaches the nested schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing as b\n\nstruct Account {\n owner: b::api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-dependency", + "description": "after use greeting::hello, hello::Greeting reaches the dependency's item", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use greeting::hello\n\nstruct Account {\n owner: hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-dependency-name", + "description": "after use greeting, a dependency's name on its own, greeting::hello::Greeting reaches the dependency's item", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use greeting\n\nstruct Account {\n owner: greeting::hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-skips-a-segment-refused", + "description": "after use package::billing, api is not in scope (fix, offered because billing::api exists: write billing::api::Invoice, or add use package::billing::api)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nstruct Account {\n owner: api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/resolved-item", + "description": "use package::billing::api::Invoice, then Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice\n\nprotocol Orders {\n function send(i: Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + }, + { + "id": "references/resolved-namespace", + "description": "use package::billing::api, then api::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api\n\nprotocol Orders {\n function send(i: api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + }, + { + "id": "references/resolved-descent", + "description": "use package::billing, then billing::api::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nprotocol Orders {\n function send(i: billing::api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + }, + { + "id": "references/resolved-alias", + "description": "use package::billing::api as b, then b::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api as b\n\nprotocol Orders {\n function send(i: b::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + }, + { + "id": "references/resolved-full-path", + "description": "package::billing::api::Invoice with no use reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "protocol Orders {\n function send(i: package::billing::api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + }, + { + "id": "references/resolved-decoy", + "description": "use package::archive, then archive::Invoice, reaches the unbounded Invoice, which an unmarked protocol can't use: the other cases reached billing's", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::archive\n\nprotocol Orders {\n function send(i: archive::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "references/existing-package-unchanged", + "description": "use package::models and models::Blob, as written before the rule, freezes the same protocols as the item use does in bounded/other-schema-marked", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n\n@unverified = \"the uploader streams whatever it's given\"\nprotocol Upload {\n function put(b: Blob);\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models\n\n@unverified = \"orders carry the upload\"\nprotocol Orders {\n function send(b: models::Blob);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Upload", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the uploader streams whatever it's given" + } + ] + }, + { + "name": "Orders", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "orders carry the upload" + } + ] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + } + ] +} diff --git a/runtime/conformance/spec/compiler/readme.md b/runtime/conformance/spec/compiler/readme.md index 0045c42..2dc6b06 100644 --- a/runtime/conformance/spec/compiler/readme.md +++ b/runtime/conformance/spec/compiler/readme.md @@ -133,16 +133,47 @@ cases with `dependencies`, which are in `acceptance` and `chain`. | `marker` | the gate (`annotations.unverified.allowed`); a marker required where a protocol gives something up (its own `@handshake`, the package's default); its reason; a marker where nothing is given up | | `keyed` | `@unverified = { = "" }`: the exact set, an unknown id, a missing one, one listed that isn't given up, one listed twice | | `package` | `unverified` in `config.idp`: the keyed and plain forms covering what a protocol takes from the package's settings; a protocol with its own `@handshake` not covered; `unverified::wrong-scope` for `bounded_size`; a guarantee no protocol gives up through it; the gate; a marker adding `bounded_size` | -| `bounded` | `bounded_size`: a string or list without a maximum, a type that contains itself without `@max_depth`, a type from another schema of the package that holds one, each unmarked (an error) and marked (given up), and the bounded variants | +| `bounded` | `bounded_size`: a string or list without a maximum, a type that contains itself without `@max_depth`, a type from another schema of the package that holds one, each unmarked (an error) and marked (given up), a type no protocol reaches (it has to be bounded: an error where it holds a string or list without a maximum, even where the package allows `@unverified`), and the bounded variants | | `acceptance` | a dependency's unverified protocols accepted under it in `config.idp`: not at all, exactly, for less, for more; the reasons the consumer is shown; the dependency judged by its own package | +| `imports` | where a `use` path starts: a package's own schemas only through `package::`, `parent::` or `self::` (a bare path to one is `import::bare-own-schema-path`, in each form of a `use`), a dependency's and `std`'s paths as they were, a path matching nothing (`import::unresolved`), a schema named like a dependency, and the names a dependency can't have | +| `references` | how a type is named once imported, the Rust model: a whole-namespace `use` brings in only its name (`types::User`, and a bare `User` is `reference::not-in-scope`); a `use` of an item, `{...}` or `*` brings in the names it lists (and `types::User` after it is `reference::qualifier-not-in-scope`); a full path (`package::`, `parent::`, `self::`, `std::`, a dependency's) in a type position with no `use`; a path going down from a name in scope, a dependency's name included; a name defined twice (`reference::defined-twice`) and an alias resolving it; each spelling reaching the same type, and a package written before the rule unchanged | | `chain` | three packages, `c` depending on `b` depending on `a`: a type holding `a`'s unbounded value, used in `c`; and the acceptance resolving `b` asks for `a`'s protocols too | -A case's `description` says what it shows. Each rule has a passing and a -failing variant. +A case's `description` says what it shows, and for a refused reference the +fix its diagnostic carries (a case holds a compiler to the code and severity, +not to the fix). The `reference` codes, in +[the proposal](https://github.com/ComlineProject/docs/blob/main/docs/docs/proposals/use-paths-and-groups/relative-use.md#qualified-references): + +| Code | When | Fix | +| --- | --- | --- | +| `reference::not-in-scope` | a bare name no `use` or declaration of the file brought in: `User` after only `use package::types` | add `use package::types::User`, or write `types::User` | +| `reference::qualifier-not-in-scope` | a qualified reference whose first segment is not a name in scope or a root: `types::User` after `use package::types::User` | write `User` (or add the `use` that brings the qualifier in) | +| `reference::defined-twice` | a name defined twice in a file: a `use`d item and a local declaration of the same name, or two `use`s bringing in the same name | rename one, or import with an alias (`use package::b::User as BUser`) | + +Both `not-in-scope` codes also cover a name or a qualifier nothing declares +(`Nowhere`, `nope::types::User`); a fix that adds a `use` is offered only +where something declares it. Every error is reported, not only the first, so +a case that has two causes lists both codes. A config error (the +reserved dependency names) stops the build before the schemas are checked, as +in Rust, so no schema error is reported with it. A `use` that fails to resolve +(`import::unresolved`) still brings its name into scope, so it never cascades +into a `reference::not-in-scope` for the name. In a type position `parent::` +and `self::` mean what they mean in a `use`. + +Each rule has a passing and a failing variant. + +The `references` group is ahead of core: its outcomes are those of the +[decision](https://github.com/ComlineProject/docs/blob/main/docs/docs/proposals/use-paths-and-groups/relative-use.md#qualified-references), +which [core#290](https://github.com/ComlineProject/core/issues/290) +implements, and core's runner fails them until then. ### To come Cases for rules core doesn't implement yet, which go in when it does: +a `group` on a dependency's entry and the same package regrouped, and a kind of case for +formatting imports ( +[specification#11](https://github.com/ComlineProject/specification/issues/11), +after core#284), acknowledgements at the inner scopes (function, argument, field and type), an outer scope covering an inner one, `strict`, pinning an acceptance to a chain of packages and its invalidation, and failing closed. diff --git a/runtime/conformance/spec/compiler/src/bounded.cue b/runtime/conformance/spec/compiler/src/bounded.cue index 0449776..3323943 100644 --- a/runtime/conformance/spec/compiler/src/bounded.cue +++ b/runtime/conformance/spec/compiler/src/bounded.cue @@ -153,7 +153,7 @@ groups: bounded: { schemas: { models: _models api: """ - use models::Blob + use package::models::Blob protocol Orders { function send(b: Blob); @@ -171,7 +171,7 @@ groups: bounded: { schemas: { models: _models api: """ - use models::Blob + use package::models::Blob @unverified = "orders carry the upload" protocol Orders { @@ -205,7 +205,7 @@ groups: bounded: { } """ api: """ - use models::Blob + use package::models::Blob protocol Orders { function send(b: Blob); @@ -219,4 +219,52 @@ groups: bounded: { warnings: [] } } + + // A position no protocol reaches is a type another package can use, and + // has to be bounded. Only a marked protocol that reaches the type gives + // it up (`other-schema-marked`), and a type nothing reaches has none. + "unreached-unmarked": { + about: "a struct no protocol reaches, with a string without a maximum, is an error: it is a type another package can use" + packages: app: schemas: models: """ + struct Blob { + data: string + } + """ + build: "app" + expect: {builds: false, errors: ["bounds::unbounded"]} + } + "unreached-list-unmarked": { + about: "a struct no protocol reaches, with a list without a maximum, is an error too" + packages: app: schemas: models: """ + struct Blob { + data: u8[] + } + """ + build: "app" + expect: {builds: false, errors: ["bounds::unbounded"]} + } + "unreached-allowed-still-unmarked": { + about: "allowing @unverified in the package doesn't cover a type no protocol reaches: nothing marked it" + packages: app: { + config: [_allow] + schemas: models: """ + struct Blob { + data: string + } + """ + } + build: "app" + expect: {builds: false, errors: ["bounds::unbounded"]} + } + "unreached-bounded": { + about: "a struct no protocol reaches, bounded, gives nothing up and builds" + packages: app: schemas: models: """ + struct Blob { + data: char[max 64] + tags: u8[max 16] + } + """ + build: "app" + expect: {builds: true, protocols: {}} + } } diff --git a/runtime/conformance/spec/compiler/src/imports.cue b/runtime/conformance/spec/compiler/src/imports.cue new file mode 100644 index 0000000..d59e60e --- /dev/null +++ b/runtime/conformance/spec/compiler/src/imports.cue @@ -0,0 +1,224 @@ +package cases + +// Where a `use` path starts. Within a package, its own schemas are reached +// only through a relative path: `package::` (from the package's root), +// `parent::` (one level up) or `self::` (the current namespace). An absolute +// first segment always means `std` or a dependency, so a bare path to one of +// the package's own schemas is an error, with a fix that writes `package::` +// in front of it (`import::bare-own-schema-path`). A path that matches +// nothing is `import::unresolved`, as it was. Rule and rollout: +// https://comlineproject.github.io/docs/proposals/use-paths-and-groups/relative-use/ +// +// A package's own schema named like a dependency or `std` is refused outright +// (the shadowing guard), and `std`, `package`, `parent` and `self` can't be a +// dependency's name. Neither error has a code: the cases say what the message +// contains, as the acceptance cases do. +// +// Every error is reported, not only the first, among those of the schemas: a +// schema's bare name that nothing brought into scope is +// `reference::not-in-scope` besides any other error of the schema (see the +// `references` group). A config error, as the reserved dependency names, +// stops the build before the schemas are checked, as in Rust, so those cases +// hold no reference of their own. + +_impModels: """ + struct Blob { + size: u32 + } + + struct Tag { + id: u32 + } + """ + +// A schema that holds no reference, for the cases a config error stops. +_impPlain: """ + struct Upload { + size: u32 + } + """ + +// A schema using `Blob`, whichever way `use` brought it in. +_impUsesBlob: """ + struct Upload { + blob: Blob + } + """ + +groups: imports: { + // A bare path to the package's own schema, in each form of a `use`. + "bare-own-item": { + about: "a bare path to an item of the package's own schema is an error" + packages: app: schemas: {models: _impModels, api: "use models::Blob\n\n" + _impUsesBlob} + build: "app" + expect: {builds: false, errors: ["import::bare-own-schema-path"]} + } + "bare-own-namespace": { + about: "a bare path to the package's own schema as a whole is an error, and so is the bare Blob after it, as a whole-namespace use brings in only its name: every error is reported" + packages: app: schemas: {models: _impModels, api: "use models\n\n" + _impUsesBlob} + build: "app" + expect: {builds: false, errors: ["import::bare-own-schema-path", "reference::not-in-scope"]} + } + "bare-own-multi": { + about: "a bare path with {...} to the package's own schema is an error" + packages: app: schemas: {models: _impModels, api: "use models::{Blob, Tag}\n\n" + _impUsesBlob} + build: "app" + expect: {builds: false, errors: ["import::bare-own-schema-path"]} + } + "bare-own-glob": { + about: "a bare path with * to the package's own schema is an error" + packages: app: schemas: {models: _impModels, api: "use models::*\n\n" + _impUsesBlob} + build: "app" + expect: {builds: false, errors: ["import::bare-own-schema-path"]} + } + "bare-own-nested": { + about: "a bare path to a schema in a directory of the package is an error, whatever the importing schema's own place" + packages: app: schemas: { + "shapes/models": _impModels + "shapes/api": "use shapes::models::Blob\n\n" + _impUsesBlob + } + build: "app" + expect: {builds: false, errors: ["import::bare-own-schema-path"]} + } + + // The same schemas through the relative forms, which build. + "package-item": { + about: "package:: reaches an item of the package's own schema" + packages: app: schemas: {models: _impModels, api: "use package::models::Blob\n\n" + _impUsesBlob} + build: "app" + expect: {builds: true, protocols: {}} + } + "package-namespace": { + about: "package:: reaches the package's own schema as a whole" + packages: app: schemas: {models: _impModels, api: "use package::models\n\nstruct Upload {\n blob: models::Blob\n}"} + build: "app" + expect: {builds: true, protocols: {}} + } + "package-multi": { + about: "package:: with {...} reaches several items of the package's own schema" + packages: app: schemas: {models: _impModels, api: "use package::models::{Blob, Tag}\n\nstruct Upload {\n blob: Blob\n tag: Tag\n}"} + build: "app" + expect: {builds: true, protocols: {}} + } + "package-glob": { + about: "package:: with * reaches every item of the package's own schema" + packages: app: schemas: {models: _impModels, api: "use package::models::*\n\n" + _impUsesBlob} + build: "app" + expect: {builds: true, protocols: {}} + } + "package-nested": { + about: "package:: reaches a schema in a directory of the package from one beside it" + packages: app: schemas: { + "shapes/models": _impModels + "shapes/api": "use package::shapes::models::Blob\n\n" + _impUsesBlob + } + build: "app" + expect: {builds: true, protocols: {}} + } + "parent-item": { + about: "parent:: reaches a schema one level up from the importing schema's namespace" + packages: app: schemas: { + "shapes/models": _impModels + "shapes/api": "use parent::models::Blob\n\n" + _impUsesBlob + } + build: "app" + expect: {builds: true, protocols: {}} + } + "self-item": { + about: "self:: reaches a schema under the importing schema's own namespace" + packages: app: schemas: { + "api": "use self::models::Blob\n\n" + _impUsesBlob + "api/models": _impModels + } + build: "app" + expect: {builds: true, protocols: {}} + } + + // A first segment that is not the package's: a dependency, and `std`. + "dependency-path": { + about: "a bare path whose first segment is a dependency reaches the dependency's schema" + packages: { + models: schemas: api: _impModels + app: { + schemas: api: "use models::api::Blob\n\n" + _impUsesBlob + dependencies: models: {} + } + } + build: "app" + expect: {builds: true, protocols: {}} + } + "std-path": { + about: "a bare path whose first segment is std reaches the standard library's schema" + packages: app: schemas: api: "use std::http::Request\n\nstruct Call {\n request: Request\n}" + build: "app" + expect: {builds: true, protocols: {}} + } + "unknown-first-segment": { + about: "a bare path that is neither a dependency, std nor one of the package's schemas is unresolved, not this error; the use still brings Blob into scope, so the bare Blob after it is no second error, as in Rust" + packages: app: schemas: {models: _impModels, api: "use modles::Blob\n\n" + _impUsesBlob} + build: "app" + expect: {builds: false, errors: ["import::unresolved"]} + } + + // What keeps a first segment from meaning two things. + "own-schema-named-like-dependency": { + about: "a package's own schema named like one of its dependencies is refused, so a first segment is never both" + packages: { + models: schemas: api: _impModels + app: { + schemas: models: _impModels + dependencies: models: {} + } + } + build: "app" + expect: {builds: false, error_contains: ["schema 'models.ids' is named like the dependency 'models'"]} + } + "dependency-named-std": { + about: "std can't be a dependency's name" + packages: { + std: schemas: api: _impModels + app: { + schemas: api: _impPlain + dependencies: std: {} + } + } + build: "app" + expect: {builds: false, error_contains: ["reserved"]} + } + "dependency-named-package": { + about: "package can't be a dependency's name" + packages: { + package: schemas: api: _impModels + app: { + schemas: api: _impPlain + dependencies: package: {} + } + } + build: "app" + expect: {builds: false, error_contains: ["reserved"]} + } + "dependency-named-parent": { + about: "parent can't be a dependency's name" + packages: { + parent: schemas: api: _impModels + app: { + schemas: api: _impPlain + dependencies: parent: {} + } + } + build: "app" + expect: {builds: false, error_contains: ["reserved"]} + } + "dependency-named-self": { + about: "self can't be a dependency's name" + packages: { + self: schemas: api: _impModels + app: { + schemas: api: _impPlain + dependencies: self: {} + } + } + build: "app" + expect: {builds: false, error_contains: ["reserved"]} + } +} diff --git a/runtime/conformance/spec/compiler/src/references.cue b/runtime/conformance/spec/compiler/src/references.cue new file mode 100644 index 0000000..94c1cc2 --- /dev/null +++ b/runtime/conformance/spec/compiler/src/references.cue @@ -0,0 +1,537 @@ +package cases + +// How a type is named once it is imported. A qualified reference starts with +// a name a `use` brought into scope, as in Rust, or with a root (`package`, +// `parent`, `self`, `std`, a dependency). Rule and decision: +// https://comlineproject.github.io/docs/proposals/use-paths-and-groups/relative-use/#qualified-references +// +// - A whole-namespace `use` brings in only its name: after +// `use package::types`, `types::User` is the way to write it, and a bare +// `User` is `reference::not-in-scope`. Fix: add `use package::types::User`, +// or write `types::User`. +// - A `use` of an item, `{ ... }` or `*` brings in the names it lists: after +// `use package::types::User`, a bare `User` and not `types::User`, which is +// `reference::qualifier-not-in-scope`. Fix: write `User`. +// - A full path works in a type position with no `use`: `package::`, +// `parent::`, `self::`, `std::` and a dependency's name are roots. +// - A path goes down from a name in scope: `billing::api::Invoice` after +// `use package::billing`. +// - A qualified reference is frozen as its resolved path, so each way of +// writing one reaches the same type. The cases can't read the frozen IR, +// so they show it by what each spelling reaches: a decoy `Invoice` in +// another schema holds an unbounded string, and the one reached holds a +// bounded one, which the protocol using it gives up nothing for. +// +// - A name defined twice, by a `use` and a declaration of the file or by two +// `use`s, is `reference::defined-twice`, as in Rust. Fix: rename one, or +// import with an alias. +// - `parent::` and `self::` mean in a type position what they mean in a `use`. +// +// Every error is reported, not only the first. A name or a qualifier that +// nothing declares is `reference::not-in-scope` or +// `reference::qualifier-not-in-scope` as well; only the fix differs, as a fix +// that adds a `use` is offered only where a declaration exists somewhere. +// +// A refused reference is an error at once, with the likely rewrite as its +// fix. The fix isn't part of what a case holds a compiler to (a diagnostic is +// matched on its code and severity); it is in each case's description. + +_refTypes: """ + struct User { + id: u32 + } + + struct Order { + id: u32 + } + """ + +// A schema holding `User` as a field, whichever way the type is written. +_refHolder: { + _ref: string + text: "struct Account {\n owner: \(_ref)\n}" +} + +// A protocol using an `Invoice`, which is bounded only when it is the one in +// `billing/api`. +_refOrders: { + _ref: string + text: "protocol Orders {\n function send(i: \(_ref));\n}" +} + +_refBilling: """ + struct Invoice { + data: char[max 64] + } + """ + +// The decoy: another `Invoice`, in a schema that sorts before `billing`. Its +// string has no maximum, so the schema builds on its own only because its own +// marked protocol reaches the type and gives bounded size up (a position no +// protocol reaches has to be bounded); the protocol is in the expected +// outcome of every case. A spelling that wrongly reaches it from an unmarked +// protocol is `bounds::unbounded`. +_refDumps: "the archive keeps what it is given" +_refArchive: """ + struct Invoice { + data: string + } + + @unverified = "\(_refDumps)" + protocol Dump { + function put(i: Invoice); + } + """ + +// What the decoy's package expects of `Dump`, beside `Orders`. +_refDump: { + given_up: ["bounded_size"] + acknowledged: bounded_size: {scope: "protocol", reason: _refDumps} +} + +_refGreeting: """ + struct Greeting { + text: char[max 64] + } + """ + +groups: references: { + // A whole-namespace `use` brings in only its name. + "namespace-qualified": { + about: "after use package::types, types::User reaches the item" + packages: app: schemas: { + types: _refTypes + api: "use package::types\n\n" + (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "namespace-bare-refused": { + about: "after use package::types a bare User is not in scope: the use brings in only types (fix, offered because User is declared in types: add use package::types::User, or write types::User)" + packages: app: schemas: { + types: _refTypes + api: "use package::types\n\n" + (_refHolder & {_ref: "User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::not-in-scope"]} + } + "namespace-alias-qualified": { + about: "after use package::types as t, t::User reaches the item" + packages: app: schemas: { + types: _refTypes + api: "use package::types as t\n\n" + (_refHolder & {_ref: "t::User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "namespace-alias-original-refused": { + about: "after use package::types as t only the alias t is in scope, not types, which the alias replaces (fix: write t::User)" + packages: app: schemas: { + types: _refTypes + api: "use package::types as t\n\n" + (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + + // The forms that name an item bring in the item, and not the namespace. + "item-bare": { + about: "after use package::types::User, User reaches the item" + packages: app: schemas: { + types: _refTypes + api: "use package::types::User\n\n" + (_refHolder & {_ref: "User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "item-qualified-refused": { + about: "after use package::types::User, types is not in scope (fix: write User)" + packages: app: schemas: { + types: _refTypes + api: "use package::types::User\n\n" + (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + "braces-bare": { + about: "after use package::types::{User, Order}, User reaches the item" + packages: app: schemas: { + types: _refTypes + api: "use package::types::{User, Order}\n\n" + (_refHolder & {_ref: "User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "braces-qualified-refused": { + about: "after use package::types::{User, Order}, types is not in scope (fix: write User)" + packages: app: schemas: { + types: _refTypes + api: "use package::types::{User, Order}\n\n" + (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + "glob-bare": { + about: "after use package::types::*, User reaches the item" + packages: app: schemas: { + types: _refTypes + api: "use package::types::*\n\n" + (_refHolder & {_ref: "User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "glob-qualified-refused": { + about: "after use package::types::*, types is not in scope (fix: write User)" + packages: app: schemas: { + types: _refTypes + api: "use package::types::*\n\n" + (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + "no-use-bare-refused": { + about: "a bare User with no use is not in scope (fix, offered because User is declared in package::types: add use package::types::User, or write package::types::User)" + packages: app: schemas: { + types: _refTypes + api: (_refHolder & {_ref: "User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::not-in-scope"]} + } + "no-use-qualified-refused": { + about: "types::User with no use is not rooted in a name in scope (fix, offered because the package declares types::User: add use package::types, or write package::types::User)" + packages: app: schemas: { + types: _refTypes + api: (_refHolder & {_ref: "types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + + // A name or a qualifier that nothing declares has the same two codes, and + // no fix that adds a `use`, as there is nothing to import. + "nowhere-bare-refused": { + about: "a bare Nowhere that no schema of the package or its dependencies declares is not in scope (no fix that adds a use is offered: nothing declares it)" + packages: app: schemas: { + types: _refTypes + api: "use package::types\n\n" + (_refHolder & {_ref: "Nowhere"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::not-in-scope"]} + } + "nowhere-qualified-refused": { + about: "nope::types::User, whose first segment matches no name in scope, root or schema, is not in scope (no fix that adds a use is offered: nothing is named nope)" + packages: app: schemas: { + types: _refTypes + api: (_refHolder & {_ref: "nope::types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + + // A name defined twice is an error, as in Rust: a local declaration with + // the name of a `use`d item, or two `use`s bringing in the same name. An + // alias resolves the clash. + "defined-twice-local-and-use": { + about: "use package::billing::Invoice and struct Invoice in the same schema define Invoice twice (fix: rename one, or import with an alias: use package::billing::Invoice as BillingInvoice)" + packages: app: schemas: { + "billing/api": _refBilling + "api": "use package::billing::api::Invoice\n\n" + _refBilling + } + build: "app" + expect: {builds: false, errors: ["reference::defined-twice"]} + } + "defined-twice-two-uses": { + about: "use package::a::User and use package::b::User bring in User twice (fix: rename one, or import with an alias: use package::b::User as BUser)" + packages: app: schemas: { + a: _refTypes + b: _refTypes + api: "use package::a::User\nuse package::b::User\n\nstruct Account {\n id: u32\n}" + } + build: "app" + expect: {builds: false, errors: ["reference::defined-twice"]} + } + "alias-resolves-local-clash": { + about: "use package::billing::api::Invoice as BillingInvoice beside a local Invoice defines each name once" + packages: app: schemas: { + "billing/api": _refBilling + "api": "use package::billing::api::Invoice as BillingInvoice\n\n" + _refBilling + "\n\nstruct Account {\n billed: BillingInvoice\n own: Invoice\n}" + } + build: "app" + expect: {builds: true, protocols: {}} + } + "alias-resolves-two-uses": { + about: "use package::a::User beside use package::b::User as BUser defines each name once" + packages: app: schemas: { + a: _refTypes + b: _refTypes + api: "use package::a::User\nuse package::b::User as BUser\n\nstruct Account {\n first: User\n second: BUser\n}" + } + build: "app" + expect: {builds: true, protocols: {}} + } + + // A full path works in a type position without a `use`. + "full-package": { + about: "package::types::User in a field needs no use" + packages: app: schemas: { + types: _refTypes + api: (_refHolder & {_ref: "package::types::User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "full-package-nested": { + about: "package:: reaches a schema in a directory from one beside it, in a field" + packages: app: schemas: { + "shapes/types": _refTypes + "shapes/api": (_refHolder & {_ref: "package::shapes::types::User"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "full-parent": { + about: "parent::common::Error in a field reaches a schema one level up from the importing schema's namespace" + packages: app: schemas: { + "shapes/common": "struct Error {\n code: u32\n}" + "shapes/api": (_refHolder & {_ref: "parent::common::Error"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "full-self": { + about: "self::nested::Type in a field reaches a schema under the importing schema's own namespace" + packages: app: schemas: { + "api": (_refHolder & {_ref: "self::nested::Type"}).text + "api/nested": "struct Type {\n id: u32\n}" + } + build: "app" + expect: {builds: true, protocols: {}} + } + "full-std": { + about: "std::http::Request in a field needs no use" + packages: app: schemas: api: (_refHolder & {_ref: "std::http::Request"}).text + build: "app" + expect: {builds: true, protocols: {}} + } + "full-dependency": { + about: "a dependency's greeting::hello::Greeting in a field needs no use" + packages: { + greeting: schemas: hello: _refGreeting + app: { + schemas: api: (_refHolder & {_ref: "greeting::hello::Greeting"}).text + dependencies: greeting: {} + } + } + build: "app" + expect: {builds: true, protocols: {}} + } + "full-own-schema-unrooted-refused": { + about: "a full path to the package's own schema that doesn't start at package, parent or self is not rooted (fix, offered because the schema exists: write package::shapes::types::User)" + packages: app: schemas: { + "shapes/types": _refTypes + "api": (_refHolder & {_ref: "shapes::types::User"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + + // A path goes down from a name in scope. + "descend-namespace": { + about: "after use package::billing, billing::api::Invoice reaches the nested schema" + packages: app: schemas: { + "billing/api": _refBilling + "api": "use package::billing\n\n" + (_refHolder & {_ref: "billing::api::Invoice"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "descend-alias": { + about: "after use package::billing as b, b::api::Invoice reaches the nested schema" + packages: app: schemas: { + "billing/api": _refBilling + "api": "use package::billing as b\n\n" + (_refHolder & {_ref: "b::api::Invoice"}).text + } + build: "app" + expect: {builds: true, protocols: {}} + } + "descend-dependency": { + about: "after use greeting::hello, hello::Greeting reaches the dependency's item" + packages: { + greeting: schemas: hello: _refGreeting + app: { + schemas: api: "use greeting::hello\n\n" + (_refHolder & {_ref: "hello::Greeting"}).text + dependencies: greeting: {} + } + } + build: "app" + expect: {builds: true, protocols: {}} + } + "descend-dependency-name": { + about: "after use greeting, a dependency's name on its own, greeting::hello::Greeting reaches the dependency's item" + packages: { + greeting: schemas: hello: _refGreeting + app: { + schemas: api: "use greeting\n\n" + (_refHolder & {_ref: "greeting::hello::Greeting"}).text + dependencies: greeting: {} + } + } + build: "app" + expect: {builds: true, protocols: {}} + } + "descend-skips-a-segment-refused": { + about: "after use package::billing, api is not in scope (fix, offered because billing::api exists: write billing::api::Invoice, or add use package::billing::api)" + packages: app: schemas: { + "billing/api": _refBilling + "api": "use package::billing\n\n" + (_refHolder & {_ref: "api::Invoice"}).text + } + build: "app" + expect: {builds: false, errors: ["reference::qualifier-not-in-scope"]} + } + + // A qualified reference is frozen as its resolved path: each spelling + // reaches the `Invoice` in `billing/api`, and not the decoy in `archive`, + // which an unmarked protocol using it can't give up. + "resolved-item": { + about: "use package::billing::api::Invoice, then Invoice, reaches billing::api::Invoice" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "use package::billing::api::Invoice\n\n" + (_refOrders & {_ref: "Invoice"}).text + } + } + build: "app" + expect: { + builds: true + protocols: {Dump: _refDump, Orders: given_up: []} + warnings: ["unverified::bounded-size"] + } + } + "resolved-namespace": { + about: "use package::billing::api, then api::Invoice, reaches billing::api::Invoice" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "use package::billing::api\n\n" + (_refOrders & {_ref: "api::Invoice"}).text + } + } + build: "app" + expect: { + builds: true + protocols: {Dump: _refDump, Orders: given_up: []} + warnings: ["unverified::bounded-size"] + } + } + "resolved-descent": { + about: "use package::billing, then billing::api::Invoice, reaches billing::api::Invoice" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "use package::billing\n\n" + (_refOrders & {_ref: "billing::api::Invoice"}).text + } + } + build: "app" + expect: { + builds: true + protocols: {Dump: _refDump, Orders: given_up: []} + warnings: ["unverified::bounded-size"] + } + } + "resolved-alias": { + about: "use package::billing::api as b, then b::Invoice, reaches billing::api::Invoice" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "use package::billing::api as b\n\n" + (_refOrders & {_ref: "b::Invoice"}).text + } + } + build: "app" + expect: { + builds: true + protocols: {Dump: _refDump, Orders: given_up: []} + warnings: ["unverified::bounded-size"] + } + } + "resolved-full-path": { + about: "package::billing::api::Invoice with no use reaches billing::api::Invoice" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "" + (_refOrders & {_ref: "package::billing::api::Invoice"}).text + } + } + build: "app" + expect: { + builds: true + protocols: {Dump: _refDump, Orders: given_up: []} + warnings: ["unverified::bounded-size"] + } + } + "resolved-decoy": { + about: "use package::archive, then archive::Invoice, reaches the unbounded Invoice, which an unmarked protocol can't use: the other cases reached billing's" + packages: app: { + config: [_allow] + schemas: { + "archive": _refArchive + "billing/api": _refBilling + "api": "use package::archive\n\n" + (_refOrders & {_ref: "archive::Invoice"}).text + } + } + build: "app" + expect: {builds: false, errors: ["bounds::unbounded"]} + } + + // A package written before the rule: a namespace `use` and references + // qualified with the schema's namespace. Its protocols freeze as they did. + "existing-package-unchanged": { + about: "use package::models and models::Blob, as written before the rule, freezes the same protocols as the item use does in bounded/other-schema-marked" + packages: app: { + config: [_allow] + schemas: { + models: """ + struct Blob { + data: string + } + + @unverified = "the uploader streams whatever it's given" + protocol Upload { + function put(b: Blob); + } + """ + api: """ + use package::models + + @unverified = "orders carry the upload" + protocol Orders { + function send(b: models::Blob); + } + """ + } + } + build: "app" + expect: { + builds: true + protocols: { + Upload: { + given_up: ["bounded_size"] + acknowledged: bounded_size: {scope: "protocol", reason: "the uploader streams whatever it's given"} + } + Orders: { + given_up: ["bounded_size"] + acknowledged: bounded_size: {scope: "protocol", reason: "orders carry the upload"} + } + } + warnings: ["unverified::bounded-size"] + } + } +} diff --git a/runtime/conformance/spec/rust/src/catalog.rs b/runtime/conformance/spec/rust/src/catalog.rs index 0ed3cee..3e7c461 100644 --- a/runtime/conformance/spec/rust/src/catalog.rs +++ b/runtime/conformance/spec/rust/src/catalog.rs @@ -5,7 +5,7 @@ use crate::{ SeqSize, Sizes, Status, StringSize, StructSize, Value, Width, }; -pub const SPEC_VERSION: &str = r#"0.11"#; +pub const SPEC_VERSION: &str = r#"0.12"#; /// Every guarantee, in the catalog's order. pub const GUARANTEES: &[Guarantee] = &[ @@ -377,7 +377,7 @@ pub const ENCODINGS: &[Encoding] = &[ Encoding { id: r#"datagram@1"#, kind: Kind::Framing, - title: r#"datagram"#, + title: r#"datagram@1"#, description: r#"Comline's own binary framing of requests and responses."#, aliases: &[r#"datagram"#, r#"comline.datagram"#], frozen_as: Some(r#"datagram"#), diff --git a/runtime/conformance/spec/specs/compiler.cue b/runtime/conformance/spec/specs/compiler.cue index 9c7a736..07cab4d 100644 --- a/runtime/conformance/spec/specs/compiler.cue +++ b/runtime/conformance/spec/specs/compiler.cue @@ -104,6 +104,11 @@ import "github.com/comlineproject/specification/catalog" close({code!: "bounds::unbounded", severity!: "error"}), close({code!: "bounds::unbounded-depth", severity!: "error"}), close({code!: "settings::forbidden", severity!: "error"}), + close({code!: "import::bare-own-schema-path", severity!: "error"}), + close({code!: "import::unresolved", severity!: "error"}), + close({code!: "reference::not-in-scope", severity!: "error"}), + close({code!: "reference::qualifier-not-in-scope", severity!: "error"}), + close({code!: "reference::defined-twice", severity!: "error"}), ]) #CompilerWarning: or([ diff --git a/runtime/conformance/spec/specs/gen/compiler.schema.json b/runtime/conformance/spec/specs/gen/compiler.schema.json index 5613bbd..0dc6fe0 100644 --- a/runtime/conformance/spec/specs/gen/compiler.schema.json +++ b/runtime/conformance/spec/specs/gen/compiler.schema.json @@ -112,6 +112,26 @@ { "code": "settings::forbidden", "severity": "error" + }, + { + "code": "import::bare-own-schema-path", + "severity": "error" + }, + { + "code": "import::unresolved", + "severity": "error" + }, + { + "code": "reference::not-in-scope", + "severity": "error" + }, + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + }, + { + "code": "reference::defined-twice", + "severity": "error" } ] }, diff --git a/runtime/conformance/spec/vectors/handshake-comline2.json b/runtime/conformance/spec/vectors/handshake-comline2.json index 848264f..4b320a9 100644 --- a/runtime/conformance/spec/vectors/handshake-comline2.json +++ b/runtime/conformance/spec/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/conformance/src/comline2.rs b/runtime/conformance/src/comline2.rs index 9dbccc2..fdf37ed 100644 --- a/runtime/conformance/src/comline2.rs +++ b/runtime/conformance/src/comline2.rs @@ -162,6 +162,14 @@ fn base(exchange: Exchange) -> Hello { } } +/// `base` listing only the protocols numbered `keep`: an end that provides +/// and calls some of the package's protocols, not all. +fn subset(exchange: Exchange, keep: &[u16]) -> Hello { + let mut h = base(exchange); + h.protocols.retain(|p| keep.contains(&p.number)); + h +} + fn message_case(id: &str, message: Message) -> Case { Case { id: format!("handshake-comline2/{id}"), @@ -189,12 +197,25 @@ fn negotiate_case( side: Option, params: Params, peer: Vec, +) -> Case { + negotiate_case_for(id, step, side, params, base(params.exchange), peer) +} + +/// A negotiation case for a local end that lists `local`: the hello it was +/// built with, not necessarily every protocol of the package. +fn negotiate_case_for( + id: &str, + step: Step, + side: Option, + params: Params, + local: Hello, + peer: Vec, ) -> Case { let input = NegotiateIn { step, side, params: Some(params), - local: Some(Comline2::new(params, base(params.exchange)).hello), + local: Some(Comline2::new(params, local).hello), pending: None, reply: None, result: NegotiateResult::Refused(Refusal { reason: Reason::Malformed, side: Side::Initiator, protocol: None }), @@ -249,6 +270,10 @@ pub fn cases() -> Vec { protocol(65535, (0, 0, 1), 0x03, &[5]), ]; cases.push(message_case("hello-symmetric-wide", Message::Hello(wide))); + // A Hello for a subset (specification#13): protocol 1 alone. It is the + // `hello` case's bytes with protocol 0's entry gone, and its protocol count + // one. + cases.push(message_case("hello-subset", Message::Hello(subset(Exchange::Offer, &[1])))); let mut empty = base(Exchange::Offer); empty.encodings.clear(); empty.protocols.clear(); @@ -370,6 +395,22 @@ pub fn cases() -> Vec { answer("offer-same-version-differs-warn", warn, peer(&same_version_differs)), answer("offer-unknown-protocol", package, peer(&|h| h.protocols.push(protocol(7, (0, 3, 0), 0xc0, &[0])))), answer("offer-only-unknown-protocols", offer, peer(&|h| h.protocols = vec![protocol(7, (0, 3, 0), 0xc0, &[0])])), + // A Hello for a subset (specification#13). The offer lists protocol 0 + // alone: protocol 1, which only this end has, is refused on its own + // (`unknown_protocol`) and every call to it fails locally; the answer + // names only what the offer listed. + answer("offer-subset-offered", offer, hello_bytes(subset(Exchange::Offer, &[0]))), + // This end lists protocol 1 alone, the offer both: protocol 0, which + // only the offerer has, is refused in the answer and is not in this + // end's result. + negotiate_case_for( + "offer-subset-local", + Step::AnswerOffer, + None, + offer, + subset(Exchange::Offer, &[1]), + hello_bytes(base(Exchange::Offer)), + ), answer("offer-package-mismatch", offer, peer(&|h| h.package_id = hash(0xee))), answer("offer-encoding-mismatch", offer, peer(&|h| h.encodings[0].param_hash = hash(0x12))), answer("offer-exchange-mismatch", offer, peer(&|h| h.exchange = Exchange::Symmetric)), @@ -400,6 +441,23 @@ pub fn cases() -> Vec { conclude("conclude-same-version-differs-warn", warn, accepted(PackageVersion::release(0, 3, 0), differs)), conclude("conclude-protocol-refused", offer, accepted(PackageVersion::release(0, 4, 0), Status::Refused { reason: Reason::LineMismatch })), conclude("conclude-refused", offer, Answer::Refuse(Refusal { reason: Reason::EncodingMismatch, side: Side::Responder, protocol: None })), + // A Hello for a subset (specification#13): this end offered protocol 0 + // alone, and the answer takes it. + negotiate_case_for( + "conclude-subset", + Step::ConcludeAnswer, + None, + offer, + subset(Exchange::Offer, &[0]), + Message::Answer(Answer::Accept { + version: PackageVersion::release(0, 3, 0), + protocols: vec![Answered { number: 0, status: Status::Accepted { shape_differs: false, missing: vec![] } }], + }) + .to_bytes(), + ), + // ... and an answer that also names protocol 1, which this end never + // listed, is not one to a Hello like this: `malformed`. + negotiate_case_for("conclude-answer-beyond-offer", Step::ConcludeAnswer, None, offer, subset(Exchange::Offer, &[0]), Message::Answer(accepted(PackageVersion::release(0, 3, 0), Status::Accepted { shape_differs: false, missing: vec![] })).to_bytes()), negotiate_case("conclude-malformed", Step::ConcludeAnswer, None, offer, b"CO\x02".to_vec()), negotiate_case("conclude-exchange-mismatch", Step::ConcludeAnswer, None, offer, hello_bytes(base(Exchange::Symmetric))), ]); @@ -424,6 +482,17 @@ pub fn cases() -> Vec { judge("symmetric-responder-newer-consumer-refuse", Side::Responder, Params { newer_consumer: NewerConsumer::Refuse, ..symmetric }, sym_peer(&newer)), judge("symmetric-line-mismatch", Side::Responder, symmetric, sym_peer(&line_moved)), judge("symmetric-unknown-protocol", Side::Initiator, symmetric, sym_peer(&|h| { h.protocols.pop(); })), + // A Hello for a subset (specification#13): this end lists protocol 0 + // alone and the peer both. The verdict refuses protocol 1, which only + // the peer has, and this end's result has no protocol 1. + negotiate_case_for( + "symmetric-subset-local", + Step::JudgeHello, + Some(Side::Initiator), + symmetric, + subset(Exchange::Symmetric, &[0]), + sym_peer(&|_| {}), + ), judge("symmetric-same-version-differs-warn", Side::Responder, Params { same_version_differs: SameVersionDiffers::Warn, ..symmetric }, sym_peer(&same_version_differs)), judge("symmetric-exchange-mismatch", Side::Responder, symmetric, peer(&|_| {})), judge("symmetric-peer-refused", Side::Initiator, symmetric, Message::Answer(Answer::Refuse(Refusal { reason: Reason::ExchangeMismatch, side: Side::Responder, protocol: None })).to_bytes()), @@ -446,6 +515,18 @@ pub fn cases() -> Vec { pending.clone(), Message::Verdict(Verdict::Accept { refused: vec![RefusedProtocol { number: 0, reason: Reason::NewerConsumer }] }), ), + // The peer's verdict refuses protocol 1, which this end never listed + // (specification#13): what this end agreed doesn't change. + finish_case( + "finish-refused-unlisted", + Side::Initiator, + Negotiated { + peer_version: PackageVersion::release(0, 3, 0), + protocols: vec![ProtocolOutcome { number: 0, state: ProtocolState::Accepted { peer_lacks: vec![] } }], + warnings: vec![], + }, + Message::Verdict(Verdict::Accept { refused: vec![RefusedProtocol { number: 1, reason: Reason::UnknownProtocol }] }), + ), finish_case( "finish-refused", Side::Initiator, diff --git a/runtime/core/src/connection/asynchronous/mod.rs b/runtime/core/src/connection/asynchronous/mod.rs index 748fc3b..b4357b5 100644 --- a/runtime/core/src/connection/asynchronous/mod.rs +++ b/runtime/core/src/connection/asynchronous/mod.rs @@ -20,6 +20,7 @@ use crate::contract::stream::DEFAULT_MAX_FRAME; use crate::contract::{ ConnectionFraming, ConnectionId, Datagram2Framing, ProtocolNumber, RuntimeError, WireFormat, }; +use crate::handshake::comline2::Negotiated; use crate::handshake::{AsyncHandshake, ComlineHandshake, Facts}; use crate::transport::AsyncTransport; @@ -31,7 +32,7 @@ use driver::{Calls, Command, Driver, Providers, Shared}; /// /// ```ignore /// let mut conn = AsyncConnection::accept(transport, Json, CONNECTION_IR_HASH).await?; -/// ChatAsyncDispatcher(ChatImpl).provide_on(&mut conn); +/// ChatAsyncDispatcher(ChatImpl).provide_on(&mut conn)?; /// let events = conn.handle(); /// tokio::spawn(conn.run()); /// EventsAsyncSender::new(&events).message("pushed").await?; @@ -42,6 +43,9 @@ pub struct AsyncConnection { commands: mpsc::UnboundedReceiver, providers: Providers, limit: usize, + /// What the connection's handshake agreed, when it negotiated protocol by + /// protocol (`comline@2`): what [`provide`](Self::provide) checks against. + agreed: Option, } impl AsyncConnection @@ -113,6 +117,7 @@ where commands, providers: Vec::new(), limit: 1, + agreed: None, } } @@ -139,7 +144,10 @@ where ) -> Result { let local = Facts::new(ir_hash, format.name(), framing.name()); handshake.initiate(&mut transport, &local).await?; - Ok(Self::with_framing_unverified(transport, format, framing)) + let agreed = handshake.agreed().cloned(); + let mut conn = Self::with_framing_unverified(transport, format, framing); + conn.agreed = agreed; + Ok(conn) } /// Answer with `handshake` ([`AsyncHandshake::respond`]). @@ -152,17 +160,40 @@ where ) -> Result { let local = Facts::new(ir_hash, format.name(), framing.name()); handshake.respond(&mut transport, &local).await?; - Ok(Self::with_framing_unverified(transport, format, framing)) + let agreed = handshake.agreed().cloned(); + let mut conn = Self::with_framing_unverified(transport, format, framing); + conn.agreed = agreed; + Ok(conn) } /// Provide `protocol` on this connection: the peer's requests to it go to /// `dispatcher`. Replaces one already registered for it. - pub fn provide(&mut self, protocol: ProtocolNumber, dispatcher: D) { + /// + /// 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 + /// ([`Negotiated::check_provide`]). A connection with no such handshake + /// (`comline@1`, `none`, or [`new_unverified`](AsyncConnection::new_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. + pub fn provide( + &mut self, + protocol: ProtocolNumber, + dispatcher: D, + ) -> Result<(), RuntimeError> { + if let Some(agreed) = &self.agreed { + agreed.check_provide(protocol)?; + } let index = usize::from(protocol); if self.providers.len() <= index { self.providers.resize_with(index + 1, || None); } self.providers[index] = Some(Arc::new(dispatcher)); + Ok(()) } /// Let up to `limit` of the peer's requests run at once, for protocols diff --git a/runtime/core/src/connection/blocking.rs b/runtime/core/src/connection/blocking.rs index 4762f16..a4a89d0 100644 --- a/runtime/core/src/connection/blocking.rs +++ b/runtime/core/src/connection/blocking.rs @@ -8,6 +8,7 @@ use crate::contract::{ Call, ConnectionFraming, ConnectionId, Datagram2Framing, Dispatch, Envelope, Frame, Kind, Outcome, Peer, ProtocolNumber, Reply, Request, RequestCall, RuntimeError, WireFormat, }; +use crate::handshake::comline2::Negotiated; use crate::handshake::{ComlineHandshake, Facts, Handshake}; use crate::transport::Transport; @@ -30,6 +31,9 @@ use crate::connection::state::{Event, State}; pub struct Connection { link: Link, providers: Providers, + /// What the connection's handshake agreed, when it negotiated protocol by + /// protocol (`comline@2`): what [`provide`](Self::provide) checks against. + agreed: Option, } /// The parts of a [`Connection`] a handler borrows mutably while the @@ -173,6 +177,7 @@ impl Connection { body: Vec::new(), }, providers: Providers { table: Vec::new() }, + agreed: None, } } @@ -186,7 +191,10 @@ impl Connection { ) -> Result { let local = Facts::new(ir_hash, format.name(), framing.name()); handshake.initiate(&mut transport, &local)?; - Ok(Self::with_framing_unverified(transport, format, framing)) + let agreed = handshake.agreed().cloned(); + let mut conn = Self::with_framing_unverified(transport, format, framing); + conn.agreed = agreed; + Ok(conn) } /// Answer with `handshake` ([`Handshake::respond`]). @@ -199,17 +207,40 @@ impl Connection { ) -> Result { let local = Facts::new(ir_hash, format.name(), framing.name()); handshake.respond(&mut transport, &local)?; - Ok(Self::with_framing_unverified(transport, format, framing)) + let agreed = handshake.agreed().cloned(); + let mut conn = Self::with_framing_unverified(transport, format, framing); + conn.agreed = agreed; + Ok(conn) } /// Provide `protocol` on this connection: the peer's requests to it go to /// `dispatcher`. Replaces one already registered for it. - pub fn provide(&mut self, protocol: ProtocolNumber, dispatcher: D) { + /// + /// 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 + /// ([`Negotiated::check_provide`]). A connection with no such handshake + /// (`comline@1`, `none`, or [`new_unverified`](Connection::new_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. + pub fn provide( + &mut self, + protocol: ProtocolNumber, + dispatcher: D, + ) -> Result<(), RuntimeError> { + if let Some(agreed) = &self.agreed { + agreed.check_provide(protocol)?; + } let index = usize::from(protocol); if self.providers.table.len() <= index { self.providers.table.resize_with(index + 1, || None); } self.providers.table[index] = Some(Box::new(dispatcher)); + Ok(()) } /// Handle the peer's next frame. `Ok(true)`: one was handled; diff --git a/runtime/core/src/contract/error.rs b/runtime/core/src/contract/error.rs index 5b45b64..ef35961 100644 --- a/runtime/core/src/contract/error.rs +++ b/runtime/core/src/contract/error.rs @@ -86,6 +86,10 @@ pub enum RuntimeError { /// written. The caller knows which call it made, so the error doesn't /// repeat it: that keeps this type 4 bytes, which the decode paths /// need. + /// + /// It is also what a connection's `provide` returns for a protocol the + /// handshake didn't accept: one this end's Hello didn't list, or one the + /// peer refused. The same protocols whose calls fail locally. Unavailable, /// The peer says it couldn't read a request of this side's, and not which: /// a JSON-RPC error with a `null` id, as the specification has for a diff --git a/runtime/core/src/handshake/comline2/driver.rs b/runtime/core/src/handshake/comline2/driver.rs index 1d0797a..260746d 100644 --- a/runtime/core/src/handshake/comline2/driver.rs +++ b/runtime/core/src/handshake/comline2/driver.rs @@ -73,6 +73,10 @@ impl Handshake for Comline2Handshake { HANDSHAKE_COMLINE2 } + fn agreed(&self) -> Option<&Negotiated> { + self.negotiated() + } + fn initiate( &mut self, transport: &mut T, @@ -162,6 +166,10 @@ impl AsyncHandshake for Comline2Handshake { HANDSHAKE_COMLINE2 } + fn agreed(&self) -> Option<&Negotiated> { + self.negotiated() + } + async fn initiate( &mut self, transport: &mut T, diff --git a/runtime/core/src/handshake/comline2/facts.rs b/runtime/core/src/handshake/comline2/facts.rs index a39086c..6a328eb 100644 --- a/runtime/core/src/handshake/comline2/facts.rs +++ b/runtime/core/src/handshake/comline2/facts.rs @@ -141,7 +141,94 @@ pub struct Hello { pub protocols: Vec, } +/// What a [`Hello`] holds whichever protocols it lists: the exchange, the +/// package's id and version, and the connection's encodings. A generator +/// emits it once for the package, beside one [`ProtocolEntry`] per protocol, +/// and [`Hello::build`] puts them together at runtime, so an end lists only +/// the protocols it provides and calls. Every field is a constant a generator +/// can write out, hence the borrows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HelloHeader<'a> { + pub exchange: Exchange, + /// `id` in `config.idp`. + pub package_id: Hash128, + /// The package version's release. + pub version: Release, + /// The package version's pre-release (`dev.2`), empty for a release. + pub pre: &'a str, + /// The encodings the connection uses, in any order: [`Hello::build`] + /// puts them in the wire's. + pub encodings: &'a [Encoding], +} + +/// One protocol's entry for a [`Hello`]: [`Protocol`], borrowing its function +/// numbers so a generator can write each one out as a constant. 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`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ProtocolEntry<'a> { + pub number: u16, + /// The release the protocol last broke at. + pub line: Release, + pub shape_hash: Hash128, + /// The functions' wire numbers, in any order. + pub functions: &'a [u16], +} + +impl ProtocolEntry<'_> { + fn to_protocol(self) -> Protocol { + Protocol { + number: self.number, + line: self.line, + shape_hash: self.shape_hash, + functions: self.functions.to_vec(), + } + } +} + impl Hello { + /// The Hello of one end that provides `provided` and calls `called`: the + /// header's package and encodings, and exactly those protocols' entries, + /// in [`canonical`](Self::canonical) order. + /// + /// - **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. + /// + /// The `exchange` is the header's, and [`Comline2::new`](super::Comline2::new) + /// sets it from its parameters anyway. + pub fn build( + header: &HelloHeader<'_>, + provided: &[ProtocolEntry<'_>], + called: &[ProtocolEntry<'_>], + ) -> Self { + let mut protocols: Vec = Vec::with_capacity(provided.len() + called.len()); + for entry in provided.iter().chain(called) { + if !protocols.iter().any(|p| p.number == entry.number) { + protocols.push(entry.to_protocol()); + } + } + Hello { + exchange: header.exchange, + package_id: header.package_id, + version: PackageVersion { + release: header.version, + pre: String::from(header.pre), + }, + encodings: header.encodings.to_vec(), + protocols, + } + .canonical() + } + /// Sorts encodings, protocols and functions into the order the wire /// requires. pub fn canonical(mut self) -> Self { diff --git a/runtime/core/src/handshake/comline2/mod.rs b/runtime/core/src/handshake/comline2/mod.rs index 000e654..4c0eec7 100644 --- a/runtime/core/src/handshake/comline2/mod.rs +++ b/runtime/core/src/handshake/comline2/mod.rs @@ -22,6 +22,15 @@ //! - `exchange = offer | symmetric`: the initiator offers and the responder //! answers, or both declare and both judge. //! +//! **A Hello for a subset.** A [`Hello`] lists the protocols its end provides +//! and the ones it calls, not necessarily every protocol of the package: a +//! connection carries exactly what its Hello lists. The peer refuses the rest +//! (`unknown_protocol`), calls to them fail locally with +//! [`RuntimeError::Unavailable`](crate::contract::RuntimeError::Unavailable), and a connection that ran this handshake +//! refuses to `provide` a protocol it didn't accept ([`Negotiated::accepts`]). +//! [`Hello::build`] puts a Hello together from a [`HelloHeader`] and the +//! [`ProtocolEntry`]s of what the end provides and calls. +//! //! The messages and their layout are in [`Message`]; the sans-IO steps are //! on [`Comline2`], and [`Comline2Handshake`] runs them over a //! [`Transport`](crate::transport::Transport) (and, with `async`, an `AsyncTransport`). @@ -34,7 +43,10 @@ mod message; mod negotiate; pub use driver::Comline2Handshake; -pub use facts::{Encoding, EncodingKind, Hash128, Hello, PackageVersion, Protocol, Release}; +pub use facts::{ + Encoding, EncodingKind, Hash128, Hello, HelloHeader, PackageVersion, Protocol, ProtocolEntry, + Release, +}; pub use message::{Answer, Answered, Message, Refusal, RefusedProtocol, Status, Verdict}; pub use negotiate::{Comline2, Negotiated, ProtocolOutcome, ProtocolState, Step}; diff --git a/runtime/core/src/handshake/comline2/negotiate.rs b/runtime/core/src/handshake/comline2/negotiate.rs index be2c307..f2bceb7 100644 --- a/runtime/core/src/handshake/comline2/negotiate.rs +++ b/runtime/core/src/handshake/comline2/negotiate.rs @@ -60,6 +60,36 @@ impl Negotiated { } } + /// 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 (its Hello didn't list it, as a Hello for a + /// subset leaves protocols out) is not accepted, nor is one it holds as + /// refused. Those are the protocols whose calls fail locally + /// ([`check_call`](Self::check_call)) and that a connection won't + /// [`provide`](Self::check_provide). + pub fn accepts(&self, protocol: u16) -> bool { + self.protocols + .binary_search_by_key(&protocol, |p| p.number) + .is_ok_and(|i| matches!(self.protocols[i].state, ProtocolState::Accepted { .. })) + } + + /// Whether this end may provide `protocol`: `Ok` when the handshake + /// [accepted](Self::accepts) it, or [`RuntimeError::Unavailable`] when its + /// Hello didn't list it or the peer refused it. A connection's `provide` + /// calls this on what its handshake agreed, so a handler can't be attached + /// to a protocol the connection doesn't carry. + /// + /// 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`. + pub fn check_provide(&self, protocol: u16) -> Result<(), RuntimeError> { + if self.accepts(protocol) { + Ok(()) + } else { + Err(RuntimeError::Unavailable) + } + } + /// Takes in the protocols the peer's verdict refused. fn apply(&mut self, refused: &[RefusedProtocol]) { for r in refused { diff --git a/runtime/core/src/handshake/mod.rs b/runtime/core/src/handshake/mod.rs index e420fb8..819736c 100644 --- a/runtime/core/src/handshake/mod.rs +++ b/runtime/core/src/handshake/mod.rs @@ -93,6 +93,17 @@ pub trait Handshake { transport: &mut T, local: &Facts<'_>, ) -> Result<(), RuntimeError>; + + /// What the handshake agreed protocol by protocol, once it has run and + /// succeeded: only `comline@2` negotiates that way, so the default is + /// `None`. A connection opened with this handshake + /// ([`Connection::connect_with`](crate::connection::Connection::connect_with), + /// `accept_with`) keeps it, and its `provide` refuses a protocol the + /// handshake didn't accept. With `None` there is nothing to check + /// against, and `provide` takes any protocol. + fn agreed(&self) -> Option<&comline2::Negotiated> { + None + } } // ── async ────────────────────────────────────────────────────────────────── @@ -140,6 +151,17 @@ pub trait AsyncHandshake { transport: &mut T, local: &Facts<'_>, ) -> impl Future> + Send; + + /// What the handshake agreed protocol by protocol, once it has run and + /// succeeded: only `comline@2` negotiates that way, so the default is + /// `None`. A connection opened with this handshake + /// ([`AsyncConnection::connect_with`](crate::connection::AsyncConnection::connect_with), + /// `accept_with`) keeps it, and its `provide` refuses a protocol the + /// handshake didn't accept. With `None` there is nothing to check + /// against, and `provide` takes any protocol. + fn agreed(&self) -> Option<&comline2::Negotiated> { + None + } } #[cfg(test)] diff --git a/runtime/core/tests/async_connection.rs b/runtime/core/tests/async_connection.rs index ee36002..e72d6eb 100644 --- a/runtime/core/tests/async_connection.rs +++ b/runtime/core/tests/async_connection.rs @@ -154,9 +154,9 @@ async fn pair(chat: ChatDispatcher) -> (Conn, Conn, EventsDispatcher) { AsyncConnection::accept(acceptor, MsgPack, IR_HASH), ); let (mut client, mut server) = (client.unwrap(), server.unwrap()); - server.provide(CHAT, chat); + server.provide(CHAT, chat).unwrap(); let events = EventsDispatcher::default(); - client.provide(EVENTS, events.clone()); + client.provide(EVENTS, events.clone()).unwrap(); (client, server, events) } @@ -273,7 +273,7 @@ async fn a_timed_out_call_s_late_reply_is_dropped() { // Only now does the other side start serving: the first call's reply // arrives first, and is skipped. let mut server = AsyncConnection::new_unverified(acceptor, MsgPack); - server.provide(CHAT, ChatDispatcher::default()); + server.provide(CHAT, ChatDispatcher::default()).unwrap(); tokio::spawn(server.run()); let count: u64 = decode_ok(&caller.call(CHAT, Call::new(1, "count"), &()).await.unwrap()).unwrap(); assert_eq!(count, 0); @@ -358,14 +358,14 @@ async fn an_async_end_talks_to_a_blocking_one_over_tcp() { let blocking = std::thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); let mut conn = Connection::accept(Tcp::new(stream), MsgPack, IR_HASH).unwrap(); - conn.provide(CHAT, BlockingChat); + conn.provide(CHAT, BlockingChat).unwrap(); conn.serve().unwrap(); }); let transport = rt_tokio::Tcp::connect(addr).await.unwrap(); let mut client = AsyncConnection::connect(transport, MsgPack, IR_HASH).await.unwrap(); let events = EventsDispatcher::default(); - client.provide(EVENTS, events.clone()); + client.provide(EVENTS, events.clone()).unwrap(); let caller = client.handle(); let run = tokio::spawn(client.run()); diff --git a/runtime/core/tests/async_handshake.rs b/runtime/core/tests/async_handshake.rs index 5855c2f..2886f4d 100644 --- a/runtime/core/tests/async_handshake.rs +++ b/runtime/core/tests/async_handshake.rs @@ -90,7 +90,7 @@ async fn bump_over( client: AsyncConnection, mut server: AsyncConnection, ) -> u32 { - server.provide(ECHO, Echo); + server.provide(ECHO, Echo).unwrap(); let handle = client.handle(); let client = tokio::spawn(client.run()); let server = tokio::spawn(server.run()); diff --git a/runtime/core/tests/comline2_subset.rs b/runtime/core/tests/comline2_subset.rs new file mode 100644 index 0000000..ad7c255 --- /dev/null +++ b/runtime/core/tests/comline2_subset.rs @@ -0,0 +1,396 @@ +//! A Hello for a subset of the package's protocols (named connections, +//! runtime#124): building one from per-protocol entries, what a connection +//! that ran it lets its end provide, and which calls fail locally. +#![cfg(feature = "std")] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread; + +use comline_runtime::connection::Connection; +use comline_runtime::contract::{ + Call, Datagram2Framing, Dispatch, Kind, Peer, Reason, Reply, RuntimeError, WireFormat, +}; +use comline_runtime::format::MsgPack; +use comline_runtime::handshake::comline2::*; +use comline_runtime::transport::{duplex, InMemory, Transport}; + +const IR_HASH: u64 = 0x1234; + +/// The `hello` case of the specification's `handshake-comline2` vectors: +/// protocols 0 and 1 of the package. +const HELLO: &str = "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330200000200a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a00300010201000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001"; + +/// Its `hello-subset` case: the same Hello with protocol 0's entry gone and +/// the count one. +const HELLO_SUBSET: &str = "434f0201000123456789abcdef0123456789abcdef00030000030011111111111111111111111111111111012222222222222222222222222222222202333333333333333333333333333333330101000100b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0020001"; + +fn bytes(hex: &str) -> Vec { + (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()) + .collect() +} + +fn hash(b: u8) -> Hash128 { + Hash128([b; 16]) +} + +const ENCODINGS: [Encoding; 3] = [ + Encoding { kind: EncodingKind::Format, param_hash: Hash128([0x11; 16]) }, + Encoding { kind: EncodingKind::Framing, param_hash: Hash128([0x22; 16]) }, + Encoding { kind: EncodingKind::Handshake, param_hash: Hash128([0x33; 16]) }, +]; + +fn header(encodings: &[Encoding]) -> HelloHeader<'_> { + HelloHeader { + exchange: Exchange::Offer, + package_id: Hash128::from_hex("0123456789abcdef0123456789abcdef").unwrap(), + version: Release::new(0, 3, 0), + pre: "", + encodings, + } +} + +/// Protocols 0, 1 and 2 of the package; the first two are the vectors'. +fn zero() -> ProtocolEntry<'static> { + ProtocolEntry { number: 0, line: Release::new(0, 2, 0), shape_hash: hash(0xa0), functions: &[0, 1, 2] } +} + +fn one() -> ProtocolEntry<'static> { + ProtocolEntry { number: 1, line: Release::new(0, 1, 0), shape_hash: hash(0xb0), functions: &[0, 1] } +} + +fn two() -> ProtocolEntry<'static> { + ProtocolEntry { number: 2, line: Release::new(0, 1, 0), shape_hash: hash(0xc0), functions: &[0] } +} + +fn encoded(hello: Hello) -> Vec { + Message::Hello(hello).to_bytes() +} + +// ── building a Hello ─────────────────────────────────────────────────────── + +#[test] +fn every_protocol_builds_the_whole_hello_byte_for_byte() { + let header = header(&ENCODINGS); + let whole = bytes(HELLO); + // However the protocols are split between provided and called, in + // whatever order, listed twice or not. + let scrambled = ProtocolEntry { functions: &[2, 0, 1, 1], ..zero() }; + let splits: [(&[ProtocolEntry], &[ProtocolEntry]); 6] = [ + (&[zero(), one()], &[]), + (&[], &[zero(), one()]), + (&[zero()], &[one()]), + (&[one()], &[zero()]), + (&[one(), scrambled], &[zero(), one()]), + (&[zero(), one()], &[one(), zero()]), + ]; + for (provided, called) in splits { + let built = encoded(Hello::build(&header, provided, called)); + assert_eq!(built, whole, "provided {provided:?}, called {called:?}"); + } + // And it is the Hello that bytes decode to. + assert_eq!( + Message::decode(&whole), + Ok(Message::Hello(Hello::build(&header, &[zero(), one()], &[]))) + ); +} + +#[test] +fn a_subset_builds_a_hello_of_those_protocols_alone() { + let header = header(&ENCODINGS); + let subset = bytes(HELLO_SUBSET); + // Protocol 1 alone, provided, called, or both. + let splits: [(&[ProtocolEntry], &[ProtocolEntry]); 3] = + [(&[one()], &[]), (&[], &[one()]), (&[one()], &[one()])]; + for (provided, called) in splits { + assert_eq!(encoded(Hello::build(&header, provided, called)), subset); + } + + let hello = Hello::build(&header, &[zero()], &[]); + assert_eq!(hello.protocols.iter().map(|p| p.number).collect::>(), [0]); + assert_eq!(hello.protocols[0].functions, [0, 1, 2]); + + // What it calls is narrowed to what's passed: the other side's protocol 2 + // isn't listed when the end doesn't call it. + let hello = Hello::build(&header, &[zero()], &[one()]); + assert_eq!(hello.protocols.iter().map(|p| p.number).collect::>(), [0, 1]); + let none = Hello::build(&header, &[], &[]); + assert!(none.protocols.is_empty()); + assert_eq!(none.encodings, ENCODINGS); +} + +#[test] +fn the_headers_encodings_are_put_in_wire_order() { + let reversed = [ENCODINGS[2], ENCODINGS[0], ENCODINGS[1], ENCODINGS[0]]; + let hello = Hello::build(&header(&reversed), &[zero(), one()], &[]); + assert_eq!(encoded(hello), bytes(HELLO)); +} + +#[test] +fn the_headers_version_and_exchange_are_the_hellos() { + let header = HelloHeader { + exchange: Exchange::Symmetric, + pre: "dev.2", + ..header(&ENCODINGS) + }; + let hello = Hello::build(&header, &[one()], &[]); + assert_eq!(hello.exchange, Exchange::Symmetric); + assert_eq!( + hello.version, + PackageVersion { release: Release::new(0, 3, 0), pre: "dev.2".into() } + ); + // `Comline2` sets the exchange from its parameters, as for any Hello. + let params = Params { exchange: Exchange::Offer, ..Params::default() }; + assert_eq!(Comline2::new(params, hello).hello.exchange, Exchange::Offer); +} + +// ── what a connection that ran a Hello lets its end provide ──────────────── + +/// A protocol with no calls, to register. +struct Nop; + +impl Dispatch for Nop { + fn calls(&self) -> &'static [&'static str] { + &[] + } + + fn dispatch( + &self, + _: Kind, + _: &[u8], + _: &W, + _: &mut Reply, + ) -> Result<(), RuntimeError> { + Err(RuntimeError::UnknownCall) + } +} + +/// Every protocol number tried in these tests: the package's, and one it +/// doesn't have. +const NUMBERS: [u16; 4] = [0, 1, 2, 7]; + +type Provided = Vec>; + +fn provide_all( + conn: &mut Connection, +) -> Provided { + NUMBERS.iter().map(|n| conn.provide(*n, Nop)).collect() +} + +/// Runs `comline@2` between `client` (which dials) and `server` over a +/// connection each, and tries to provide every one of [`NUMBERS`] on each: +/// what the dialling and the accepting end got. +fn provided_after(params: Params, client: Hello, server: Hello) -> (Provided, Provided) { + let (dialler, acceptor) = duplex(); + let accepting = thread::spawn(move || { + let mut handshake = Comline2Handshake::new(params, server); + let mut conn = Connection::accept_with(acceptor, MsgPack, Datagram2Framing, &mut handshake, IR_HASH).unwrap(); + provide_all(&mut conn) + }); + let mut handshake = Comline2Handshake::new(params, client); + let mut conn = Connection::connect_with(dialler, MsgPack, Datagram2Framing, &mut handshake, IR_HASH).unwrap(); + let dialling = provide_all(&mut conn); + (dialling, accepting.join().unwrap()) +} + +const OK: Result<(), RuntimeError> = Ok(()); +const NO: Result<(), RuntimeError> = Err(RuntimeError::Unavailable); + +#[test] +fn providing_a_protocol_the_hello_didnt_list_or_the_peer_refused_is_refused() { + let header = header(&ENCODINGS); + for exchange in [Exchange::Offer, Exchange::Symmetric] { + let params = Params { exchange, ..Params::default() }; + + // The dialling end lists protocols 0 and 1; the accepting one has 2 + // as well. For the dialling end, 2 is a protocol its Hello didn't + // list; for the accepting end, one the peer refused + // (`unknown_protocol`). Protocol 7 is in no Hello. + let (dialling, accepting) = provided_after( + params, + Hello::build(&header, &[zero()], &[one()]), + Hello::build(&header, &[zero(), one(), two()], &[]), + ); + assert_eq!(dialling, [OK, OK, NO, NO], "dialling, {exchange:?}"); + assert_eq!(accepting, [OK, OK, NO, NO], "accepting, {exchange:?}"); + + // Both ends list protocol 1, but the lines differ: each refuses it + // on its own, and the others go through. + let moved = ProtocolEntry { line: Release::new(0, 4, 0), ..one() }; + let (dialling, accepting) = provided_after( + params, + Hello::build(&header, &[zero(), two()], &[moved]), + Hello::build(&header, &[zero(), one(), two()], &[]), + ); + assert_eq!(dialling, [OK, NO, OK, NO], "dialling, line mismatch, {exchange:?}"); + assert_eq!(accepting, [OK, NO, OK, NO], "accepting, line mismatch, {exchange:?}"); + + // Every protocol on both ends: everything the Hello lists. + let all = |header: &HelloHeader<'_>| Hello::build(header, &[zero(), one(), two()], &[]); + let (dialling, accepting) = provided_after(params, all(&header), all(&header)); + assert_eq!(dialling, [OK, OK, OK, NO], "dialling, whole, {exchange:?}"); + assert_eq!(accepting, [OK, OK, OK, NO], "accepting, whole, {exchange:?}"); + } +} + +#[test] +fn without_a_hello_nothing_is_checked() { + // Opened by hand, with no handshake at all. + let (a, _b) = duplex(); + let mut conn = Connection::new_unverified(a, MsgPack); + assert_eq!(provide_all(&mut conn), [OK, OK, OK, OK]); + + // `comline@1` has no Hello: it checks the schema's hash, not protocols. + let (dialler, acceptor) = duplex(); + let accepting = thread::spawn(move || { + let mut conn = Connection::accept(acceptor, MsgPack, IR_HASH).unwrap(); + provide_all(&mut conn) + }); + let mut conn = Connection::connect(dialler, MsgPack, IR_HASH).unwrap(); + assert_eq!(provide_all(&mut conn), [OK, OK, OK, OK]); + assert_eq!(accepting.join().unwrap(), [OK, OK, OK, OK]); +} + +// ── calls outside the negotiated result ──────────────────────────────────── + +/// A transport that counts the frames written to it. +struct Counting { + inner: InMemory, + sent: Arc, +} + +impl Transport for Counting { + fn send(&mut self, frame: &[u8]) -> Result<(), RuntimeError> { + self.sent.fetch_add(1, Ordering::SeqCst); + self.inner.send(frame) + } + + fn recv(&mut self, buf: &mut Vec) -> Result<(), RuntimeError> { + self.inner.recv(buf) + } +} + +#[test] +fn a_call_outside_the_negotiated_result_fails_locally_and_sends_nothing() { + let header = header(&ENCODINGS); + for exchange in [Exchange::Offer, Exchange::Symmetric] { + let params = Params { exchange, ..Params::default() }; + // The dialling end lists protocol 0 alone: it provides it, and + // narrowed what it calls to nothing. The accepting end has all three. + let client = Hello::build(&header, &[zero()], &[]); + let server = Hello::build(&header, &[zero(), one(), two()], &[]); + + let (dialler, acceptor) = duplex(); + // The accepting end's result, and its transport, kept open here. + let accepting = thread::spawn(move || { + let mut handshake = Comline2Handshake::new(params, server); + let conn = Connection::accept_with(acceptor, MsgPack, Datagram2Framing, &mut handshake, IR_HASH).unwrap(); + (handshake.negotiated().cloned().unwrap(), conn.into_transport()) + }); + let sent = Arc::new(AtomicUsize::new(0)); + let transport = Counting { inner: dialler, sent: Arc::clone(&sent) }; + let mut handshake = Comline2Handshake::new(params, client); + let mut conn = Connection::connect_with(transport, MsgPack, Datagram2Framing, &mut handshake, IR_HASH).unwrap(); + let (accepted, _accepting_end) = accepting.join().unwrap(); + let negotiated = handshake.negotiated().unwrap(); + + // What a generated sender runs before it writes a request. + let mut call = |protocol: u16, function: u16| -> Result<(), RuntimeError> { + negotiated.check_call(protocol, function)?; + conn.notify(protocol, Call::new(function, "f"), &()) + }; + + let before = sent.load(Ordering::SeqCst); + // Protocols the dialling end's Hello didn't list, and one in no + // Hello: local, and nothing reached the transport. + for protocol in [1, 2, 7] { + assert_eq!(call(protocol, 0), Err(RuntimeError::Unavailable), "{protocol}, {exchange:?}"); + } + assert_eq!(sent.load(Ordering::SeqCst), before, "{exchange:?}"); + // The accepting end holds them as refused (`unknown_protocol`): the + // same error for it, for the same reason. + for protocol in [1, 2] { + assert_eq!(accepted.check_call(protocol, 0), Err(RuntimeError::Unavailable)); + assert_eq!( + accepted.protocols.iter().find(|p| p.number == protocol).map(|p| &p.state), + Some(&ProtocolState::Refused { reason: Reason::UnknownProtocol }) + ); + } + for protocol in NUMBERS { + assert_eq!(negotiated.accepts(protocol), negotiated.check_provide(protocol).is_ok()); + assert_eq!(negotiated.accepts(protocol), negotiated.check_call(protocol, 0).is_ok()); + } + // A protocol the Hello listed goes through, and is written. + assert_eq!(call(0, 1), Ok(()), "{exchange:?}"); + assert_eq!(sent.load(Ordering::SeqCst), before + 1, "{exchange:?}"); + } +} + +// ── the same on an async connection ──────────────────────────────────────── + +#[cfg(feature = "async")] +mod asynchronous { + use super::*; + use comline_runtime::connection::{Answer, AsyncConnection, AsyncDispatch, AsyncPeer}; + use comline_runtime::transport::async_duplex; + + struct AsyncNop; + + impl AsyncDispatch for AsyncNop { + fn calls(&self) -> &'static [&'static str] { + &[] + } + + async fn dispatch<'a, P: AsyncPeer>( + &'a self, + _: Kind, + _: &'a [u8], + _: &'a P, + ) -> Result { + Err(RuntimeError::UnknownCall) + } + } + + fn provide_all(conn: &mut AsyncConnection) -> Provided + where + T: comline_runtime::transport::AsyncTransport, + F: comline_runtime::contract::ConnectionFraming + Send + Sync + 'static, + { + NUMBERS.iter().map(|n| conn.provide(*n, AsyncNop)).collect() + } + + #[tokio::test] + async fn providing_a_protocol_the_hello_didnt_list_or_the_peer_refused_is_refused() { + let header = header(&ENCODINGS); + for exchange in [Exchange::Offer, Exchange::Symmetric] { + let params = Params { exchange, ..Params::default() }; + let (dialler, acceptor) = async_duplex(); + let mut ours = Comline2Handshake::new(params, Hello::build(&header, &[zero()], &[one()])); + let mut theirs = Comline2Handshake::new(params, Hello::build(&header, &[zero(), one(), two()], &[])); + let (client, server) = tokio::join!( + AsyncConnection::connect_with(dialler, MsgPack, Datagram2Framing, &mut ours, IR_HASH), + AsyncConnection::accept_with(acceptor, MsgPack, Datagram2Framing, &mut theirs, IR_HASH), + ); + let (mut client, mut server) = (client.unwrap(), server.unwrap()); + assert_eq!(provide_all(&mut client), [OK, OK, NO, NO], "dialling, {exchange:?}"); + assert_eq!(provide_all(&mut server), [OK, OK, NO, NO], "accepting, {exchange:?}"); + } + } + + #[tokio::test] + async fn without_a_hello_nothing_is_checked() { + let (a, _b) = async_duplex(); + let mut conn = AsyncConnection::new_unverified(a, MsgPack); + assert_eq!(provide_all(&mut conn), [OK, OK, OK, OK]); + + let (dialler, acceptor) = async_duplex(); + let (client, server) = tokio::join!( + AsyncConnection::connect(dialler, MsgPack, IR_HASH), + AsyncConnection::accept(acceptor, MsgPack, IR_HASH), + ); + assert_eq!(provide_all(&mut client.unwrap()), [OK, OK, OK, OK]); + assert_eq!(provide_all(&mut server.unwrap()), [OK, OK, OK, OK]); + } +} diff --git a/runtime/core/tests/connection_roundtrip.rs b/runtime/core/tests/connection_roundtrip.rs index af1ae28..e4c943d 100644 --- a/runtime/core/tests/connection_roundtrip.rs +++ b/runtime/core/tests/connection_roundtrip.rs @@ -149,12 +149,12 @@ fn pair( let (dialler, acceptor) = duplex(); let server = thread::spawn(move || { let mut conn = Connection::accept(acceptor, MsgPack, IR_HASH).unwrap(); - conn.provide(CHAT, ChatDispatcher); + conn.provide(CHAT, ChatDispatcher).unwrap(); serve(&mut conn); }); let mut client = Connection::connect(dialler, MsgPack, IR_HASH).unwrap(); let events = EventsDispatcher::default(); - client.provide(EVENTS, events.clone()); + client.provide(EVENTS, events.clone()).unwrap(); (client, events, server) } diff --git a/runtime/core/tests/frame_limits.rs b/runtime/core/tests/frame_limits.rs index 86e68e9..2136b5b 100644 --- a/runtime/core/tests/frame_limits.rs +++ b/runtime/core/tests/frame_limits.rs @@ -185,7 +185,7 @@ fn a_connection_reports_an_oversized_request() { let (dialled, mut raw) = sockets(); raw.write_all(&[0xff; 4]).unwrap(); let mut conn = Connection::new_unverified(Tcp::new(dialled), MsgPack); - conn.provide(ECHO, EchoDispatcher); + conn.provide(ECHO, EchoDispatcher).unwrap(); assert_eq!(conn.serve_one(), Err(RuntimeError::FrameTooLarge)); } @@ -193,7 +193,7 @@ fn a_connection_reports_an_oversized_request() { fn serve_connection(accepted: TcpStream) -> thread::JoinHandle> { thread::spawn(move || { let mut conn = Connection::new_unverified(Tcp::new(accepted), MsgPack); - conn.provide(ECHO, EchoDispatcher); + conn.provide(ECHO, EchoDispatcher).unwrap(); conn.serve() }) } @@ -321,7 +321,7 @@ mod tokio_tcp { let (dialled, accepted) = tokio_sockets().await; let client = AsyncConnection::new_unverified(rt_tokio::Tcp::new(dialled), MsgPack); let mut server = AsyncConnection::new_unverified(rt_tokio::Tcp::new(accepted), MsgPack); - server.provide(ECHO, AsyncEcho); + server.provide(ECHO, AsyncEcho).unwrap(); (client, server) } diff --git a/runtime/core/tests/frame_limits_config.rs b/runtime/core/tests/frame_limits_config.rs index c771763..5c8ef41 100644 --- a/runtime/core/tests/frame_limits_config.rs +++ b/runtime/core/tests/frame_limits_config.rs @@ -180,7 +180,7 @@ fn a_connection_checks_against_its_transports_configured_limit() { let (a, b) = duplex(); let server = thread::spawn(move || { let mut conn = Connection::new_unverified(b.with_max_frame(LOW), MsgPack); - conn.provide(ECHO, EchoDispatcher); + conn.provide(ECHO, EchoDispatcher).unwrap(); conn.serve() }); let mut conn = Connection::new_unverified(a.with_max_frame(LOW), MsgPack); @@ -252,7 +252,7 @@ mod tokio_tcp { let mut server = AsyncConnection::new_unverified(b, MsgPack); client.set_max_frame(limit); server.set_max_frame(limit); - server.provide(ECHO, AsyncEcho); + server.provide(ECHO, AsyncEcho).unwrap(); let caller = client.handle(); let client = tokio::spawn(client.run()); let server = tokio::spawn(server.run()); diff --git a/runtime/core/tests/jsonrpc_connection.rs b/runtime/core/tests/jsonrpc_connection.rs index b1e4448..ae9c80c 100644 --- a/runtime/core/tests/jsonrpc_connection.rs +++ b/runtime/core/tests/jsonrpc_connection.rs @@ -129,7 +129,7 @@ fn calls_go_both_ways_named_by_protocol() { thread::spawn(move || { let mut conn: JsonRpcConnection = Connection::accept_with(acceptor, Json, JsonRpcFraming, &mut ComlineHandshake, IR_HASH).unwrap(); - conn.provide(CHAT, chat); + conn.provide(CHAT, chat).unwrap(); // A call of its own, then a notification, then serve. let shown: bool = decode_ok( conn.call(EVENTS, Call::new(0, EVENTS_CALLS[0]), &TextParams { text: "pushed".into() }) @@ -144,7 +144,7 @@ fn calls_go_both_ways_named_by_protocol() { let mut client: JsonRpcConnection = Connection::connect_with(dialler, Json, JsonRpcFraming, &mut ComlineHandshake, IR_HASH).unwrap(); let events = EventsDispatcher::default(); - client.provide(EVENTS, events.clone()); + client.provide(EVENTS, events.clone()).unwrap(); // The push and the ping first: a blocking side's calls can't cross. assert!(client.serve_one().unwrap() && client.serve_one().unwrap()); @@ -173,7 +173,7 @@ fn a_notification_gets_no_reply() { let (mut raw, conn_side) = duplex(); let server = thread::spawn(move || { let mut conn: JsonRpcConnection = Connection::with_framing_unverified(conn_side, Json, JsonRpcFraming); - conn.provide(CHAT, ChatDispatcher::default()); + conn.provide(CHAT, ChatDispatcher::default()).unwrap(); conn.notify(EVENTS, Call::new(1, EVENTS_CALLS[1]), &()).unwrap(); conn.serve().unwrap(); }); @@ -222,7 +222,7 @@ async fn the_async_driver_finds_protocols_by_method_and_skips_notifications() { let (mut raw, conn_side) = async_duplex(); let mut conn = AsyncConnection::with_framing_unverified(conn_side, Json, JsonRpcFraming); - conn.provide(CHAT, Count); + conn.provide(CHAT, Count).unwrap(); tokio::spawn(conn.run()); raw.send(br#"{"jsonrpc":"2.0","method":"app.Chat/count","params":null}"#.to_vec()).await.unwrap();