Compare commits

...
Author SHA1 Message Date
Hare 027555eb4e fix: align protocol error semantics 2026-09-30 05:26:34 +09:00
Hare 75119f23e5 feat(example): restore virtual workspace conformance 2026-09-29 06:51:05 +09:00
Hare 653a1171a2 fix: reject malformed host target paths 2026-09-29 06:35:10 +09:00
Hare 2efda433e7 fix: align host dispatch with canonical paths 2026-09-29 06:28:33 +09:00
Hare 2d524723a4 fix: align interface macros with canonical values 2026-09-29 06:11:07 +09:00
Hare 7f4e0e4460 fix: integrate canonical protocol model 2026-09-29 05:54:36 +09:00
Hare 4f0552c48f fix: align protocol model with canonical WIP 2026-09-29 05:47:14 +09:00
Hare 0705101c97 feat(example): add public API end-to-end flow 2026-09-29 00:04:11 +09:00
Hare 5992322371 fix(interface): harden generated public API 2026-09-29 00:04:04 +09:00
Hare d0683f0b6d feat(host): resolve published interface references 2026-09-29 00:03:55 +09:00
Hare f9f083d4c6 fix(host): align descriptor and publication identity 2026-09-28 23:44:43 +09:00
Hare 32f3fb6fb1 feat(host): add object publication and dispatch 2026-09-28 23:36:50 +09:00
Hare 3f94d48f04 fix(interface): preserve operation item uniqueness
Disambiguate generated argument types when distinct operation names normalize to the same PascalCase form, and add the requested Number round-trip and collision regression coverage.
2026-09-28 23:21:13 +09:00
Hare 18ac8844b0 feat(interface): add authoring macros and codecs
Add the wip-interface facade and proc-macro implementation for typed interface descriptors, DTO value codecs, validated dispatch, metadata extraction, and span-aware compile failures.
2026-09-28 23:11:17 +09:00
56 changed files with 7598 additions and 1149 deletions
Generated
+272 -1
View File
@@ -2,13 +2,284 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_spanned"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
dependencies = [
"serde_core",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "target-tuple"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f"
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "toml"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]]
name = "trybuild"
version = "1.0.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0cabaa10be1917331a313866bd94526343e03c77bcf69144b62b072ad35d47c"
dependencies = [
"glob",
"serde",
"serde_derive",
"serde_json",
"target-tuple",
"termcolor",
"toml",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
[[package]]
name = "wip-host"
version = "0.1.0"
dependencies = [
"trybuild",
"wip-interface",
"wip-protocol",
]
[[package]]
name = "wip-interface"
version = "0.1.0"
dependencies = [
"trybuild",
"wip-interface-macros",
"wip-protocol",
]
[[package]]
name = "wip-interface-macros"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "wip-protocol" name = "wip-protocol"
version = "0.1.0" version = "0.1.0"
[[package]] [[package]]
name = "wip-rs" name = "wip-public-api-example"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"wip-host",
"wip-interface",
"wip-protocol", "wip-protocol",
] ]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+1 -9
View File
@@ -1,11 +1,3 @@
[workspace] [workspace]
members = [".", "crates/wip-protocol"] members = ["crates/*"]
resolver = "3" resolver = "3"
[package]
name = "wip-rs"
version = "0.1.0"
edition = "2024"
[dependencies]
wip-protocol = { path = "crates/wip-protocol" }
+246
View File
@@ -0,0 +1,246 @@
# wip-rs
Rust building blocks for the Web Interface Protocol (WIP).
The repository is a resolver-3 virtual Cargo workspace whose packages all live
under `crates/*`. It provides a transport-independent protocol model, a Rust
interface-authoring facade, a request-scoped host runtime, and a private
public-API conformance consumer. The repository root is not itself a package.
HTTP and other transport bindings are intentionally outside the supported
slice.
## Crate graph and responsibilities
```text
wip-public-api-example (workspace-only executable, integration tests, doctest)
├── wip-protocol logical declarations, values, calls, and validation
├── wip-interface application DTO codecs and interface authoring facade
│ ├── wip-protocol
│ └── wip-interface-macros proc-macro implementation detail
└── wip-host descriptor registry, publication, and qualified dispatch
├── wip-interface
└── wip-protocol
```
| Crate | Responsibility | Does not own |
| --- | --- | --- |
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, and interface-qualified dispatch against one host-owned instance. | Backend atomicity, global object lookup, or network serving. |
| `wip-public-api-example` | An independently compiled consumer of only the three public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
The boundary is intentional: protocol types describe what can cross a
transport; application DTOs opt into that model with `WipType`; a host-private
implementation owns credentials, handles, and backend state; and a future
transport maps its own routes/envelopes to `CallOperationRequest` and
`CallOperationResponse` without placing transport-specific types in descriptors
or application traits.
## End-to-end example
[`crates/wip-public-api-example/src/lib.rs`](crates/wip-public-api-example/src/lib.rs)
is the complete public-API example and
[`crates/wip-public-api-example/src/main.rs`](crates/wip-public-api-example/src/main.rs)
runs it. It demonstrates all of the following:
1. public application DTOs derived as `WipType` records, enums, and unions,
including canonical entry paths and schema-opaque JSON;
2. two public traits declared with `#[wip::interface]`;
3. a private host struct implementing both traits;
4. explicit publication of both interfaces as an ordered set on one object;
5. separate observation of opaque interface references, descriptors, and
descriptor validators;
6. calls qualified by `target.path`, object validator, interface reference and
validator, operation, and schema-neutral `Value` arguments;
7. validated result values decoded back to the typed application result;
8. independent dispatch of the same `status` operation name on both interfaces;
9. distinct domain rejection, host/backend failure, `PermissionDenied`, stale
validator recovery, interface membership, and lookup failure codes; and
10. canonical failure precedence when several request fields are invalid.
Run it inside the development shell:
```console
nix develop
cargo run --package wip-public-api-example
```
The public-only conformance suite is in
[`crates/wip-public-api-example/tests/end_to_end.rs`](crates/wip-public-api-example/tests/end_to_end.rs).
It covers canonical object/descriptor shape, ordered interfaces,
schema-neutral record/enum/union/entry/JSON values, fully qualified calls, and
the distinct domain, host, authorization, validator-recovery, and interface
failure classes. Exhaustive public type construction and matching make legacy
ObjectId, descriptor `name`, and semantic `Value` variants compile-time
regressions. Unit tests in the public crates additionally cover every host
dispatch failure, `InvalidRequest` versus descriptor-bound `InvalidArguments`,
invalid local responses, validators, same-named operations, and exhaustive
per-interaction protocol error-code sets.
## Interface authoring
Applications depend on `wip-interface`, normally imported as `wip`:
```rust
use wip_interface as wip;
#[derive(wip::WipType)]
struct Message {
/// Message body.
text: String,
}
#[wip::interface]
pub trait Messenger {
/// Sends a message.
///
/// # Returns
/// Whether the application accepted the message.
fn send(
&self,
/// Message to send.
message: Message,
) -> wip::OperationResult<bool>;
}
```
The `interface` attribute and `WipType` derive are re-exported by the facade;
users do not import `wip-interface-macros` or generated private support symbols.
The generated `MessengerDefinition` constructs an `InterfaceDescriptor`,
decodes named arguments, encodes results, validates both boundaries, and
provides typed dispatch for any `T: Messenger`.
### Supported Rust syntax
A supported interface is a public, non-generic trait containing methods with:
- exactly an immutable `&self` receiver;
- simple named, owned parameters;
- an explicit `wip::OperationResult<T>` return;
- `()` only as the application return when no value is produced; and
- direct `Option<T>` only for an omittable parameter.
`WipType` derives support named-field structs, all-unit enums, and unions whose
cases may be unit variants or variants containing exactly one unnamed payload.
The macros reject private,
generic, inherited, unsafe, auto, or associated-item traits; const, async,
unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
borrowed/custom-lifetime values; tuple/unit/generic structs; Rust unions;
named-field/multi-field enum variants; explicit discriminants; nested `Option`; and
`Option` in returns, collections, entries, or union payloads. These diagnostics
are compile-fail tested under `crates/wip-interface/tests/ui`.
### Rust type mapping
| Rust | Protocol |
| --- | --- |
| `()` | unit / `Value::Unit` |
| `bool` | boolean |
| integer primitives | JavaScript-lossless integer |
| `f32`, `f64` | finite number |
| `String` | string |
| `wip::Bytes` | bytes |
| `wip::JsonValue` | JSON interpreted over the schema-neutral `Value` tree |
| `wip::Entry` | canonical absolute Worldspace path encoded as a string |
| `Vec<T>` | list |
| named-field `#[derive(wip::WipType)]` struct | named record |
| all-unit `#[derive(wip::WipType)]` enum | named enum encoded as a string |
| mixed unit/newtype or all-newtype enum | named union encoded as a discriminator record |
`Option<T>` means that a direct DTO field or operation parameter may be
omitted; it is not protocol null. JSON null remains available inside
`wip::JsonValue`.
#### Migration from the pre-canonical value API
The old generic `wip::Entry<K, V>` represented an application key/value pair
and is no longer available. Use `wip::Entry::new("/canonical/path")` for a
Worldspace entry path and place any associated application data in a record.
`Entry` encodes as `Value::String` and validates the canonical absolute path.
The semantic `Value::Json`, `Value::Entry`, `Value::Enum`, and `Value::Union`
variants have also been removed. JSON recursively uses `Unit`, primitive,
`List`, and `Record` values and rejects `Bytes`; enums use `String`; unions use
a `Record` containing `$case` and, for payload-bearing cases, `value`. Unit
operation results are represented explicitly as `Value::Unit`.
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
section documents the return declaration; text before that section documents
the operation itself.
## Host publication and dispatch
Applications use `wip-host` to register generated definitions and explicitly
choose the ordered interface set for each object publication:
```rust,ignore
let mut interfaces = wip_host::InterfaceRegistry::new();
let messenger = interfaces.register(MessengerDefinition, None)?;
let published = wip_host::PublishedObject::new(request_scoped_object)
.expose(&messenger)?;
let protocol_object = published.protocol_object();
```
`expose` compiles only when the object implements the generated definition's
interface trait. Implementing a trait does not expose it automatically, empty
interface sets are valid, insertion order is preserved, and duplicate
references are rejected. Registry references are opaque and remain outside the
descriptor; generated descriptors contain neither those references nor Rust
trait identity.
Dispatch is qualified by interface reference and operation name and targets a
canonical Worldspace path. An `ObjectProvider` validates that path before
resolution, maps malformed paths to `InvalidRequest`, then resolves a valid path
exactly once inside `with_object`; the host checks the supplied object validator,
current interface membership, interface validator, descriptor operation,
operation-specific object-validator policy, arguments, and authorization in
canonical precedence. Path and children remain provider resolution context and
are never projected by `WipObject`; host-private fields and backend handles are
also excluded.
Application domain failures belong in a derived result union and are returned
through `Ok`. `wip::HostError` is reserved for runtime/backend failures. A
structurally malformed call is `InvalidRequest`; only argument values checked
after the current Interface Descriptor is fixed are `InvalidArguments`. A Host
must never return a wire `InvalidResult`: Clients keep invalid Object,
Descriptor, operation-result, and error responses as local `InvalidResponse`
failures, while unsupported descriptor formats remain local
`UnsupportedDescriptorFormat` failures.
For operation calls, `Internal` and `ResourceLimitExceeded` guarantee that the
operation did not run or that its effects were rolled back.
`OperationOutcomeUnknown` is the only protocol code that makes no such
guarantee, so Clients must not automatically retry it. The current host API maps
implementation failures and invalid post-execution results conservatively to
`OperationOutcomeUnknown`.
Providers remain responsible for backend atomicity. Enter a transaction, lock,
stable-handle scope, or conditional-update primitive before invoking the
`with_object` callback, and retain it until the callback returns. Mutable
operations must make validator comparison and backend commit atomic and return a
validator for the committed state. The runtime never validates one object and
then resolves a second snapshot, but it cannot make an arbitrary external
backend atomic by itself.
## Validation
Enter the dev shell and run the acceptance commands exactly:
```console
nix develop
cargo fmt --all -- --check
cargo check --workspace --all-targets
cargo test --workspace --all-targets
cargo test --workspace --doc
cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps
cargo run --package wip-public-api-example
git diff --check
```
`cargo test --workspace --all-targets` includes the public-only conformance
consumer, runtime failure tests, and `trybuild` compile-fail suites. The separate
doctest, rustdoc, executable, and whitespace checks are all required acceptance
steps.
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "wip-host"
version = "0.1.0"
edition = "2024"
description = "Host-side object publication and operation dispatch for WIP"
license = "MIT OR Apache-2.0"
[dependencies]
wip-interface = { path = "../wip-interface" }
wip-protocol = { path = "../wip-protocol" }
[dev-dependencies]
trybuild = "1"
+719
View File
@@ -0,0 +1,719 @@
//! Host-side publication and operation dispatch for Web Interface Protocol objects.
//!
//! # Responsibility boundaries
//!
//! [`InterfaceRegistry::register`] validates and freezes a generated interface
//! descriptor, assigns an opaque [`InterfaceRef`], and leaves that reference
//! outside the descriptor. [`PublishedObject::expose`] explicitly combines a
//! request-scoped Rust object with a registered interface; its
//! [`InterfaceImplementation`] bound proves at compile time that the object
//! implements the interface. Implementing a Rust trait alone never publishes it,
//! and a publication with no interfaces is valid.
//!
//! [`ObjectProvider::call_operation`] resolves `target.path` exactly once and
//! keeps the resulting object, interface membership, descriptor, implementation,
//! and backend target fixed within the provider's [`ObjectProvider::with_object`]
//! callback. Dispatch is qualified by `(interface reference, operation name)`.
//! The same frozen operation declaration validates both arguments and results.
//!
//! A provider is responsible for entering a backend transaction, lock,
//! stable-handle scope, or conditional-update primitive before invoking the
//! callback and retaining it until the callback returns. The runtime does not
//! reopen the path or select another implementation after checking validators,
//! but cannot make an arbitrary external backend atomic on its own. Mutable
//! operations must make object-validator comparison and backend commit atomic;
//! the validator returned after dispatch must describe the committed state.
#![deny(missing_docs)]
use std::any::TypeId;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use wip_interface::DispatchError;
pub use wip_interface::{InterfaceDefinition, InterfaceImplementation};
pub use wip_protocol;
pub use wip_protocol::{
CallOperationRequest as CallRequest, CallOperationResponse as CallResult, InterfaceTarget,
Target,
};
use wip_protocol::{
FetchInterfaceResponse, InterfaceDescriptor, Object, ProtocolError, ProtocolErrorCode,
ValidationError, Value,
};
/// Opaque bytes used as a conditional execution precondition.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Validator(Vec<u8>);
impl Validator {
/// Creates a validator without assigning meaning to its bytes.
#[must_use]
pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
Self(bytes.into())
}
/// Returns the opaque bytes for transport encoding or comparison.
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
/// Opaque host-assigned reference to one registered interface artifact.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InterfaceRef(String);
impl InterfaceRef {
/// Returns the opaque reference for a protocol transport.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
/// One atomic observation of an interface reference, descriptor, and validator.
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceObservation {
/// Opaque reference selected by published objects and operation calls.
pub reference: InterfaceRef,
/// Canonical descriptor frozen when the interface was registered.
pub descriptor: InterfaceDescriptor,
/// Optional validator. Its presence makes it a required call precondition.
pub validator: Option<Validator>,
}
impl InterfaceObservation {
/// Converts this host observation to the canonical protocol response.
#[must_use]
pub fn protocol_response(&self) -> FetchInterfaceResponse {
FetchInterfaceResponse {
interface: self.reference.0.clone(),
descriptor: self.descriptor.clone(),
validator: self.validator.as_ref().map(|validator| validator.0.clone()),
}
}
}
#[derive(Debug)]
struct InterfaceArtifact {
reference: InterfaceRef,
descriptor: InterfaceDescriptor,
validator: Option<Validator>,
}
/// A typed registration token for a generated interface definition.
///
/// Tokens can be reused by any number of request-scoped objects. They expose an
/// opaque reference, not the Rust type name or an address.
pub struct RegisteredInterface<D> {
artifact: Arc<InterfaceArtifact>,
definition: PhantomData<fn() -> D>,
}
impl<D> Clone for RegisteredInterface<D> {
fn clone(&self) -> Self {
Self {
artifact: Arc::clone(&self.artifact),
definition: PhantomData,
}
}
}
impl<D> RegisteredInterface<D> {
/// Returns the opaque protocol reference assigned by the registry.
#[must_use]
pub fn reference(&self) -> &InterfaceRef {
&self.artifact.reference
}
}
/// Registry of validated, immutable interface artifacts.
///
/// Generated descriptors are never rewritten to contain their assigned
/// references. A validator-free artifact is immutable for the lifetime of its
/// reference. A validator-bearing artifact requires that exact validator on a
/// call. Re-registering a definition is rejected rather than silently changing
/// the observation associated with an existing reference.
#[derive(Debug)]
pub struct InterfaceRegistry {
namespace: u64,
next_reference: u64,
definitions: HashSet<TypeId>,
artifacts: HashMap<InterfaceRef, Arc<InterfaceArtifact>>,
}
static NEXT_REGISTRY_NAMESPACE: AtomicU64 = AtomicU64::new(1);
impl Default for InterfaceRegistry {
fn default() -> Self {
Self {
namespace: NEXT_REGISTRY_NAMESPACE.fetch_add(1, Ordering::Relaxed),
next_reference: 0,
definitions: HashSet::new(),
artifacts: HashMap::new(),
}
}
}
impl InterfaceRegistry {
/// Creates an empty interface registry.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Registers and freezes one generated interface definition.
pub fn register<D>(
&mut self,
_definition: D,
validator: Option<Validator>,
) -> Result<RegisteredInterface<D>, RegistrationError>
where
D: InterfaceDefinition + 'static,
{
let definition = TypeId::of::<D>();
if self.definitions.contains(&definition) {
return Err(RegistrationError::AlreadyRegistered);
}
let descriptor = D::descriptor();
descriptor
.validate()
.map_err(RegistrationError::InvalidDescriptor)?;
let reference = InterfaceRef(format!(
"wip-interface:{}:{}",
self.namespace, self.next_reference
));
self.next_reference = self
.next_reference
.checked_add(1)
.ok_or(RegistrationError::ReferenceSpaceExhausted)?;
let artifact = Arc::new(InterfaceArtifact {
reference: reference.clone(),
descriptor,
validator,
});
self.definitions.insert(definition);
self.artifacts.insert(reference, Arc::clone(&artifact));
Ok(RegisteredInterface {
artifact,
definition: PhantomData,
})
}
/// Resolves a transport-provided opaque reference string in this registry.
#[must_use]
pub fn resolve(&self, reference: &str) -> Option<InterfaceRef> {
let reference = InterfaceRef(reference.to_owned());
self.artifacts.contains_key(&reference).then_some(reference)
}
/// Observes a registered interface by its host-side reference.
#[must_use]
pub fn observe(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
self.artifacts.get(reference).map(Self::observation)
}
/// Implements canonical `fetch_interface` semantics for an opaque reference.
///
/// Unknown and currently unpublished references map to `InterfaceNotFound`,
/// not object membership errors or authorization failures.
pub fn fetch_interface(&self, reference: &str) -> Result<InterfaceObservation, ProtocolError> {
let reference = InterfaceRef(reference.to_owned());
self.artifacts
.get(&reference)
.map(Self::observation)
.ok_or_else(|| ProtocolError {
code: ProtocolErrorCode::InterfaceNotFound,
message: "interface reference is not currently published".into(),
})
}
fn observation(artifact: &Arc<InterfaceArtifact>) -> InterfaceObservation {
InterfaceObservation {
reference: artifact.reference.clone(),
descriptor: artifact.descriptor.clone(),
validator: artifact.validator.clone(),
}
}
}
/// Failure while registering a generated interface definition.
#[derive(Debug)]
pub enum RegistrationError {
/// The same generated definition was already assigned a reference.
AlreadyRegistered,
/// The generated descriptor is structurally invalid.
InvalidDescriptor(ValidationError),
/// The registry cannot assign another opaque reference.
ReferenceSpaceExhausted,
}
impl Display for RegistrationError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::AlreadyRegistered => {
formatter.write_str("interface definition already registered")
}
Self::InvalidDescriptor(error) => {
write!(formatter, "invalid interface descriptor: {error}")
}
Self::ReferenceSpaceExhausted => {
formatter.write_str("interface reference space exhausted")
}
}
}
}
impl Error for RegistrationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InvalidDescriptor(error) => Some(error),
Self::AlreadyRegistered | Self::ReferenceSpaceExhausted => None,
}
}
}
/// Public metadata and conditional-execution policy for a host-private object.
///
/// Only values returned by this trait are projected into protocol metadata.
/// Paths, children, backend handles, credentials, and resolution state are not
/// part of this API and therefore cannot be serialized into [`Object`].
pub trait WipObject {
/// Returns the public path-segment name of this object.
fn name(&self) -> &str;
/// Returns a short public description, if one is available.
fn description(&self) -> Option<&str> {
None
}
/// Returns optional opaque identity within the client-facing Worldspace.
fn reference(&self) -> Option<&str> {
None
}
/// Returns the current opaque object validator, if any.
fn validator(&self) -> Option<&Validator> {
None
}
/// Whether this specific qualified operation requires an object validator.
///
/// This hook is evaluated only after membership, interface validators, and
/// operation existence have been checked, preserving canonical precedence.
fn requires_validator(&self, _interface: &InterfaceRef, _operation: &str) -> bool {
false
}
}
type DispatchFn<T> = fn(&T, &str, BTreeMap<String, Value>) -> Result<Value, DispatchError>;
struct BoundInterface<T> {
artifact: Arc<InterfaceArtifact>,
dispatch: DispatchFn<T>,
}
/// A host-private object instance combined with an explicit ordered interface set.
///
/// The instance is owned by this value and can therefore be request-scoped. No
/// global object registry is required. Worldspace paths remain provider context
/// and are deliberately absent from the publication.
pub struct PublishedObject<T: WipObject> {
implementation: T,
interfaces: Vec<BoundInterface<T>>,
}
impl<T: WipObject> PublishedObject<T> {
/// Starts a publication with no exposed interfaces.
#[must_use]
pub fn new(implementation: T) -> Self {
Self {
implementation,
interfaces: Vec::new(),
}
}
/// Explicitly exposes a registered generated interface in insertion order.
///
/// The `InterfaceImplementation<T>` bound is generated only when `T`
/// implements the corresponding Rust interface trait. Duplicate opaque
/// references are rejected.
pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
where
D: InterfaceImplementation<T>,
{
if self
.interfaces
.iter()
.any(|bound| bound.artifact.reference == interface.artifact.reference)
{
return Err(PublicationError::DuplicateInterface(
interface.artifact.reference.clone(),
));
}
self.interfaces.push(BoundInterface {
artifact: Arc::clone(&interface.artifact),
dispatch: D::dispatch,
});
Ok(self)
}
/// Returns the host-private implementation without projecting its fields.
#[must_use]
pub fn implementation(&self) -> &T {
&self.implementation
}
/// Builds canonical protocol object metadata in interface insertion order.
///
/// The observation contains no path, children, descriptor, backend handle,
/// credential, or provider resolution state.
#[must_use]
pub fn protocol_object(&self) -> Object {
Object {
name: self.implementation.name().to_owned(),
description: self.implementation.description().map(str::to_owned),
interfaces: self
.interfaces
.iter()
.map(|bound| bound.artifact.reference.0.clone())
.collect(),
r#ref: self.implementation.reference().map(str::to_owned),
validator: self
.implementation
.validator()
.map(|validator| validator.0.clone()),
}
}
fn dispatch_resolved(
&self,
request: CallRequest,
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
) -> Result<CallResult, CallError> {
let current_object_validator = self.implementation.validator();
if let Some(supplied) = request.target.validator.as_deref()
&& current_object_validator.map(Validator::as_bytes) != Some(supplied)
{
return Err(CallError::new(
CallErrorKind::ValidatorMismatch,
"object validator does not match current object state",
));
}
let Some(bound) = self.interfaces.iter().find(|bound| {
bound.artifact.reference.as_str() == request.interface.reference.as_str()
}) else {
return Err(CallError::new(
CallErrorKind::InterfaceMismatch,
"interface is not a member of the current object publication",
));
};
match (
bound.artifact.validator.as_ref(),
request.interface.validator.as_deref(),
) {
(Some(_), None) => {
return Err(CallError::new(
CallErrorKind::InterfaceValidatorRequired,
"registered interface requires a validator",
));
}
(expected, Some(actual)) if expected.map(Validator::as_bytes) != Some(actual) => {
return Err(CallError::new(
CallErrorKind::InterfaceValidatorMismatch,
"interface validator does not match the registered descriptor",
));
}
_ => {}
}
if !bound
.artifact
.descriptor
.operations
.iter()
.any(|operation| operation.name == request.operation)
{
return Err(CallError::new(
CallErrorKind::OperationNotFound,
format!("operation `{}` is not declared", request.operation),
));
}
if request.target.validator.is_none()
&& self
.implementation
.requires_validator(&bound.artifact.reference, &request.operation)
{
return Err(CallError::new(
CallErrorKind::ValidatorRequired,
"this operation requires an object validator",
));
}
bound
.artifact
.descriptor
.validate_arguments(&request.operation, &request.arguments)
.map_err(|error| CallError::new(CallErrorKind::InvalidArguments, error.to_string()))?;
if !authorize(
&self.implementation,
&bound.artifact.reference,
&request.operation,
) {
return Err(CallError::new(
CallErrorKind::PermissionDenied,
"operation is not permitted for this caller",
));
}
let value = (bound.dispatch)(&self.implementation, &request.operation, request.arguments)
.map_err(CallError::from_dispatch)?;
bound
.artifact
.descriptor
.validate_result(&request.operation, &value)
.map_err(|error| CallError::new(CallErrorKind::InvalidResult, error.to_string()))?;
Ok(CallResult {
result: value,
validator: self
.implementation
.validator()
.map(|validator| validator.0.clone()),
})
}
/// Consumes the publication and returns its host-private implementation.
#[must_use]
pub fn into_inner(self) -> T {
self.implementation
}
}
/// A request-scoped Worldspace resolver and execution boundary.
///
/// `with_object` must resolve the current object at `path` exactly once and pass
/// a publication that pins its current interface set, implementations, and
/// backend target for the duration of `operation`. Implementations may hold a
/// transaction or lock around the callback. Returning `None` means the path is
/// not published to the caller. The borrowed publication cannot escape the
/// callback, so the default call path cannot outlive that provider boundary.
pub trait ObjectProvider {
/// Host-private object type produced by this provider.
type Object: WipObject;
/// Runs an operation against the single object snapshot resolved at `path`.
fn with_object<R>(
&self,
path: &str,
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
) -> Option<R>;
/// Decides whether a declared operation may execute for the current caller.
///
/// The hook runs after all validators, membership, operation lookup, and
/// argument validation, but before implementation code. Returning `false`
/// exposes the operation while producing `PermissionDenied`.
fn authorize(
&self,
_path: &str,
_object: &Self::Object,
_interface: &InterfaceRef,
_operation: &str,
) -> bool {
true
}
/// Fetches the canonical object projection currently published at `path`.
fn fetch(&self, path: &str) -> Result<Object, CallError> {
wip_protocol::validate_path(path)
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
self.with_object(path, PublishedObject::protocol_object)
.ok_or_else(|| CallError::new(CallErrorKind::NotFound, "target path is not published"))
.and_then(|object| {
object
.validate_at_path(path)
.map_err(|error| CallError::new(CallErrorKind::Internal, error.to_string()))?;
Ok(object)
})
}
/// Resolves and executes a canonical path-targeted operation request.
///
/// Structural path validation precedes provider resolution. For a valid
/// request, failure checks follow the exact canonical precedence: path,
/// supplied object validator mismatch, membership, interface validator
/// requirement and mismatch, operation existence, object validator
/// requirement, arguments, then authorization. No failed precondition
/// invokes the provider callback or typed implementation.
fn call_operation(&self, request: CallRequest) -> Result<CallResult, CallError> {
wip_protocol::validate_path(&request.target.path)
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
let path = request.target.path.clone();
self.with_object(&path, |publication| {
publication.dispatch_resolved(request, |object, interface, operation| {
self.authorize(&path, object, interface, operation)
})
})
.ok_or_else(|| CallError::new(CallErrorKind::NotFound, "target path is not published"))?
}
}
/// Failure to construct an explicit object publication.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PublicationError {
/// The same opaque interface reference was exposed more than once.
DuplicateInterface(InterfaceRef),
}
impl Display for PublicationError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateInterface(reference) => write!(
formatter,
"interface `{}` is already exposed by this object",
reference.as_str()
),
}
}
}
impl Error for PublicationError {}
/// Stable host dispatch failure kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallErrorKind {
/// The request is structurally invalid.
InvalidRequest,
/// The target path is not currently published.
NotFound,
/// The selected interface is not exposed by the current object.
InterfaceMismatch,
/// The operation is absent from the selected descriptor.
OperationNotFound,
/// Supplied named values do not satisfy the operation declaration.
InvalidArguments,
/// The Host constructed an invalid response before operation execution.
Internal,
/// The encoded implementation result violates its declaration after execution.
InvalidResult,
/// This operation requires a validator and the call omitted it.
ValidatorRequired,
/// The supplied object validator is stale or belongs to another object.
ValidatorMismatch,
/// The selected mutable interface requires its observed validator.
InterfaceValidatorRequired,
/// The supplied interface validator does not identify the current descriptor.
InterfaceValidatorMismatch,
/// The operation is declared but not authorized for the caller.
PermissionDenied,
/// The typed implementation reported a host/backend failure.
Implementation,
}
/// A dispatch failure with a stable kind and non-normative diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallError {
kind: CallErrorKind,
message: String,
}
impl CallError {
fn new(kind: CallErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
fn from_dispatch(error: DispatchError) -> Self {
match error {
DispatchError::UnknownOperation(operation) => Self::new(
CallErrorKind::OperationNotFound,
format!("operation `{operation}` is not declared"),
),
DispatchError::InvalidArguments(error) => {
Self::new(CallErrorKind::InvalidArguments, error.to_string())
}
DispatchError::Decode(error) => {
Self::new(CallErrorKind::InvalidArguments, error.to_string())
}
DispatchError::Host(error) => {
Self::new(CallErrorKind::Implementation, error.to_string())
}
DispatchError::Encode(error) => {
Self::new(CallErrorKind::InvalidResult, error.to_string())
}
DispatchError::InvalidResult(error) => {
Self::new(CallErrorKind::InvalidResult, error.to_string())
}
}
}
/// Returns the stable failure kind.
#[must_use]
pub fn kind(&self) -> CallErrorKind {
self.kind
}
/// Returns the human-readable diagnostic.
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
/// Maps this host failure to the canonical protocol error taxonomy.
#[must_use]
pub fn protocol_error(&self) -> ProtocolError {
let code = match self.kind {
CallErrorKind::InvalidRequest => ProtocolErrorCode::InvalidRequest,
CallErrorKind::NotFound => ProtocolErrorCode::NotFound,
CallErrorKind::InterfaceMismatch => ProtocolErrorCode::InterfaceMismatch,
CallErrorKind::OperationNotFound => ProtocolErrorCode::OperationNotFound,
CallErrorKind::InvalidArguments => ProtocolErrorCode::InvalidArguments,
CallErrorKind::Internal => ProtocolErrorCode::Internal,
CallErrorKind::InvalidResult | CallErrorKind::Implementation => {
ProtocolErrorCode::OperationOutcomeUnknown
}
CallErrorKind::ValidatorRequired => ProtocolErrorCode::ValidatorRequired,
CallErrorKind::ValidatorMismatch => ProtocolErrorCode::ValidatorMismatch,
CallErrorKind::InterfaceValidatorRequired => {
ProtocolErrorCode::InterfaceValidatorRequired
}
CallErrorKind::InterfaceValidatorMismatch => {
ProtocolErrorCode::InterfaceValidatorMismatch
}
CallErrorKind::PermissionDenied => ProtocolErrorCode::PermissionDenied,
};
ProtocolError {
code,
message: self.message.clone(),
}
}
}
impl Display for CallError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(
formatter,
"host dispatch failed ({:?}): {}",
self.kind, self.message
)
}
}
impl Error for CallError {}
+5
View File
@@ -0,0 +1,5 @@
#[test]
fn rejects_exposing_an_unimplemented_interface() {
let tests = trybuild::TestCases::new();
tests.compile_fail("tests/ui/unimplemented_interface.rs");
}
+668
View File
@@ -0,0 +1,668 @@
use std::cell::Cell;
use std::collections::BTreeMap;
use std::rc::Rc;
use wip_host::{
CallError, CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget,
ObjectProvider, PublishedObject, RegisteredInterface, Target, Validator, WipObject,
};
use wip_interface::{
CodecError, HostError, OperationResult, TypeDeclaration, TypeExpr, Value, WipType, interface,
};
use wip_protocol::ProtocolErrorCode;
#[interface]
pub trait Reader {
/// Returns the reader-qualified label.
fn label(&self) -> OperationResult<String>;
/// Adds two integers.
fn add(&self, left: i64, right: i64) -> OperationResult<i64>;
/// Reports a backend failure.
fn fail(&self) -> OperationResult<String>;
}
#[interface]
pub trait Writer {
/// Returns the writer-qualified label.
fn label(&self) -> OperationResult<String>;
}
#[interface]
pub trait Hidden {
/// Returns a hidden value.
fn hidden(&self) -> OperationResult<String>;
}
#[interface]
pub trait Broken {
/// Returns a deliberately invalid encoded value.
fn broken(&self) -> OperationResult<BadValue>;
}
#[derive(Debug)]
pub struct BadValue;
impl WipType for BadValue {
fn type_expr() -> TypeExpr {
TypeExpr::Integer
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::String("not an integer".into()))
}
fn decode(_: Value) -> Result<Self, CodecError> {
Ok(Self)
}
}
struct Document {
name: String,
description: Option<String>,
reference: Option<String>,
validator: Option<Validator>,
require_validator: bool,
calls: Rc<Cell<usize>>,
private_backend_handle: String,
}
impl Document {
fn open(name: &str, reference: Option<&str>, calls: Rc<Cell<usize>>) -> Self {
Self {
name: name.into(),
description: Some("public document".into()),
reference: reference.map(str::to_owned),
validator: None,
require_validator: false,
calls,
private_backend_handle: "/private/backend/path".into(),
}
}
fn strict(name: &str, reference: &str, validator: &[u8], calls: Rc<Cell<usize>>) -> Self {
Self {
name: name.into(),
description: Some("public document".into()),
reference: Some(reference.into()),
validator: Some(Validator::new(validator)),
require_validator: true,
calls,
private_backend_handle: "secret-handle".into(),
}
}
fn record_call(&self) {
self.calls.set(self.calls.get() + 1);
}
}
impl WipObject for Document {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> Option<&str> {
self.description.as_deref()
}
fn reference(&self) -> Option<&str> {
self.reference.as_deref()
}
fn validator(&self) -> Option<&Validator> {
self.validator.as_ref()
}
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
self.require_validator
}
}
impl Reader for Document {
fn label(&self) -> OperationResult<String> {
self.record_call();
Ok("reader".into())
}
fn add(&self, left: i64, right: i64) -> OperationResult<i64> {
self.record_call();
Ok(left + right)
}
fn fail(&self) -> OperationResult<String> {
self.record_call();
Err(HostError::new("backend unavailable"))
}
}
impl Writer for Document {
fn label(&self) -> OperationResult<String> {
self.record_call();
Ok("writer".into())
}
}
impl Hidden for Document {
fn hidden(&self) -> OperationResult<String> {
self.record_call();
Ok("hidden".into())
}
}
impl Broken for Document {
fn broken(&self) -> OperationResult<BadValue> {
self.record_call();
Ok(BadValue)
}
}
struct TestProvider {
reader: RegisteredInterface<ReaderDefinition>,
writer: RegisteredInterface<WriterDefinition>,
broken: RegisteredInterface<BrokenDefinition>,
calls: Rc<Cell<usize>>,
resolutions: Cell<usize>,
authorization_checks: Cell<usize>,
deny: Cell<bool>,
switched: Cell<bool>,
}
impl TestProvider {
fn new(
reader: RegisteredInterface<ReaderDefinition>,
writer: RegisteredInterface<WriterDefinition>,
broken: RegisteredInterface<BrokenDefinition>,
) -> Self {
Self {
reader,
writer,
broken,
calls: Rc::new(Cell::new(0)),
resolutions: Cell::new(0),
authorization_checks: Cell::new(0),
deny: Cell::new(false),
switched: Cell::new(false),
}
}
}
impl ObjectProvider for TestProvider {
type Object = Document;
fn with_object<R>(
&self,
path: &str,
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
) -> Option<R> {
self.resolutions.set(self.resolutions.get() + 1);
let (document, interfaces) = match path {
"/document" => (
Document::strict(
"document",
"document-ref",
b"object-v1",
Rc::clone(&self.calls),
),
2,
),
"/open" => (
Document::open("open", Some("open-ref"), Rc::clone(&self.calls)),
2,
),
"/left/document" | "/right/document" => (
Document::strict(
"document",
"shared-ref",
b"shared-v1",
Rc::clone(&self.calls),
),
2,
),
"/switch" => {
let switched = self.switched.replace(true);
let (reference, validator) = if switched {
("second-ref", b"second".as_slice())
} else {
("first-ref", b"first".as_slice())
};
(
Document::strict("switch", reference, validator, Rc::clone(&self.calls)),
2,
)
}
"/empty" => (Document::open("empty", None, Rc::clone(&self.calls)), 0),
"/invalid-object" => (
Document::open("wrong-name", None, Rc::clone(&self.calls)),
0,
),
"/broken" => (
Document::open("broken", Some("broken-ref"), Rc::clone(&self.calls)),
3,
),
_ => return None,
};
let publication = PublishedObject::new(document);
let publication = match interfaces {
0 => publication,
2 => publication
.expose(&self.writer)
.unwrap()
.expose(&self.reader)
.unwrap(),
3 => publication.expose(&self.broken).unwrap(),
_ => unreachable!(),
};
Some(operation(&publication))
}
fn authorize(&self, _: &str, _: &Document, _: &InterfaceRef, _: &str) -> bool {
self.authorization_checks
.set(self.authorization_checks.get() + 1);
!self.deny.get()
}
}
fn registry_and_provider() -> (
InterfaceRegistry,
TestProvider,
RegisteredInterface<HiddenDefinition>,
) {
let mut registry = InterfaceRegistry::new();
let reader = registry
.register(ReaderDefinition, Some(Validator::new(b"schema-v1")))
.unwrap();
let writer = registry.register(WriterDefinition, None).unwrap();
let hidden = registry.register(HiddenDefinition, None).unwrap();
let broken = registry.register(BrokenDefinition, None).unwrap();
let provider = TestProvider::new(reader, writer, broken);
(registry, provider, hidden)
}
fn request(
path: &str,
object_validator: Option<&[u8]>,
reference: &InterfaceRef,
interface_validator: Option<&[u8]>,
operation: &str,
arguments: BTreeMap<String, Value>,
) -> CallRequest {
CallRequest {
target: Target {
path: path.into(),
validator: object_validator.map(<[u8]>::to_vec),
},
interface: InterfaceTarget {
reference: reference.as_str().to_owned(),
validator: interface_validator.map(<[u8]>::to_vec),
},
operation: operation.into(),
arguments,
}
}
fn assert_failure(error: CallError, kind: CallErrorKind, code: ProtocolErrorCode) {
assert_eq!(error.kind(), kind);
assert_eq!(error.protocol_error().code, code);
}
#[test]
fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor() {
let (registry, provider, _) = registry_and_provider();
let reference = provider.reader.reference();
assert_ne!(reference.as_str(), "Reader");
let observation = registry.fetch_interface(reference.as_str()).unwrap();
assert_eq!(observation.reference, *reference);
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
let response = observation.protocol_response();
assert_eq!(response.interface, reference.as_str());
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
response.descriptor.validate().unwrap();
let error = registry.fetch_interface("unknown").unwrap_err();
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
}
#[test]
fn canonical_object_projection_supports_optional_metadata_and_ordered_sets() {
let (_, provider, _) = registry_and_provider();
let object = provider.fetch("/document").unwrap();
assert_eq!(object.name, "document");
assert_eq!(object.description.as_deref(), Some("public document"));
assert_eq!(object.r#ref.as_deref(), Some("document-ref"));
assert_eq!(object.validator.as_deref(), Some(b"object-v1".as_slice()));
assert_eq!(
object.interfaces,
vec![
provider.writer.reference().as_str().to_owned(),
provider.reader.reference().as_str().to_owned(),
]
);
assert!(!format!("{object:?}").contains("secret-handle"));
assert!(!format!("{object:?}").contains("/document"));
let empty = provider.fetch("/empty").unwrap();
assert!(empty.interfaces.is_empty());
assert_eq!(empty.r#ref, None);
assert_eq!(empty.validator, None);
}
#[test]
fn duplicate_exposure_is_rejected_and_private_state_is_not_projected() {
let (_, provider, _) = registry_and_provider();
let publication = PublishedObject::new(Document::open(
"duplicate",
None,
Rc::clone(&provider.calls),
))
.expose(&provider.reader)
.unwrap();
assert_eq!(
publication.implementation().private_backend_handle,
"/private/backend/path"
);
let error = match publication.expose(&provider.reader) {
Ok(_) => panic!("duplicate exposure unexpectedly succeeded"),
Err(error) => error,
};
assert!(
error
.to_string()
.contains(provider.reader.reference().as_str())
);
}
#[test]
fn paths_are_resolution_context_not_object_identity() {
let (_, provider, _) = registry_and_provider();
let left = provider.fetch("/left/document").unwrap();
let right = provider.fetch("/right/document").unwrap();
assert_eq!(left, right);
assert_eq!(left.r#ref.as_deref(), Some("shared-ref"));
let first = provider.fetch("/switch").unwrap();
let second = provider.fetch("/switch").unwrap();
assert_ne!(first.r#ref, second.r#ref);
assert_ne!(first.validator, second.validator);
}
#[test]
fn path_dispatch_is_interface_qualified_and_resolves_once_per_call() {
let (_, provider, _) = registry_and_provider();
let before = provider.resolutions.get();
let writer = provider
.call_operation(request(
"/open",
None,
provider.writer.reference(),
None,
"label",
BTreeMap::new(),
))
.unwrap();
let reader = provider
.call_operation(request(
"/open",
None,
provider.reader.reference(),
Some(b"schema-v1"),
"label",
BTreeMap::new(),
))
.unwrap();
let strict = provider
.call_operation(request(
"/document",
Some(b"object-v1"),
provider.reader.reference(),
Some(b"schema-v1"),
"label",
BTreeMap::new(),
))
.unwrap();
assert_eq!(writer.result, Value::String("writer".into()));
assert_eq!(reader.result, Value::String("reader".into()));
assert_eq!(strict.result, Value::String("reader".into()));
assert_eq!(strict.validator.as_deref(), Some(b"object-v1".as_slice()));
assert_eq!(provider.resolutions.get() - before, 3);
assert_eq!(provider.calls.get(), 3);
}
#[test]
fn call_failures_follow_canonical_precedence_without_execution() {
let (_, provider, hidden) = registry_and_provider();
let resolutions = provider.resolutions.get();
for invalid_path in [
"relative",
"/trailing/",
"/double//segment",
"/dot/./segment",
"/parent/../segment",
] {
assert_failure(
provider
.call_operation(request(
invalid_path,
Some(b"stale"),
hidden.reference(),
Some(b"stale"),
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InvalidRequest,
ProtocolErrorCode::InvalidRequest,
);
}
assert_eq!(provider.resolutions.get(), resolutions);
assert_failure(
provider.fetch("/invalid/").unwrap_err(),
CallErrorKind::InvalidRequest,
ProtocolErrorCode::InvalidRequest,
);
assert_eq!(provider.resolutions.get(), resolutions);
assert_failure(
provider
.call_operation(request(
"/missing",
Some(b"stale"),
hidden.reference(),
Some(b"stale"),
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::NotFound,
ProtocolErrorCode::NotFound,
);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"stale"),
hidden.reference(),
None,
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::ValidatorMismatch,
ProtocolErrorCode::ValidatorMismatch,
);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"object-v1"),
hidden.reference(),
None,
"hidden",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InterfaceMismatch,
ProtocolErrorCode::InterfaceMismatch,
);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"object-v1"),
provider.reader.reference(),
None,
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InterfaceValidatorRequired,
ProtocolErrorCode::InterfaceValidatorRequired,
);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"object-v1"),
provider.reader.reference(),
Some(b"stale-schema"),
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InterfaceValidatorMismatch,
ProtocolErrorCode::InterfaceValidatorMismatch,
);
assert_failure(
provider
.call_operation(request(
"/document",
None,
provider.reader.reference(),
Some(b"schema-v1"),
"missing",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::OperationNotFound,
ProtocolErrorCode::OperationNotFound,
);
assert_failure(
provider
.call_operation(request(
"/document",
None,
provider.reader.reference(),
Some(b"schema-v1"),
"add",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::ValidatorRequired,
ProtocolErrorCode::ValidatorRequired,
);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"object-v1"),
provider.reader.reference(),
Some(b"schema-v1"),
"add",
BTreeMap::from([("left".into(), Value::String("wrong".into()))]),
))
.unwrap_err(),
CallErrorKind::InvalidArguments,
ProtocolErrorCode::InvalidArguments,
);
provider.deny.set(true);
assert_failure(
provider
.call_operation(request(
"/document",
Some(b"object-v1"),
provider.reader.reference(),
Some(b"schema-v1"),
"label",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::PermissionDenied,
ProtocolErrorCode::PermissionDenied,
);
assert_eq!(provider.authorization_checks.get(), 1);
assert_eq!(provider.calls.get(), 0);
}
#[test]
fn immutable_interface_rejects_a_supplied_validator() {
let (_, provider, _) = registry_and_provider();
assert_failure(
provider
.call_operation(request(
"/open",
None,
provider.writer.reference(),
Some(b"unexpected"),
"label",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InterfaceValidatorMismatch,
ProtocolErrorCode::InterfaceValidatorMismatch,
);
assert_eq!(provider.calls.get(), 0);
}
#[test]
fn invalid_host_responses_and_uncertain_operation_failures_use_canonical_codes() {
let (_, provider, _) = registry_and_provider();
assert_failure(
provider.fetch("/invalid-object").unwrap_err(),
CallErrorKind::Internal,
ProtocolErrorCode::Internal,
);
assert_failure(
provider
.call_operation(request(
"/broken",
None,
provider.broken.reference(),
None,
"broken",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::InvalidResult,
ProtocolErrorCode::OperationOutcomeUnknown,
);
assert_failure(
provider
.call_operation(request(
"/open",
None,
provider.reader.reference(),
Some(b"schema-v1"),
"fail",
BTreeMap::new(),
))
.unwrap_err(),
CallErrorKind::Implementation,
ProtocolErrorCode::OperationOutcomeUnknown,
);
}
@@ -0,0 +1,21 @@
use wip_host::{InterfaceRegistry, PublishedObject, WipObject};
use wip_interface::{OperationResult, interface};
#[interface]
pub trait Search {
fn search(&self) -> OperationResult<String>;
}
struct Object;
impl WipObject for Object {
fn name(&self) -> &str {
"object"
}
}
fn main() {
let mut registry = InterfaceRegistry::new();
let search = registry.register(SearchDefinition, None).unwrap();
let _published = PublishedObject::new(Object).expose(&search).unwrap();
}
@@ -0,0 +1,34 @@
error[E0277]: the trait bound `Object: Search` is not satisfied
--> tests/ui/unimplemented_interface.rs:20:58
|
20 | let _published = PublishedObject::new(Object).expose(&search).unwrap();
| ------ ^^^^^^^ unsatisfied trait bound
| |
| required by a bound introduced by this call
|
help: the trait `Search` is not implemented for `Object`
--> tests/ui/unimplemented_interface.rs:9:1
|
9 | struct Object;
| ^^^^^^^^^^^^^
help: this trait has no implementations, consider adding one
--> tests/ui/unimplemented_interface.rs:5:1
|
5 | pub trait Search {
| ^^^^^^^^^^^^^^^^
note: required for `SearchDefinition` to implement `InterfaceImplementation<Object>`
--> tests/ui/unimplemented_interface.rs:4:1
|
4 | #[interface]
| ^^^^^^^^^^^^
5 | pub trait Search {
| ^^^^^^
note: required by a bound in `PublishedObject::<T>::expose`
--> src/lib.rs
|
| pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
| ------ required by a bound in this associated function
| where
| D: InterfaceImplementation<T>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `PublishedObject::<T>::expose`
= note: this error originates in the attribute macro `interface` (in Nightly builds, run with -Z macro-backtrace for more info)
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "wip-interface-macros"
version = "0.1.0"
edition = "2024"
description = "Procedural macros for WIP interface declarations and DTO codecs"
license = "MIT OR Apache-2.0"
[lib]
proc-macro = true
[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full", "visit"] }
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "wip-interface"
version = "0.1.0"
edition = "2024"
description = "Public Rust authoring API for WIP interfaces and operation value codecs"
license = "MIT OR Apache-2.0"
[dependencies]
wip-interface-macros = { path = "../wip-interface-macros" }
wip-protocol = { path = "../wip-protocol" }
[dev-dependencies]
trybuild = "1"
+792
View File
@@ -0,0 +1,792 @@
//! Public authoring API for Web Interface Protocol (WIP) interfaces.
//!
//! Add `wip-interface` to an application and import it under the short name
//! used by the attribute examples:
//!
//! ```
//! use wip_interface as wip;
//!
//! #[derive(Debug, PartialEq, wip::WipType)]
//! struct Greeting {
//! /// Text shown to the recipient.
//! message: String,
//! }
//!
//! #[wip::interface]
//! pub trait Greeter {
//! /// Builds a greeting.
//! ///
//! /// # Returns
//! /// The generated greeting.
//! fn greet(&self, /// Person to greet.
//! name: String) -> wip::OperationResult<Greeting>;
//! }
//! ```
//!
//! The attribute and derive are re-exported by this facade; applications do
//! not depend on the implementation-only `wip-interface-macros` crate.
//!
//! # Rust to protocol type mapping
//!
//! | Rust type | Protocol type/value |
//! | --- | --- |
//! | `()` | `Unit` |
//! | `bool` | `Boolean` |
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
//! | `f32`, `f64` | finite `Number` |
//! | `String` | `String` |
//! | [`Bytes`] | `Bytes` |
//! | [`JsonValue`] | schema-neutral `Json` value tree |
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
//! | `Vec<T>` | `List<T>` |
//! | a named-field struct deriving [`WipType`] | named record |
//! | an all-unit enum deriving [`WipType`] | named enum |
//! | an enum mixing unit and single-payload cases deriving [`WipType`] | named union |
//!
//! `Option<T>` is supported only directly as a record field or operation
//! parameter. It means omission, not a null value. A domain failure belongs in
//! an application return enum/union and is returned as `Ok(value)`.
//! [`HostError`] is reserved for host/runtime failure, so the required
//! [`OperationResult`] convention keeps those two failure classes distinct.
//!
//! # Migration to canonical values
//!
//! Earlier releases exposed `Entry<K, V>` and semantic `Value::Json`,
//! `Value::Entry`, `Value::Enum`, and `Value::Union` variants. Those forms are
//! intentionally gone: [`Entry`] is now one validated absolute Worldspace path,
//! while JSON, enum, and union meaning comes only from the descriptor. Codecs
//! exchange only raw [`Value`] strings, records, lists, and primitives. Unit
//! operation results now cross the boundary as [`Value::Unit`] rather than an
//! absent value.
//!
//! # Supported interface syntax
//!
//! An interface is a public, non-generic trait whose operations use exactly
//! `&self`, simple named owned parameters, and an explicit
//! `OperationResult<T>`. `WipType` derives support named-field structs,
//! all-unit enums as protocol enums, and enums made from any mix of unit and
//! single-payload cases as protocol unions.
//!
//! The macros reject trait inheritance and associated items; const, async,
//! unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
//! borrowed values and custom lifetimes; tuple, unit, or generic structs;
//! unsupported named-field or multi-field enum variants; explicit discriminants; Rust unions;
//! and `Option` anywhere except a direct DTO field or operation parameter.
//! Unsupported inputs produce source-located compile errors rather than
//! generating a partial interface.
#![deny(missing_docs)]
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
pub use wip_interface_macros::{WipType, interface};
pub use wip_protocol;
pub use wip_protocol::{
Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
};
/// Converts one Rust application type to and from its protocol representation.
///
/// Implementations must describe the same shape accepted by [`WipType::decode`]
/// and produced by [`WipType::encode`]. Prefer deriving this trait for named
/// DTOs. Its declaration-collection method exists for generated interface code
/// and normally should not be called by applications.
pub trait WipType: Sized {
/// Returns the protocol type expression for this Rust type.
fn type_expr() -> TypeExpr;
/// Adds named declarations reachable from this type to `declarations`.
///
/// Implementations must be cycle-safe and preserve declaration order.
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>);
/// Encodes this value into the transport-independent protocol value model.
fn encode(self) -> Result<Value, CodecError>;
/// Decodes a previously validated protocol value.
fn decode(value: Value) -> Result<Self, CodecError>;
}
/// Static metadata implemented by every companion generated by
/// [`interface`].
pub trait InterfaceDefinition {
/// Builds the interface descriptor solely from its trait declaration.
fn descriptor() -> InterfaceDescriptor;
}
/// Typed dispatch implemented by every generated interface companion.
///
/// `T` must implement the Rust interface trait associated with this definition.
/// Host runtimes use this bound when an interface is explicitly exposed, so an
/// object that does not implement that interface is rejected at compile time.
pub trait InterfaceImplementation<T>: InterfaceDefinition {
/// Validates, decodes, and dispatches one operation to `implementation`,
/// then encodes and validates its result.
fn dispatch(
implementation: &T,
operation: &str,
arguments: BTreeMap<String, Value>,
) -> Result<Value, DispatchError>;
}
/// Result convention required for generated interface operations.
///
/// `Ok(T)` is an application result, including domain-failure union cases.
/// `Err(HostError)` means the host or runtime could not perform the operation.
pub type OperationResult<T> = Result<T, HostError>;
/// A host/runtime failure, kept separate from the operation's application
/// return type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostError {
message: String,
}
impl HostError {
/// Creates a host failure with a human-readable diagnostic.
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
/// Returns the diagnostic message.
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl Display for HostError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl Error for HostError {}
/// A failure while converting between a Rust value and a protocol [`Value`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodecError {
path: Vec<String>,
message: String,
}
impl CodecError {
/// Creates a codec failure at the current value.
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
path: Vec::new(),
message: message.into(),
}
}
/// Creates a structural-kind mismatch diagnostic.
#[must_use]
pub fn expected(expected: &str, actual: &Value) -> Self {
Self::new(format!("expected {expected}, found {:?}", actual.kind()))
}
/// Prepends a field, variant, or collection position to the error path.
#[must_use]
pub fn at(mut self, segment: impl Into<String>) -> Self {
self.path.insert(0, segment.into());
self
}
/// Returns the path from the decoded root to the failing value.
#[must_use]
pub fn path(&self) -> &[String] {
&self.path
}
/// Returns the human-readable reason for the failure.
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl Display for CodecError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
write!(formatter, "WIP codec error: {}", self.message)
} else {
write!(
formatter,
"WIP codec error at {}: {}",
self.path.join("."),
self.message
)
}
}
}
impl Error for CodecError {}
/// A failure produced by macro-generated typed operation dispatch.
#[derive(Debug)]
pub enum DispatchError {
/// The requested operation is not declared by this interface.
UnknownOperation(String),
/// Protocol validation rejected the named arguments.
InvalidArguments(wip_protocol::ValidationError),
/// A validated value could not be decoded to its Rust type.
Decode(CodecError),
/// The implementation reported a host/runtime failure.
Host(HostError),
/// The Rust result could not be encoded.
Encode(CodecError),
/// The encoded result did not match the generated declaration.
InvalidResult(wip_protocol::ValidationError),
}
impl Display for DispatchError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownOperation(operation) => {
write!(formatter, "unknown operation `{operation}`")
}
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
}
}
}
impl Error for DispatchError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::UnknownOperation(_) => None,
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
Self::Decode(error) | Self::Encode(error) => Some(error),
Self::Host(error) => Some(error),
}
}
}
/// An explicitly byte-oriented sequence.
///
/// Use this wrapper when the protocol type must be `Bytes`; `Vec<T>` always
/// denotes a protocol list, including `Vec<u8>`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Bytes(pub Vec<u8>);
impl From<Vec<u8>> for Bytes {
fn from(value: Vec<u8>) -> Self {
Self(value)
}
}
impl From<Bytes> for Vec<u8> {
fn from(value: Bytes) -> Self {
value.0
}
}
/// A canonical absolute path to an entry in the current Worldspace.
///
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
/// entry from a path such as `/articles/1`; application data associated with
/// that entry belongs in an ordinary record alongside this value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entry(String);
impl Entry {
/// Validates and creates an entry path.
pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
let path = path.into();
validate_entry_path(&path)?;
Ok(Self(path))
}
/// Returns the canonical absolute Worldspace path.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
/// Consumes the entry and returns its path.
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl TryFrom<String> for Entry {
type Error = CodecError;
fn try_from(path: String) -> Result<Self, Self::Error> {
Self::new(path)
}
}
impl std::str::FromStr for Entry {
type Err = CodecError;
fn from_str(path: &str) -> Result<Self, Self::Err> {
Self::new(path)
}
}
/// One member in a [`JsonValue::Object`].
#[derive(Debug, Clone, PartialEq)]
pub struct JsonMember {
/// Member name.
pub name: String,
/// Member value.
pub value: JsonValue,
}
/// JSON data represented independently of any application schema.
///
/// Its codec uses the ordinary schema-neutral [`Value`] variants. JSON null is
/// [`Value::Unit`], arrays are [`Value::List`], and objects are
/// [`Value::Record`]. Protocol bytes have no JSON representation and decoding
/// a tree containing [`Value::Bytes`] is rejected.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonValue {
/// JSON null.
Null,
/// A JSON boolean.
Boolean(bool),
/// An interoperable integral JSON number.
Integer(i64),
/// A finite non-integral JSON number.
Number(f64),
/// A JSON string.
String(String),
/// A JSON array.
Array(Vec<JsonValue>),
/// A JSON object. Duplicate member names are rejected while encoding.
Object(Vec<JsonMember>),
}
impl WipType for () {
fn type_expr() -> TypeExpr {
TypeExpr::Unit
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::Unit)
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Unit => Ok(()),
other => Err(CodecError::expected("unit", &other)),
}
}
}
impl WipType for bool {
fn type_expr() -> TypeExpr {
TypeExpr::Boolean
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::Boolean(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Boolean(value) => Ok(value),
other => Err(CodecError::expected("boolean", &other)),
}
}
}
macro_rules! integer_codec {
($($ty:ty),+ $(,)?) => {
$(
impl WipType for $ty {
fn type_expr() -> TypeExpr {
TypeExpr::Integer
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
let value = i64::try_from(self).map_err(|_| {
CodecError::new("integer is outside the protocol i64 range")
})?;
ensure_safe_integer(value)?;
Ok(Value::Integer(value))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::Integer(value) = value else {
return Err(CodecError::expected("integer", &value));
};
ensure_safe_integer(value)?;
Self::try_from(value).map_err(|_| {
CodecError::new(concat!("integer does not fit Rust `", stringify!($ty), "`"))
})
}
}
)+
};
}
integer_codec!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);
fn ensure_safe_integer(value: i64) -> Result<(), CodecError> {
if (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
Ok(())
} else {
Err(CodecError::new(format!(
"integer {value} is outside the JavaScript-lossless protocol range"
)))
}
}
impl WipType for f64 {
fn type_expr() -> TypeExpr {
TypeExpr::Number
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
ensure_finite(self)?;
Ok(Value::Number(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Number(value) => {
ensure_finite(value)?;
Ok(value)
}
other => Err(CodecError::expected("number", &other)),
}
}
}
impl WipType for f32 {
fn type_expr() -> TypeExpr {
TypeExpr::Number
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
let value = f64::from(self);
ensure_finite(value)?;
Ok(Value::Number(value))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let value = f64::decode(value)?;
let narrowed = value as Self;
if narrowed.is_finite() {
Ok(narrowed)
} else {
Err(CodecError::new("number does not fit finite Rust `f32`"))
}
}
}
fn ensure_finite(value: f64) -> Result<(), CodecError> {
if value.is_finite() {
Ok(())
} else {
Err(CodecError::new("protocol numbers must be finite"))
}
}
impl WipType for String {
fn type_expr() -> TypeExpr {
TypeExpr::String
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::String(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::String(value) => Ok(value),
other => Err(CodecError::expected("string", &other)),
}
}
}
impl WipType for Bytes {
fn type_expr() -> TypeExpr {
TypeExpr::Bytes
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::Bytes(self.0))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Bytes(value) => Ok(Self(value)),
other => Err(CodecError::expected("bytes", &other)),
}
}
}
impl WipType for JsonValue {
fn type_expr() -> TypeExpr {
TypeExpr::Json
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
encode_json(self)
}
fn decode(value: Value) -> Result<Self, CodecError> {
decode_json(value)
}
}
fn encode_json(value: JsonValue) -> Result<Value, CodecError> {
match value {
JsonValue::Null => Ok(Value::Unit),
JsonValue::Boolean(value) => Ok(Value::Boolean(value)),
JsonValue::Integer(value) => {
ensure_safe_integer(value)?;
Ok(Value::Integer(value))
}
JsonValue::Number(value) => {
ensure_finite(value)?;
Ok(Value::Number(value))
}
JsonValue::String(value) => Ok(Value::String(value)),
JsonValue::Array(values) => values
.into_iter()
.enumerate()
.map(|(index, value)| encode_json(value).map_err(|error| error.at(index.to_string())))
.collect::<Result<Vec<_>, _>>()
.map(Value::List),
JsonValue::Object(members) => {
let mut fields = BTreeMap::new();
for member in members {
let name = member.name;
let value = encode_json(member.value).map_err(|error| error.at(name.clone()))?;
if fields.insert(name.clone(), value).is_some() {
return Err(CodecError::new(format!("duplicate JSON member `{name}`")).at(name));
}
}
Ok(Value::Record(fields))
}
}
}
fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
match value {
Value::Unit => Ok(JsonValue::Null),
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
Value::Integer(value) => {
ensure_safe_integer(value)?;
Ok(JsonValue::Integer(value))
}
Value::Number(value) => {
ensure_finite(value)?;
Ok(JsonValue::Number(value))
}
Value::String(value) => Ok(JsonValue::String(value)),
Value::Bytes(_) => Err(CodecError::new("bytes are not valid inside JSON")),
Value::List(values) => values
.into_iter()
.enumerate()
.map(|(index, value)| decode_json(value).map_err(|error| error.at(index.to_string())))
.collect::<Result<Vec<_>, _>>()
.map(JsonValue::Array),
Value::Record(fields) => fields
.into_iter()
.map(|(name, value)| {
decode_json(value)
.map(|value| JsonMember {
name: name.clone(),
value,
})
.map_err(|error| error.at(name))
})
.collect::<Result<Vec<_>, _>>()
.map(JsonValue::Object),
}
}
impl<T: WipType> WipType for Vec<T> {
fn type_expr() -> TypeExpr {
TypeExpr::List {
items: Box::new(T::type_expr()),
}
}
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
T::collect_declarations(declarations);
}
fn encode(self) -> Result<Value, CodecError> {
self.into_iter()
.enumerate()
.map(|(index, value)| value.encode().map_err(|error| error.at(index.to_string())))
.collect::<Result<Vec<_>, _>>()
.map(Value::List)
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::List(values) = value else {
return Err(CodecError::expected("list", &value));
};
values
.into_iter()
.enumerate()
.map(|(index, value)| T::decode(value).map_err(|error| error.at(index.to_string())))
.collect()
}
}
impl WipType for Entry {
fn type_expr() -> TypeExpr {
TypeExpr::Entry
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
validate_entry_path(&self.0)?;
Ok(Value::String(self.0))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::String(path) = value else {
return Err(CodecError::expected("entry path string", &value));
};
Self::new(path)
}
}
fn validate_entry_path(path: &str) -> Result<(), CodecError> {
wip_protocol::validate_path(path)
.map_err(|error| CodecError::new(format!("invalid canonical Worldspace path: {error}")))
}
/// Implementation details used by code emitted from the facade's macros.
///
/// These APIs are public only because macro expansions execute in the
/// application crate. They are excluded from normal generated documentation
/// and are not intended for direct use.
#[doc(hidden)]
pub mod __private {
use std::collections::BTreeMap;
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
use crate::{CodecError, Documentation, WipType};
/// Builds optional descriptor documentation from generated string literals.
pub fn documentation(summary: &str, details: Option<&str>) -> Option<Documentation> {
if summary.is_empty() && details.is_none() {
None
} else {
Some(Documentation {
summary: summary.into(),
details: details.map(str::to_owned),
})
}
}
/// Registers one declaration and reports whether its dependencies should
/// be traversed. Identical declarations are deduplicated; a conflicting
/// declaration with the same name is retained for protocol validation.
pub fn register_declaration(
declarations: &mut Vec<TypeDeclaration>,
declaration: TypeDeclaration,
) -> bool {
if declarations.iter().any(|existing| existing == &declaration) {
false
} else {
declarations.push(declaration);
true
}
}
/// Validates named arguments against one generated operation declaration.
pub fn validate_arguments(
descriptor: &InterfaceDescriptor,
operation: &str,
arguments: &BTreeMap<String, Value>,
) -> Result<(), ValidationError> {
descriptor.validate_arguments(operation, arguments)
}
/// Builds a codec error for a generated structural mismatch.
pub fn decode_type_mismatch(expected: &str, actual: Value) -> CodecError {
CodecError::expected(expected, &actual)
}
/// Builds a codec error for an unknown generated enum or union variant.
pub fn decode_unknown_variant(type_name: &str, variant: String) -> CodecError {
CodecError::new(format!(
"unknown variant `{variant}` for WIP type `{type_name}`"
))
.at(variant)
}
/// Decoder for a protocol record or operation's named argument collection.
pub struct RecordDecoder {
fields: BTreeMap<String, Value>,
}
impl RecordDecoder {
/// Starts decoding record fields or named operation arguments.
pub fn new(fields: BTreeMap<String, Value>) -> Self {
Self { fields }
}
/// Decodes a required field.
pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
let value = self.take(name).ok_or_else(|| {
CodecError::new(format!("missing required field `{name}`")).at(name)
})?;
T::decode(value).map_err(|error| error.at(name))
}
/// Decodes an optional field, where absence maps to `None`.
pub fn optional<T: WipType>(&mut self, name: &str) -> Result<Option<T>, CodecError> {
self.take(name)
.map(T::decode)
.transpose()
.map_err(|error| error.at(name))
}
/// Rejects any fields that were not consumed by generated code.
pub fn finish(self) -> Result<(), CodecError> {
if let Some(name) = self.fields.keys().next() {
Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
} else {
Ok(())
}
}
fn take(&mut self, name: &str) -> Option<Value> {
self.fields.remove(name)
}
}
}
+231
View File
@@ -0,0 +1,231 @@
use std::collections::BTreeMap;
use wip_interface::wip_protocol::{TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, Value};
use wip_interface::{Bytes, Entry, JsonMember, JsonValue, WipType};
/// A request record.
#[derive(Debug, Clone, PartialEq, WipType)]
struct Request {
/// Required title.
title: String,
/// Optional priority.
priority: Option<i32>,
/// Related Worldspace entries.
related: Vec<Entry>,
/// Opaque bytes.
body: Bytes,
/// Arbitrary metadata.
metadata: JsonValue,
}
/// Available colors.
#[derive(Debug, Clone, PartialEq, WipType)]
enum Color {
/// Warm red.
Red,
/// Cool blue.
Blue,
}
/// A receipt record.
#[derive(Debug, Clone, PartialEq, WipType)]
struct Receipt {
/// Receipt number.
number: u32,
}
/// Application-level publication outcome.
#[derive(Debug, Clone, PartialEq, WipType)]
enum PublishOutcome {
/// Work has not completed and carries no payload.
Pending,
/// Application success.
Published(Receipt),
/// Domain rejection, not a host failure.
Rejected(String),
}
fn field<'a>(record: &'a BTreeMap<String, Value>, name: &str) -> &'a Value {
record
.get(name)
.unwrap_or_else(|| panic!("missing `{name}`"))
}
#[test]
fn primitive_unit_record_list_entry_and_json_values_round_trip() {
assert_eq!(().encode().unwrap(), Value::Unit);
assert_eq!(<()>::decode(Value::Unit).unwrap(), ());
assert_eq!(<()>::type_expr(), TypeExpr::Unit);
let request = Request {
title: "hello".into(),
priority: None,
related: vec![Entry::new("/articles/1").unwrap()],
body: Bytes(vec![1, 2, 3]),
metadata: JsonValue::Object(vec![JsonMember {
name: "source".into(),
value: JsonValue::Array(vec![JsonValue::String("test".into()), JsonValue::Null]),
}]),
};
let encoded = request.clone().encode().unwrap();
let Value::Record(fields) = &encoded else {
panic!("record derive must encode a raw protocol record")
};
assert!(!fields.contains_key("priority"));
assert_eq!(
field(fields, "related"),
&Value::List(vec![Value::String("/articles/1".into())])
);
assert_eq!(
field(fields, "metadata"),
&Value::Record(BTreeMap::from([(
"source".into(),
Value::List(vec![Value::String("test".into()), Value::Unit]),
)]))
);
assert_eq!(Request::decode(encoded).unwrap(), request);
let number = 42.5_f64;
assert_eq!(f64::type_expr(), TypeExpr::Number);
assert_eq!(f64::decode(number.encode().unwrap()).unwrap(), number);
let narrow_number = 1.5_f32;
assert_eq!(f32::type_expr(), TypeExpr::Number);
assert_eq!(
f32::decode(narrow_number.encode().unwrap()).unwrap(),
narrow_number
);
}
#[test]
fn enums_are_strings_and_unions_are_discriminated_records() {
for color in [Color::Red, Color::Blue] {
let encoded = color.clone().encode().unwrap();
assert!(matches!(encoded, Value::String(_)));
assert_eq!(Color::decode(encoded).unwrap(), color);
}
let pending = PublishOutcome::Pending.encode().unwrap();
assert_eq!(
pending,
Value::Record(BTreeMap::from([(
UNION_CASE_FIELD.into(),
Value::String("Pending".into()),
)]))
);
let published = PublishOutcome::Published(Receipt { number: 7 })
.encode()
.unwrap();
let Value::Record(fields) = &published else {
panic!("union must encode as a record")
};
assert_eq!(
fields.get(UNION_CASE_FIELD),
Some(&Value::String("Published".into()))
);
assert!(matches!(
fields.get(UNION_VALUE_FIELD),
Some(Value::Record(_))
));
for outcome in [
PublishOutcome::Pending,
PublishOutcome::Published(Receipt { number: 7 }),
PublishOutcome::Rejected("policy".into()),
] {
let encoded = outcome.clone().encode().unwrap();
assert_eq!(PublishOutcome::decode(encoded).unwrap(), outcome);
}
}
#[test]
fn derived_declarations_use_canonical_named_type_expressions() {
let mut declarations = Vec::new();
Request::collect_declarations(&mut declarations);
Color::collect_declarations(&mut declarations);
PublishOutcome::collect_declarations(&mut declarations);
let request = declarations
.iter()
.find(|declaration| declaration.name == "Request")
.unwrap();
assert_eq!(
request.documentation.as_ref().unwrap().summary,
"A request record."
);
let TypeExpr::Record { fields } = &request.definition else {
panic!("Request must be a record declaration")
};
assert_eq!(
fields[0].documentation.as_ref().unwrap().summary,
"Required title."
);
assert!(fields[0].required);
assert!(!fields[1].required);
assert_eq!(fields[1].r#type, TypeExpr::Integer);
assert_eq!(
fields[2].r#type,
TypeExpr::List {
items: Box::new(TypeExpr::Entry),
}
);
let color = declarations
.iter()
.find(|declaration| declaration.name == "Color")
.unwrap();
let TypeExpr::Enum { cases } = &color.definition else {
panic!("Color must be an enum declaration")
};
assert_eq!(
cases[0].documentation.as_ref().unwrap().summary,
"Warm red."
);
let outcome = declarations
.iter()
.find(|declaration| declaration.name == "PublishOutcome")
.unwrap();
let TypeExpr::Union { cases } = &outcome.definition else {
panic!("PublishOutcome must be a union declaration")
};
assert_eq!(cases[0].payload, None);
assert_eq!(
cases[1].payload,
Some(TypeExpr::Named {
name: "Receipt".into(),
})
);
assert!(
declarations
.iter()
.any(|declaration| declaration.name == "Receipt")
);
}
#[test]
fn codecs_reject_invalid_boundaries_and_json_bytes() {
assert!(i64::MAX.encode().is_err());
assert!(f64::NAN.encode().is_err());
assert!(Request::decode(Value::Record(BTreeMap::new())).is_err());
assert!(
Request::decode(Value::Record(BTreeMap::from([(
"unknown".into(),
Value::String("value".into()),
)])))
.is_err()
);
assert!(Color::decode(Value::String("Green".into())).is_err());
assert!(Entry::new("articles/1").is_err());
assert!(Entry::decode(Value::String("/articles/../1".into())).is_err());
assert!(JsonValue::decode(Value::Bytes(vec![1])).is_err());
assert!(
JsonValue::decode(Value::Record(BTreeMap::from([(
"nested".into(),
Value::List(vec![Value::Bytes(vec![1])]),
)])))
.is_err()
);
}
@@ -0,0 +1,5 @@
#[test]
fn rejects_unsupported_interface_and_dto_syntax() {
let tests = trybuild::TestCases::new();
tests.compile_fail("tests/ui/*.rs");
}
+252
View File
@@ -0,0 +1,252 @@
use std::collections::BTreeMap;
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
/// Publication request.
#[derive(Debug, Clone, PartialEq, WipType)]
pub struct PublishRequest {
/// Item title.
pub title: String,
}
/// Application outcome, including domain failure.
#[derive(Debug, Clone, PartialEq, WipType)]
pub enum PublishOutcome {
/// The item was accepted.
Published(bool),
/// The application rejected the item.
Rejected(String),
}
/// Catalog editing capability.
///
/// The shape is implementation-independent.
#[interface]
pub trait Catalog {
/// Publishes one item.
///
/// This operation can report a domain rejection in its application union.
///
/// # Returns
/// The application publication outcome.
fn publish(
&self,
/// Item to publish.
request: PublishRequest,
/// Optional audit note.
note: Option<String>,
) -> OperationResult<PublishOutcome>;
/// Checks connectivity without returning application data.
fn ping(&self) -> OperationResult<()>;
/// Demonstrates a host/runtime failure.
///
/// # Returns
/// A value only when the host succeeds.
fn host_value(&self) -> OperationResult<String>;
}
struct AcceptingCatalog;
impl Catalog for AcceptingCatalog {
fn publish(
&self,
request: PublishRequest,
note: Option<String>,
) -> OperationResult<PublishOutcome> {
assert_eq!(request.title, "example");
assert_eq!(note.as_deref(), Some("audit"));
Ok(PublishOutcome::Published(true))
}
fn ping(&self) -> OperationResult<()> {
Ok(())
}
fn host_value(&self) -> OperationResult<String> {
Err(HostError::new("backend unavailable"))
}
}
struct RejectingCatalog;
impl Catalog for RejectingCatalog {
fn publish(
&self,
_request: PublishRequest,
_note: Option<String>,
) -> OperationResult<PublishOutcome> {
Ok(PublishOutcome::Rejected("policy".into()))
}
fn ping(&self) -> OperationResult<()> {
Ok(())
}
fn host_value(&self) -> OperationResult<String> {
Ok("ready".into())
}
}
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
let mut arguments = BTreeMap::from([(
"request".into(),
PublishRequest {
title: "example".into(),
}
.encode()
.unwrap(),
)]);
if with_note {
arguments.insert("note".into(), Value::String("audit".into()));
}
arguments
}
#[test]
fn descriptor_is_canonical_and_generated_only_from_the_trait_declaration() {
let first = CatalogDefinition::descriptor();
let second = CatalogDefinition::descriptor();
assert_eq!(first, second);
first.validate().unwrap();
assert_eq!(first.format, INTERFACE_FORMAT_V1);
assert_eq!(
first.documentation.as_ref().unwrap().summary,
"Catalog editing capability."
);
assert_eq!(
first.documentation.as_ref().unwrap().details.as_deref(),
Some("The shape is implementation-independent.")
);
assert_eq!(first.operations.len(), 3);
let publish = &first.operations[0];
assert_eq!(publish.name, "publish");
assert_eq!(publish.parameters[0].name, "request");
assert_eq!(
publish.parameters[0]
.documentation
.as_ref()
.unwrap()
.summary,
"Item to publish."
);
assert!(publish.parameters[0].required);
assert!(!publish.parameters[1].required);
assert_eq!(
publish.returns.documentation.as_ref().unwrap().summary,
"The application publication outcome."
);
assert_eq!(
publish.returns.r#type,
TypeExpr::Named {
name: "PublishOutcome".into(),
}
);
assert_eq!(first.operations[1].returns.r#type, TypeExpr::Unit);
assert!(
first
.types
.iter()
.any(|declaration| matches!(declaration.definition, TypeExpr::Record { .. }))
);
assert!(
first
.types
.iter()
.any(|declaration| matches!(declaration.definition, TypeExpr::Union { .. }))
);
// Both implementation types satisfy one immutable generated definition;
// implementation selection cannot contribute fields to the descriptor.
fn accepts_definition<T: Catalog>(_: &T) {}
accepts_definition(&AcceptingCatalog);
accepts_definition(&RejectingCatalog);
assert_eq!(CatalogDefinition::descriptor(), first);
}
#[test]
fn generated_argument_decoder_and_result_encoder_use_raw_values() {
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
assert_eq!(decoded.request.title, "example");
assert_eq!(decoded.note, None);
let encoded =
CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into())).unwrap();
assert_eq!(
PublishOutcome::decode(encoded).unwrap(),
PublishOutcome::Rejected("domain".into())
);
assert_eq!(
CatalogPingArguments::encode_result(()).unwrap(),
Value::Unit
);
}
#[test]
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
let value =
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true)).unwrap();
assert_eq!(
PublishOutcome::decode(value).unwrap(),
PublishOutcome::Published(true)
);
assert_eq!(
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", BTreeMap::new()).unwrap(),
Value::Unit
);
let invalid =
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
let host =
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
let unknown =
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
}
/// Operations whose distinct source names normalize to the same PascalCase.
#[interface]
pub trait DistinctOperations {
/// Returns the first item marker.
fn item(&self) -> OperationResult<String>;
/// Returns the underscored item marker.
fn item_(&self) -> OperationResult<String>;
}
struct DistinctImplementation;
impl DistinctOperations for DistinctImplementation {
fn item(&self) -> OperationResult<String> {
Ok("item".into())
}
fn item_(&self) -> OperationResult<String> {
Ok("item_".into())
}
}
#[test]
fn distinct_operation_names_always_generate_distinct_public_items() {
let descriptor = DistinctOperationsDefinition::descriptor();
assert_eq!(descriptor.operations[0].name, "item");
assert_eq!(descriptor.operations[1].name, "item_");
let first =
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", BTreeMap::new())
.unwrap();
let second =
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", BTreeMap::new())
.unwrap();
assert_eq!(first, Value::String("item".into()));
assert_eq!(second, Value::String("item_".into()));
}
@@ -0,0 +1,10 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait AssociatedType {
type Item;
fn load(&self) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: associated types are not supported in WIP interfaces
--> tests/ui/associated_type.rs:5:5
|
5 | type Item;
| ^^^^^^^^^^
warning: unused import: `OperationResult`
--> tests/ui/associated_type.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,8 @@
use wip_interface::interface;
#[interface]
pub trait AsyncOperation {
async fn status(&self) -> wip_interface::OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,5 @@
error: async operations are not supported
--> tests/ui/async_operation.rs:5:5
|
5 | async fn status(&self) -> wip_interface::OperationResult<String>;
| ^^^^^
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait BadReceiver {
fn load(&mut self) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: the only supported receiver is exactly `&self`
--> tests/ui/bad_receiver.rs:5:13
|
5 | fn load(&mut self) -> OperationResult<String>;
| ^^^^^^^^^
warning: unused import: `OperationResult`
--> tests/ui/bad_receiver.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait BadReturn {
fn load(&self) -> String;
}
fn main() {}
@@ -0,0 +1,13 @@
error: an operation must explicitly return `OperationResult<T>`
--> tests/ui/bad_return.rs:5:23
|
5 | fn load(&self) -> String;
| ^^^^^^
warning: unused import: `OperationResult`
--> tests/ui/bad_return.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait BorrowedValue<'a> {
fn load(&self, value: &'a str) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: generic WIP interface traits are not supported
--> tests/ui/custom_lifetime.rs:4:24
|
4 | pub trait BorrowedValue<'a> {
| ^^^^
warning: unused import: `OperationResult`
--> tests/ui/custom_lifetime.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,10 @@
use wip_interface::interface;
#[interface]
pub trait DefaultMethod {
fn status(&self) -> wip_interface::OperationResult<String> {
Ok(String::new())
}
}
fn main() {}
@@ -0,0 +1,8 @@
error: WIP operation methods must not have a body
--> tests/ui/default_method.rs:5:64
|
5 | fn status(&self) -> wip_interface::OperationResult<String> {
| ________________________________________________________________^
6 | | Ok(String::new())
7 | | }
| |_____^
@@ -0,0 +1,9 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait DuplicateOperation {
fn load(&self) -> OperationResult<String>;
fn load(&self, other: String) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: duplicate operation name `load`
--> tests/ui/duplicate_operation.rs:6:8
|
6 | fn load(&self, other: String) -> OperationResult<String>;
| ^^^^
warning: unused import: `OperationResult`
--> tests/ui/duplicate_operation.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,8 @@
use wip_interface::WipType;
#[derive(WipType)]
struct GenericDto<T> {
value: T,
}
fn main() {}
@@ -0,0 +1,5 @@
error: generic DTOs are not supported by `WipType`
--> tests/ui/generic_dto.rs:4:18
|
4 | struct GenericDto<T> {
| ^^^
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait GenericOperation {
fn load<T>(&self, value: T) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: generic operations are not supported
--> tests/ui/generic_method.rs:5:12
|
5 | fn load<T>(&self, value: T) -> OperationResult<String>;
| ^^^
warning: unused import: `OperationResult`
--> tests/ui/generic_method.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait Inherited: Send {
fn load(&self) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,13 @@
error: WIP interface trait inheritance is not supported
--> tests/ui/inherited_trait.rs:4:22
|
4 | pub trait Inherited: Send {
| ^^^^
warning: unused import: `OperationResult`
--> tests/ui/inherited_trait.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,9 @@
use wip_interface::WipType;
#[derive(WipType)]
enum UnsupportedEnum {
Empty,
Payload { value: String },
}
fn main() {}
@@ -0,0 +1,5 @@
error: a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported
--> tests/ui/mixed_enum.rs:6:5
|
6 | Payload { value: String },
| ^^^^^^^
@@ -0,0 +1,8 @@
use wip_interface::WipType;
#[derive(WipType)]
struct NestedOption {
values: Vec<Option<String>>,
}
fn main() {}
@@ -0,0 +1,5 @@
error: `Option<T>` must appear directly as the DTO field type
--> tests/ui/nested_option.rs:5:13
|
5 | values: Vec<Option<String>>,
| ^^^^^^^^^^^^^^^^^^^
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
trait PrivateInterface {
fn load(&self) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,15 @@
error: a WIP interface trait must be public
--> tests/ui/private_trait.rs:3:1
|
3 | #[interface]
| ^^^^^^^^^^^^
|
= note: this error originates in the attribute macro `interface` (in Nightly builds, run with -Z macro-backtrace for more info)
warning: unused import: `OperationResult`
--> tests/ui/private_trait.rs:1:21
|
1 | use wip_interface::{OperationResult, interface};
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
@@ -0,0 +1,6 @@
use wip_interface::WipType;
#[derive(WipType)]
struct TupleDto(String, String);
fn main() {}
@@ -0,0 +1,5 @@
error: `WipType` supports only structs with named fields
--> tests/ui/tuple_dto.rs:4:16
|
4 | struct TupleDto(String, String);
| ^^^^^^^^^^^^^^^^
@@ -0,0 +1,8 @@
use wip_interface::{OperationResult, interface};
#[interface]
pub trait UnsupportedType {
fn load(&self, pair: (String, String)) -> OperationResult<String>;
}
fn main() {}
@@ -0,0 +1,31 @@
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
--> tests/ui/unsupported_type.rs:5:26
|
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
help: the trait `WipType` is implemented for `()`
--> src/lib.rs
|
| impl WipType for () {
| ^^^^^^^^^^^^^^^^^^^
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
--> tests/ui/unsupported_type.rs:5:26
|
3 | #[interface]
| ------------ required by a bound introduced by this call
4 | pub trait UnsupportedType {
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
help: the trait `WipType` is implemented for `()`
--> src/lib.rs
|
| impl WipType for () {
| ^^^^^^^^^^^^^^^^^^^
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
--> src/lib.rs
|
| pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
| ^^^^^^^ required by this bound in `RecordDecoder::required`
+220 -86
View File
@@ -8,79 +8,65 @@ pub enum NameNamespace {
TypeDeclaration, TypeDeclaration,
/// Operations in an interface descriptor. /// Operations in an interface descriptor.
Operation, Operation,
/// Fields in a record declaration. /// Fields in an inline or named record type.
Field, Field,
/// Parameters in an operation declaration. /// Parameters in an operation declaration.
Parameter, Parameter,
/// Variants in an enum declaration. /// Cases in an enum type.
EnumVariant, EnumCase,
/// Variants in a union declaration. /// Cases in a union type.
UnionVariant, UnionCase,
/// Fields supplied in a record value. /// Child object names beneath one tree node.
RecordValueField, ChildObject,
/// Arguments supplied in an operation call.
Argument,
/// Members in a logical JSON object.
JsonMember,
/// Descriptors in an interface observation.
InterfaceDescriptor,
} }
/// Structural kind of a logical protocol value. /// Structural kind of a schema-neutral logical value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueKind { pub enum ValueKind {
/// String value. /// Unit value.
String, Unit,
/// Boolean value. /// Boolean value.
Boolean, Boolean,
/// Integer value. /// Integer value.
Integer, Integer,
/// Floating-point number value. /// Floating-point number value.
Number, Number,
/// String value.
String,
/// Byte sequence. /// Byte sequence.
Bytes, Bytes,
/// List value.
List,
/// Key/value entry.
Entry,
/// Record value. /// Record value.
Record, Record,
/// Enum value. /// List value.
Enum, List,
/// Tagged-union value.
Union,
/// Logical JSON value.
Json,
} }
/// A typed segment identifying a declaration or value location. /// A typed segment identifying a declaration or value location.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathSegment { pub enum PathSegment {
/// Interface descriptor. /// Descriptor root.
Interface(String), Descriptor,
/// Named type declaration. /// Named type declaration.
Declaration(String), Declaration(String),
/// Operation declaration or call. /// Operation declaration or call.
Operation(String), Operation(String),
/// Record field declaration or value. /// Record field declaration or value.
Field(String), Field(String),
/// Operation parameter declaration or argument. /// Operation parameter or argument.
Parameter(String), Parameter(String),
/// Enum or union variant. /// Enum or union case.
Variant(String), Case(String),
/// List or JSON array index. /// List index.
Index(usize), Index(usize),
/// Entry key.
EntryKey,
/// Entry value.
EntryValue,
/// Operation return value. /// Operation return value.
Return, Return,
/// JSON object member. /// Object at a Worldspace path.
JsonMember(String), Object(String),
/// Child object in a tree response.
Child(String),
} }
/// Machine-readable reason why protocol validation failed. /// Machine-readable reason why logical protocol validation failed.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind { pub enum ValidationErrorKind {
/// A name occurred more than once in one namespace. /// A name occurred more than once in one namespace.
@@ -117,11 +103,15 @@ pub enum ValidationErrorKind {
/// Missing field name. /// Missing field name.
name: String, name: String,
}, },
/// An enum or union value selected an undeclared variant. /// An enum or union selected an undeclared case.
UnknownVariant { UnknownCase {
/// Unknown variant name. /// Unknown case name.
name: String, name: String,
}, },
/// A payload-bearing union case omitted `value`.
MissingUnionPayload,
/// A payload-free union case supplied `value`.
UnexpectedUnionPayload,
/// An operation call contains an undeclared argument. /// An operation call contains an undeclared argument.
UnknownParameter { UnknownParameter {
/// Unknown parameter name. /// Unknown parameter name.
@@ -132,44 +122,66 @@ pub enum ValidationErrorKind {
/// Missing parameter name. /// Missing parameter name.
name: String, name: String,
}, },
/// An integer is outside the JavaScript-lossless range. /// An operation is not declared by the descriptor.
UnknownOperation {
/// Unknown operation name.
name: String,
},
/// An integer is outside the interoperable safe range.
IntegerOutOfRange { IntegerOutOfRange {
/// Rejected integer. /// Rejected integer.
value: i64, value: i64,
}, },
/// A numeric value is NaN or infinite. /// A numeric value is NaN or infinite.
NonFiniteNumber, NonFiniteNumber,
/// A JSON-interpreted value tree contains protocol bytes.
BytesInJson,
/// An object name is not a valid root or non-root path segment.
InvalidObjectName {
/// Rejected object name.
name: String,
},
/// An object's ordered interface set contains a duplicate. /// An object's ordered interface set contains a duplicate.
DuplicateInterface { DuplicateInterface {
/// Duplicate interface name. /// Duplicate opaque interface reference.
name: String, reference: String,
}, },
/// An observation omits a descriptor named by its object. /// A string is not a canonical absolute Worldspace path.
MissingInterfaceDescriptor { InvalidPath {
/// Missing interface name. /// Rejected path.
name: String, path: String,
}, },
/// An observation contains a descriptor not named by its object. /// An object name does not match the path where it was observed.
UnexpectedInterfaceDescriptor { ObjectNameMismatch {
/// Unexpected interface name. /// Name required by the observation path.
name: String,
},
/// A call targets an interface other than the descriptor being used.
InterfaceMismatch {
/// Descriptor interface name.
expected: String, expected: String,
/// Call target interface name. /// Name supplied by the object.
actual: String, actual: String,
}, },
/// An operation is not declared by the interface. /// Equivalent ref/validator observations disagree on object representation.
UnknownOperation { InconsistentObjectObservation {
/// Unknown operation name. /// Shared opaque object reference.
name: String, reference: String,
},
/// A `fetch_tree` request used a zero limit.
ZeroTreeLimit,
/// A tree response exceeds the requested maximum depth.
TreeDepthExceeded {
/// Requested maximum depth.
maximum: u32,
},
/// A tree response exceeds the requested maximum node count.
TreeLimitExceeded {
/// Requested maximum node count.
limit: u32,
},
/// A response refers to a different interface than its request.
InterfaceResponseMismatch {
/// Requested opaque reference.
expected: String,
/// Returned opaque reference.
actual: String,
}, },
/// A no-return operation produced a value.
UnexpectedReturnValue,
/// An operation with a return declaration produced no value.
MissingReturnValue,
} }
/// A validation failure with a typed path to the failing location. /// A validation failure with a typed path to the failing location.
@@ -211,30 +223,152 @@ impl Display for ValidationError {
impl Error for ValidationError {} impl Error for ValidationError {}
/// Stable category of an error returned by a protocol host runtime. /// One core interaction whose failure codes form a closed set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolErrorCategory { pub enum ProtocolInteraction {
/// The request is structurally invalid. /// Fetch one object by its Worldspace path.
InvalidRequest, Fetch,
/// The target object is not published. /// Fetch a bounded tree of objects.
ObjectNotFound, FetchTree,
/// The target interface is not implemented by the object. /// Fetch one interface descriptor by its opaque reference.
InterfaceNotFound, FetchInterface,
/// The target operation is not declared by the interface. /// Invoke one operation on a path-targeted object.
OperationNotFound, CallOperation,
/// Supplied operation arguments are invalid.
InvalidArguments,
/// The implementation rejected the call for a domain reason.
OperationFailed,
/// The host encountered an internal failure.
Internal,
} }
/// Transport-independent protocol failure returned by a host runtime. /// Stable protocol failure code returned by a host.
///
/// This is the complete wire-level code set. A Client treats a malformed success
/// or failure response, including a code disallowed for its interaction, as a
/// Client-local `InvalidResponse`. An unsupported descriptor format is likewise
/// a Client-local `UnsupportedDescriptorFormat`; neither condition is a code a
/// Host can return.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolErrorCode {
/// The request is structurally invalid before an operation descriptor is fixed.
InvalidRequest,
/// The target object is not published.
NotFound,
/// The interface reference is not currently published.
InterfaceNotFound,
/// The selected interface is not on the current object.
InterfaceMismatch,
/// The selected operation is not declared by the current interface.
OperationNotFound,
/// Supplied arguments do not match the fixed operation declaration.
InvalidArguments,
/// The operation requires an object validator and none was supplied.
ValidatorRequired,
/// The supplied object validator does not match current state.
ValidatorMismatch,
/// A mutable interface requires its validator and none was supplied.
InterfaceValidatorRequired,
/// The supplied interface validator does not match the descriptor.
InterfaceValidatorMismatch,
/// A published operation is not permitted for the caller.
PermissionDenied,
/// A bounded protocol resource limit was exceeded.
///
/// For `call_operation`, the Host guarantees that the operation was not run
/// or that all of its effects were rolled back.
ResourceLimitExceeded,
/// The Host encountered an internal failure.
///
/// For `call_operation`, the Host guarantees that the operation was not run
/// or that all of its effects were rolled back.
Internal,
/// The Host cannot guarantee that the operation was not run or rolled back.
///
/// A Client must not automatically retry because the operation may have
/// committed effects even though no success response was available.
OperationOutcomeUnknown,
}
impl ProtocolErrorCode {
/// Every canonical wire-level error code.
pub const ALL: [Self; 14] = [
Self::InvalidRequest,
Self::NotFound,
Self::InterfaceNotFound,
Self::InterfaceMismatch,
Self::OperationNotFound,
Self::InvalidArguments,
Self::ValidatorRequired,
Self::ValidatorMismatch,
Self::InterfaceValidatorRequired,
Self::InterfaceValidatorMismatch,
Self::PermissionDenied,
Self::ResourceLimitExceeded,
Self::Internal,
Self::OperationOutcomeUnknown,
];
/// Whether a Host may return this code for `interaction`.
///
/// `false` identifies an invalid error response; it does not turn that
/// response into another wire-level protocol failure.
#[must_use]
pub const fn is_allowed_for(self, interaction: ProtocolInteraction) -> bool {
use ProtocolErrorCode::{
InterfaceMismatch, InterfaceNotFound, InterfaceValidatorMismatch,
InterfaceValidatorRequired, Internal, InvalidArguments, InvalidRequest, NotFound,
OperationNotFound, OperationOutcomeUnknown, PermissionDenied, ResourceLimitExceeded,
ValidatorMismatch, ValidatorRequired,
};
use ProtocolInteraction::{CallOperation, Fetch, FetchInterface, FetchTree};
match (interaction, self) {
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
(Fetch | FetchTree, NotFound) => true,
(FetchInterface, InterfaceNotFound) => true,
(
CallOperation,
NotFound
| InterfaceMismatch
| OperationNotFound
| InvalidArguments
| ValidatorRequired
| ValidatorMismatch
| InterfaceValidatorRequired
| InterfaceValidatorMismatch
| PermissionDenied
| OperationOutcomeUnknown,
) => true,
(
_,
NotFound
| InterfaceNotFound
| InterfaceMismatch
| OperationNotFound
| InvalidArguments
| ValidatorRequired
| ValidatorMismatch
| InterfaceValidatorRequired
| InterfaceValidatorMismatch
| PermissionDenied
| OperationOutcomeUnknown,
) => false,
}
}
}
/// Transport-independent protocol failure.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtocolError { pub struct ProtocolError {
/// Stable programmatic category. /// Stable programmatic code. Consumers must branch on this field.
pub category: ProtocolErrorCategory, pub code: ProtocolErrorCode,
/// Human-readable diagnostic. Consumers must not branch on this text. /// Bounded human-readable diagnostic. Consumers must not branch on it.
pub message: String, pub message: String,
} }
impl Display for ProtocolError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(
formatter,
"protocol failure ({:?}): {}",
self.code, self.message
)
}
}
impl Error for ProtocolError {}
+64 -14
View File
@@ -1,9 +1,45 @@
//! Transport-independent logical types for the Web Interface Protocol (WIP). //! Canonical transport-independent logical types for the Web Interface Protocol.
//! //!
//! This crate deliberately models interface declarations, published objects, //! This crate follows the Core Model and `3-protocol.md` without assigning HTTP
//! operation calls, and operation results without assigning them HTTP routes, //! routes, methods, headers, URL encodings, or JSON envelopes. The correspondence
//! methods, headers, or JSON envelopes. A transport can encode these values, //! between canonical logical concepts and this crate is direct:
//! but the encoding is outside this crate's contract. //!
//! | Canonical protocol concept | Rust API |
//! | --- | --- |
//! | Object projection and ordered interface set | [`Object`] |
//! | Optional object identity / state precondition | `Object::ref` / [`Object::validator`] |
//! | Interface Descriptor | [`InterfaceDescriptor`] |
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
//! | Schema-neutral primitive/composite value | [`Value`] |
//! | `fetch` | [`FetchRequest`] / [`FetchResponse`] |
//! | `fetch_tree` | [`FetchTreeRequest`] / [`FetchTreeResponse`] |
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
//! | Stable Host failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
//! | Per-interaction allowed failure codes | [`ProtocolInteraction`] / [`ProtocolErrorCode::is_allowed_for`] |
//!
//! [`ProtocolErrorCode`] is a closed set of Host-returned wire failures. After a
//! Client receives a response, an invalid Object, Descriptor, operation result,
//! malformed error, or error code disallowed by [`ProtocolInteraction`] is a
//! Client-local `InvalidResponse`, not another wire error. A descriptor whose
//! `format` is not supported is a Client-local `UnsupportedDescriptorFormat`.
//!
//! For `call_operation`, [`ProtocolErrorCode::Internal`] and
//! [`ProtocolErrorCode::ResourceLimitExceeded`] guarantee that the operation did
//! not run or that all effects were rolled back. Only
//! [`ProtocolErrorCode::OperationOutcomeUnknown`] means the Host cannot make that
//! guarantee; Clients must not automatically retry it.
//!
//! Paths, object refs, interface refs, and validators remain separate concepts.
//! They are represented by ordinary protocol strings/bytes in the corresponding
//! fields. In particular, object refs are optional, operation targeting uses a
//! path, and this crate defines no interaction that fetches an object by ref.
//!
//! [`Value`] contains only the canonical raw value kinds. A descriptor interprets
//! enum values as strings, entries as canonical-path strings, and unions as
//! records with a `$case` string plus an optional `value` payload. JSON uses the
//! same value tree (`Unit` is JSON null) and rejects bytes.
#![deny(missing_docs)] #![deny(missing_docs)]
@@ -12,19 +48,33 @@ mod model;
mod validation; mod validation;
pub use error::{ pub use error::{
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCategory, ValidationError, NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
ValidationErrorKind, ValueKind, ValidationError, ValidationErrorKind, ValueKind,
}; };
pub use model::{ pub use model::{
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor, CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
InterfaceObservation, JsonMember, JsonValue, NamedValue, Object, ObjectId, OperationCall, FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest, FetchTreeResponse,
OperationDeclaration, OperationOutcome, OperationResult, OperationTarget, ParameterDeclaration, FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object, ObjectTreeNode,
RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr, UnionDeclaration, OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
UnionVariantDeclaration, Value, TypeDeclaration, TypeExpr, UnionCase, Value,
}; };
/// Largest integer that is exactly interoperable with a JavaScript `Number`. /// Validates a canonical absolute Worldspace path.
pub fn validate_path(path: &str) -> Result<(), ValidationError> {
validation::validate_path(path)
}
/// Canonical format identifier for the first Interface Descriptor format.
pub const INTERFACE_FORMAT_V1: &str = "wip-interface/1";
/// Discriminator field used by a union's raw record value.
pub const UNION_CASE_FIELD: &str = "$case";
/// Optional payload field used by a union's raw record value.
pub const UNION_VALUE_FIELD: &str = "value";
/// Largest integer exactly interoperable with a JavaScript `Number`.
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991; pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
/// Smallest integer that is exactly interoperable with a JavaScript `Number`. /// Smallest integer exactly interoperable with a JavaScript `Number`.
pub const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER; pub const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER;
+308 -253
View File
@@ -1,6 +1,8 @@
use std::collections::BTreeMap;
use crate::{ProtocolError, ValidationError}; use crate::{ProtocolError, ValidationError};
/// Human-readable documentation attached to a protocol declaration. /// Human-readable plain-text documentation attached to a protocol declaration.
#[derive(Debug, Clone, PartialEq, Eq, Default)] #[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Documentation { pub struct Documentation {
/// A short, self-contained description. /// A short, self-contained description.
@@ -9,242 +11,194 @@ pub struct Documentation {
pub details: Option<String>, pub details: Option<String>,
} }
/// Stable logical identity of a published object. /// The protocol projection currently published at one Worldspace path.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObjectId(pub String);
/// A published object and the ordered set of interfaces it implements.
/// ///
/// The vector order is significant. Call [`Object::validate`] before /// `name` is a path segment, `interfaces` is an ordered set of opaque interface
/// publication to reject duplicate interface names. /// references, `r#ref` is optional object identity, and `validator` is an
/// independent optional observation precondition. In particular, neither the
/// path nor `r#ref` is a mandatory object identifier.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Object { pub struct Object {
/// Logical object identity. /// Path-segment name. The root object's name is empty.
pub id: ObjectId, pub name: String,
/// Interface names in publication order. /// Short public description of the object.
pub description: Option<String>,
/// Opaque interface references in host publication order.
pub interfaces: Vec<String>, pub interfaces: Vec<String>,
} /// Optional opaque identity within one client-facing Worldspace.
pub r#ref: Option<String>,
/// A complete logical observation of an object and its interface descriptors. /// Optional opaque validator for the object's observed state.
#[derive(Debug, Clone, PartialEq)] pub validator: Option<Vec<u8>>,
pub struct InterfaceObservation {
/// Observed object.
pub object: Object,
/// Descriptors corresponding to `object.interfaces`.
pub descriptors: Vec<InterfaceDescriptor>,
} }
/// Transport-independent description of one interface. /// Transport-independent description of one interface.
#[derive(Debug, Clone, PartialEq)] ///
/// Interface identity is supplied by interaction fields such as
/// [`FetchInterfaceResponse::interface`], not embedded in the descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceDescriptor { pub struct InterfaceDescriptor {
/// Interface name. /// Descriptor format version understood by clients and hosts.
pub name: String, pub format: String,
/// Optional interface documentation. /// Optional interface documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Named type declarations local to this descriptor. /// Named declarations local to this descriptor.
pub declarations: Vec<TypeDeclaration>, pub types: Vec<TypeDeclaration>,
/// Operations exposed by this interface. /// Operations exposed by this interface.
pub operations: Vec<OperationDeclaration>, pub operations: Vec<OperationDeclaration>,
} }
/// A named type declaration local to an interface descriptor. /// A descriptor-local named type declaration.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeDeclaration { pub struct TypeDeclaration {
/// A record declaration.
Record(RecordDeclaration),
/// An enumeration declaration.
Enum(EnumDeclaration),
/// A tagged union declaration.
Union(UnionDeclaration),
}
impl TypeDeclaration {
/// Returns the descriptor-local declaration name.
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::Record(declaration) => &declaration.name,
Self::Enum(declaration) => &declaration.name,
Self::Union(declaration) => &declaration.name,
}
}
}
/// Declaration of a record with named fields.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordDeclaration {
/// Descriptor-local type name. /// Descriptor-local type name.
pub name: String, pub name: String,
/// Optional record documentation. /// Optional type documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Fields in declaration order. /// Definition associated with `name`.
pub fields: Vec<FieldDeclaration>, pub definition: TypeExpr,
}
/// A type expression used by declarations, fields, parameters, and returns.
///
/// [`TypeExpr::Named`] references are resolved only within the containing
/// descriptor. Recursive references, including recursion through lists,
/// records, and unions, are invalid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeExpr {
/// A value carrying no data.
Unit,
/// A boolean.
Boolean,
/// A JavaScript-lossless signed integer.
Integer,
/// A finite IEEE-754 binary64 number.
Number,
/// A Unicode string.
String,
/// An opaque byte sequence.
Bytes,
/// A schema-opaque JSON-compatible value tree.
Json,
/// A canonical absolute Worldspace path represented by a string value.
Entry,
/// A descriptor-local named declaration.
Named {
/// Referenced declaration name.
name: String,
},
/// A record with named fields.
Record {
/// Fields in declaration order.
fields: Vec<FieldDeclaration>,
},
/// An ordered list.
List {
/// Type of every list item.
items: Box<TypeExpr>,
},
/// A closed set of payload-free cases represented by strings.
Enum {
/// Cases in declaration order.
cases: Vec<EnumCase>,
},
/// A discriminated union represented by a record.
Union {
/// Cases in declaration order.
cases: Vec<UnionCase>,
},
} }
/// Declaration of a record field. /// Declaration of a record field.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldDeclaration { pub struct FieldDeclaration {
/// Field name. /// Field name.
pub name: String, pub name: String,
/// Whether the field must be present.
pub required: bool,
/// Optional field documentation. /// Optional field documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Field value type. /// Field value type.
pub ty: TypeExpr, pub r#type: TypeExpr,
/// Whether the field may be omitted.
///
/// Optionality represents absence, not a `null` value.
pub optional: bool,
} }
/// Declaration of an enumeration. /// One payload-free enum case.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumDeclaration { pub struct EnumCase {
/// Descriptor-local type name. /// Case name.
pub name: String, pub name: String,
/// Optional enum documentation. /// Optional case documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Allowed variants in declaration order.
pub variants: Vec<EnumVariantDeclaration>,
} }
/// Declaration of one enumeration variant. /// One union case with zero or one payload.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumVariantDeclaration { pub struct UnionCase {
/// Variant name. /// Case name.
pub name: String, pub name: String,
/// Optional variant documentation. /// Optional case documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
} /// Optional payload type.
pub payload: Option<TypeExpr>,
/// Declaration of a tagged union.
#[derive(Debug, Clone, PartialEq)]
pub struct UnionDeclaration {
/// Descriptor-local type name.
pub name: String,
/// Optional union documentation.
pub documentation: Option<Documentation>,
/// Allowed tagged variants in declaration order.
pub variants: Vec<UnionVariantDeclaration>,
}
/// Declaration of one tagged-union variant.
#[derive(Debug, Clone, PartialEq)]
pub struct UnionVariantDeclaration {
/// Variant tag.
pub name: String,
/// Optional variant documentation.
pub documentation: Option<Documentation>,
/// Payload type.
pub ty: TypeExpr,
}
/// A type expression used by fields, parameters, returns, and union payloads.
///
/// `Named` references are resolved only within the containing descriptor.
/// Optional values are represented by the containing field or parameter and
/// therefore are intentionally not a type expression.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
/// A UTF-8 string.
String,
/// A boolean.
Boolean,
/// A JavaScript-lossless integer.
Integer,
/// A finite IEEE-754 double precision number.
Number,
/// An opaque byte sequence.
Bytes,
/// An ordered sequence of values.
List(Box<TypeExpr>),
/// A key/value entry.
Entry {
/// Entry key type.
key: Box<TypeExpr>,
/// Entry value type.
value: Box<TypeExpr>,
},
/// A logical JSON value.
Json,
/// A descriptor-local named declaration.
Named(String),
} }
/// Declaration of one interface operation. /// Declaration of one interface operation.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationDeclaration { pub struct OperationDeclaration {
/// Operation name, unique within its interface. /// Operation name, unique within its descriptor.
pub name: String, pub name: String,
/// Optional operation documentation. /// Optional operation documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Parameters in declaration order. /// Parameters in declaration order.
pub parameters: Vec<ParameterDeclaration>, pub parameters: Vec<ParameterDeclaration>,
/// Return declaration, or `None` for an operation with no return value. /// Return declaration. No-data operations return [`TypeExpr::Unit`].
pub returns: Option<ReturnDeclaration>, pub returns: ReturnDeclaration,
} }
/// Declaration of one operation parameter. /// Declaration of one operation parameter.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParameterDeclaration { pub struct ParameterDeclaration {
/// Parameter name. /// Parameter name.
pub name: String, pub name: String,
/// Whether the parameter must be present.
pub required: bool,
/// Optional parameter documentation. /// Optional parameter documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Parameter value type. /// Parameter value type.
pub ty: TypeExpr, pub r#type: TypeExpr,
/// Whether the parameter may be omitted.
///
/// Optionality represents absence, not a `null` value.
pub optional: bool,
} }
/// Declaration of an operation return value. /// Declaration of an operation return value.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReturnDeclaration { pub struct ReturnDeclaration {
/// Optional return-value documentation. /// Optional return-value documentation.
pub documentation: Option<Documentation>, pub documentation: Option<Documentation>,
/// Return value type. /// Return value type.
pub ty: TypeExpr, pub r#type: TypeExpr,
} }
/// A logical protocol value. /// A schema-neutral logical protocol value.
/// ///
/// There is no general `Null` variant: optional record fields and operation /// Enum cases, union cases, entries, and JSON are interpretations imposed by a
/// parameters are omitted. JSON null remains available inside [`Value::Json`]. /// descriptor. They are deliberately not variants of this enum. Record key
/// ordering is not protocol-significant.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Value { pub enum Value {
/// A UTF-8 string. /// A value carrying no data; it also represents JSON null under `Json`.
String(String), Unit,
/// A boolean. /// A boolean.
Boolean(bool), Boolean(bool),
/// An integer, validated against the JavaScript safe integer range. /// A JavaScript-lossless integer.
Integer(i64), Integer(i64),
/// A number, validated to be finite. /// A finite IEEE-754 binary64 number.
Number(f64), Number(f64),
/// A Unicode string.
String(String),
/// An opaque byte sequence. /// An opaque byte sequence.
Bytes(Vec<u8>), Bytes(Vec<u8>),
/// String-keyed fields with order-insensitive semantics.
Record(BTreeMap<String, Value>),
/// An ordered sequence. /// An ordered sequence.
List(Vec<Value>), List(Vec<Value>),
/// A key/value entry.
Entry {
/// Entry key.
key: Box<Value>,
/// Entry value.
value: Box<Value>,
},
/// Record fields. Duplicate names are invalid.
Record(Vec<NamedValue>),
/// An enum variant name.
Enum(String),
/// A tagged-union value.
Union {
/// Selected variant tag.
variant: String,
/// Variant payload.
value: Box<Value>,
},
/// A logical JSON value.
Json(JsonValue),
} }
impl Value { impl Value {
@@ -252,132 +206,233 @@ impl Value {
#[must_use] #[must_use]
pub fn kind(&self) -> crate::ValueKind { pub fn kind(&self) -> crate::ValueKind {
match self { match self {
Self::String(_) => crate::ValueKind::String, Self::Unit => crate::ValueKind::Unit,
Self::Boolean(_) => crate::ValueKind::Boolean, Self::Boolean(_) => crate::ValueKind::Boolean,
Self::Integer(_) => crate::ValueKind::Integer, Self::Integer(_) => crate::ValueKind::Integer,
Self::Number(_) => crate::ValueKind::Number, Self::Number(_) => crate::ValueKind::Number,
Self::String(_) => crate::ValueKind::String,
Self::Bytes(_) => crate::ValueKind::Bytes, Self::Bytes(_) => crate::ValueKind::Bytes,
Self::List(_) => crate::ValueKind::List,
Self::Entry { .. } => crate::ValueKind::Entry,
Self::Record(_) => crate::ValueKind::Record, Self::Record(_) => crate::ValueKind::Record,
Self::Enum(_) => crate::ValueKind::Enum, Self::List(_) => crate::ValueKind::List,
Self::Union { .. } => crate::ValueKind::Union,
Self::Json(_) => crate::ValueKind::Json,
} }
} }
} }
/// A named value used by records and operation arguments. /// Request for the object currently published at one path.
#[derive(Debug, Clone, PartialEq)]
pub struct NamedValue {
/// Field or parameter name.
pub name: String,
/// Associated value.
pub value: Value,
}
/// A transport-independent JSON value.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonValue {
/// JSON null.
Null,
/// JSON boolean.
Boolean(bool),
/// JSON integer, validated against the JavaScript safe integer range.
Integer(i64),
/// JSON number, validated to be finite.
Number(f64),
/// JSON string.
String(String),
/// JSON array.
Array(Vec<JsonValue>),
/// JSON object. Duplicate member names are invalid.
Object(Vec<JsonMember>),
}
/// A member of a logical JSON object.
#[derive(Debug, Clone, PartialEq)]
pub struct JsonMember {
/// Member name.
pub name: String,
/// Member value.
pub value: JsonValue,
}
/// Logical destination of an operation call.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationTarget { pub struct FetchRequest {
/// Target object. /// Canonical absolute Worldspace path.
pub object: ObjectId, pub path: String,
/// Target interface name. }
/// Successful `fetch` response.
pub type FetchResponse = Object;
/// Request for a bounded breadth-first object-tree observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTreeRequest {
/// Canonical absolute path of the tree root.
pub path: String,
/// Maximum depth, where the requested object has depth zero.
pub depth: u32,
/// Maximum total node count, including the root. Must be nonzero.
pub limit: u32,
}
/// One node in a tree observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectTreeNode {
/// Object observed at this tree position.
pub object: Object,
/// Direct children in host-defined traversal order.
pub children: Vec<ObjectTreeNode>,
}
/// Successful `fetch_tree` response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTreeResponse {
/// Observed tree rooted at the requested path.
pub root: ObjectTreeNode,
/// Whether public indexable children were omitted by depth or limit.
pub truncated: bool,
}
/// Request for the current descriptor of one opaque interface reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchInterfaceRequest {
/// Opaque interface reference obtained from an object.
pub interface: String, pub interface: String,
/// Target operation name. }
/// Successful `fetch_interface` response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchInterfaceResponse {
/// Opaque interface reference corresponding to the request.
pub interface: String,
/// Current validated descriptor.
pub descriptor: InterfaceDescriptor,
/// Optional opaque validator for this descriptor observation.
pub validator: Option<Vec<u8>>,
}
/// Object portion of an operation target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
/// Canonical absolute path of the target object.
pub path: String,
/// Optional validator copied from the object observation.
pub validator: Option<Vec<u8>>,
}
/// Interface portion of an operation target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceTarget {
/// Opaque interface reference selected from the object's interface set.
pub reference: String,
/// Optional validator copied from the interface observation.
pub validator: Option<Vec<u8>>,
}
/// Transport-independent request to execute one operation.
#[derive(Debug, Clone, PartialEq)]
pub struct CallOperationRequest {
/// Path and optional object-state precondition.
pub target: Target,
/// Interface reference and its independent optional precondition.
pub interface: InterfaceTarget,
/// Operation name within the selected descriptor.
pub operation: String, pub operation: String,
/// Named arguments; map iteration order has no protocol meaning.
pub arguments: BTreeMap<String, Value>,
} }
/// A transport-independent operation call. /// Successful operation response.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct OperationCall { pub struct CallOperationResponse {
/// Logical call target. /// Application result validated against the operation return declaration.
pub target: OperationTarget, pub result: Value,
/// Named arguments. Optional arguments are represented by omission. /// Optional validator for the object state observed after execution.
pub arguments: Vec<NamedValue>, pub validator: Option<Vec<u8>>,
} }
/// Successful or failed logical outcome of an operation. /// Logical outcome of any core interaction.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum OperationOutcome { pub enum ProtocolResult<T> {
/// Operation returned. `None` represents a declared no-return operation. /// The interaction succeeded.
Returned(Option<Value>), Success(T),
/// Operation failed with a protocol-level error. /// The interaction failed at the protocol boundary.
Failed(ProtocolError), Failure(ProtocolError),
}
/// A transport-independent operation result.
#[derive(Debug, Clone, PartialEq)]
pub struct OperationResult {
/// Target corresponding to the result.
pub target: OperationTarget,
/// Logical outcome.
pub outcome: OperationOutcome,
} }
impl Object { impl Object {
/// Validates ordered-set interface semantics. /// Validates the object-independent name and ordered-interface-set rules.
pub fn validate(&self) -> Result<(), ValidationError> { pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_object(self) crate::validation::validate_object(self)
} }
}
impl InterfaceObservation { /// Validates this object as the response observed at `path`.
/// Validates the object, descriptor structure, and their correspondence. pub fn validate_at_path(&self, path: &str) -> Result<(), ValidationError> {
pub fn validate(&self) -> Result<(), ValidationError> { crate::validation::validate_object_at_path(self, path)
crate::validation::validate_observation(self) }
/// Validates equal representations for a shared ref and present validator.
pub fn validate_consistency_with(&self, other: &Self) -> Result<(), ValidationError> {
crate::validation::validate_object_consistency(self, other)
} }
} }
impl InterfaceDescriptor { impl InterfaceDescriptor {
/// Validates declaration structure, references, and absence of recursion. /// Validates declaration structure, named references, and absence of cycles.
pub fn validate(&self) -> Result<(), ValidationError> { pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_descriptor(self) crate::validation::validate_descriptor(self)
} }
/// Validates a value against a type expression in this descriptor. /// Validates a raw value against a type expression in this descriptor.
pub fn validate_value(&self, ty: &TypeExpr, value: &Value) -> Result<(), ValidationError> { pub fn validate_value(&self, r#type: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
crate::validation::validate_root_value(self, ty, value) crate::validation::validate_root_value(self, r#type, value)
} }
/// Validates a call target and arguments against this descriptor. /// Validates named arguments for one declared operation.
pub fn validate_call(&self, call: &OperationCall) -> Result<(), ValidationError> { pub fn validate_arguments(
crate::validation::validate_call(self, call)
}
/// Validates an operation's returned value against this descriptor.
pub fn validate_return(
&self, &self,
operation: &str, operation: &str,
value: Option<&Value>, arguments: &BTreeMap<String, Value>,
) -> Result<(), ValidationError> { ) -> Result<(), ValidationError> {
crate::validation::validate_return(self, operation, value) crate::validation::validate_arguments(self, operation, arguments)
}
/// Validates one operation result against its return declaration.
pub fn validate_result(&self, operation: &str, result: &Value) -> Result<(), ValidationError> {
crate::validation::validate_result(self, operation, result)
}
/// Validates the path, operation, and arguments in a call request.
pub fn validate_call(&self, request: &CallOperationRequest) -> Result<(), ValidationError> {
crate::validation::validate_call(self, request)
}
}
impl FetchRequest {
/// Validates the request path.
pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_path(&self.path)
}
/// Validates an object returned for this request.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`].
pub fn validate_response(&self, response: &FetchResponse) -> Result<(), ValidationError> {
response.validate_at_path(&self.path)
}
}
impl FetchTreeRequest {
/// Validates the request path and nonzero node limit.
pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_fetch_tree_request(self)
}
}
impl FetchTreeResponse {
/// Validates tree shape, names, depth, and node limit for `request`.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`].
pub fn validate_for(&self, request: &FetchTreeRequest) -> Result<(), ValidationError> {
crate::validation::validate_fetch_tree_response(self, request)
}
}
impl FetchInterfaceResponse {
/// Validates request correspondence and descriptor semantics.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`]. Descriptor format support is a
/// separate Client concern: an otherwise valid descriptor with an unsupported
/// `format` is a Client-local `UnsupportedDescriptorFormat`.
pub fn validate_for(&self, request: &FetchInterfaceRequest) -> Result<(), ValidationError> {
crate::validation::validate_fetch_interface_response(self, request)
}
}
impl CallOperationRequest {
/// Validates this call against the descriptor selected by `interface`.
pub fn validate_with(&self, descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
descriptor.validate_call(self)
}
}
impl CallOperationResponse {
/// Validates this result against the named operation in `descriptor`.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`].
pub fn validate_for(
&self,
descriptor: &InterfaceDescriptor,
operation: &str,
) -> Result<(), ValidationError> {
descriptor.validate_result(operation, &self.result)
} }
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "wip-public-api-example"
version = "0.1.0"
edition = "2024"
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
license = "MIT OR Apache-2.0"
publish = false
[dependencies]
wip-host = { path = "../wip-host" }
wip-interface = { path = "../wip-interface" }
wip-protocol = { path = "../wip-protocol" }
+508
View File
@@ -0,0 +1,508 @@
//! Public-only conformance consumer for the WIP Rust crates.
//!
//! # Architectural boundary
//!
//! This package is an ordinary application consumer. Its direct dependencies are
//! the public `wip-protocol`, `wip-interface`, and `wip-host` crates; it neither
//! imports workspace-private modules nor depends on `wip-interface-macros`.
//! `wip-protocol` owns transport-independent DTOs and schema-neutral values,
//! while this package owns its application DTOs and interface traits. The
//! request-scoped implementation, backend handle, authorization policy, and
//! publication wiring remain host-private. A transport binding would translate
//! its own wire routes and envelopes to the protocol call DTOs; no HTTP type is
//! part of an application trait or interface descriptor.
//!
//! # Breaking migration exercised here
//!
//! The canonical API targets operations by `target.path` rather than a mandatory
//! object identifier. Object `ref` and object/interface validators are separate,
//! optional observation fields. Interface references are opaque values observed
//! separately from descriptors, and descriptors contain neither a Rust trait
//! name nor an opaque-reference `name` field. Application records, enums,
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
//! variants: entries and enums are strings, unions are discriminator records,
//! and JSON recursively uses ordinary records/lists/primitives. The former
//! `Entry<K, V>` and semantic `Value::Entry`, `Value::Enum`, `Value::Union`, and
//! `Value::Json` forms are intentionally unsupported.
//!
//! # Supported authoring subset
//!
//! Public, non-generic traits use immutable `&self` receivers, owned named
//! parameters, and explicit `wip::OperationResult<T>` returns. Derived DTOs are
//! named-field records, all-unit enums, or unions with unit and single-payload
//! cases. A direct `Option<T>` means field/argument omission, never protocol
//! null. See `wip-interface` for the complete rejected-syntax list.
#![deny(missing_docs)]
use std::collections::BTreeMap;
use std::error::Error;
use std::io;
use wip_host::{
CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget, ObjectProvider,
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
};
use wip_interface as wip;
use wip_interface::WipType;
use wip_protocol::{ProtocolError, ProtocolErrorCode, Value};
const OBJECT_PATH: &str = "/article-service";
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
/// Publication visibility represented as a protocol enum string.
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
pub enum Visibility {
/// Visible to every authorized caller.
Public,
/// Visible only inside the application domain.
Private,
}
/// An application-owned request DTO mapped to a protocol record.
#[derive(Debug, Clone, PartialEq, wip::WipType)]
pub struct PublishRequest {
/// Title of the article to publish.
pub title: String,
/// Optional article body; omission is distinct from JSON null.
pub body: Option<String>,
/// Canonical Worldspace path to the source entry.
pub source: wip::Entry,
/// Application enum represented by a schema-neutral string.
pub visibility: Visibility,
/// Schema-opaque JSON represented by ordinary protocol values.
pub metadata: wip::JsonValue,
}
/// The application domain result of a publication attempt.
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
pub enum PublishOutcome {
/// Publication succeeded and returned its application identifier.
Published(String),
/// An application policy rejected the publication.
Rejected(String),
}
/// Article publication operations.
#[wip::interface]
pub trait Catalog {
/// Publishes an article or reports an application-domain rejection.
///
/// # Returns
/// The typed application outcome.
fn publish(
&self,
/// Application publication request.
request: PublishRequest,
) -> wip::OperationResult<PublishOutcome>;
/// Returns the catalog-qualified status.
fn status(&self) -> wip::OperationResult<String>;
/// Demonstrates a host/backend failure rather than a domain result.
fn backend_status(&self) -> wip::OperationResult<String>;
/// Demonstrates denial after every structural precondition succeeds.
fn restricted_status(&self) -> wip::OperationResult<String>;
}
/// Audit operations exposed by the same object.
#[wip::interface]
pub trait Audit {
/// Returns the audit-qualified status.
fn status(&self) -> wip::OperationResult<String>;
}
/// A registered but deliberately unexposed interface.
#[wip::interface]
pub trait Diagnostics {
/// Returns host-private diagnostics when explicitly exposed.
fn diagnostics(&self) -> wip::OperationResult<String>;
}
/// Observable outcomes from the complete public-API scenario.
#[derive(Debug, Clone, PartialEq)]
pub struct DemoReport {
/// Path-segment name from the canonical object projection.
pub object_name: String,
/// Optional object identity, distinct from the resolution path.
pub object_reference: Option<String>,
/// Optional object-state validator.
pub object_validator: Option<Vec<u8>>,
/// Opaque interface references published by the object, in exposure order.
pub published_interfaces: Vec<String>,
/// Opaque reference assigned to the catalog descriptor.
pub catalog_interface_reference: String,
/// Opaque reference assigned to the audit descriptor.
pub audit_interface_reference: String,
/// Descriptor format observed separately for the catalog reference.
pub catalog_descriptor_format: String,
/// Descriptor format observed separately for the audit reference.
pub audit_descriptor_format: String,
/// Typed successful application result decoded from a validated [`Value`].
pub published: PublishOutcome,
/// Typed application-domain rejection decoded from a validated [`Value`].
pub rejected: PublishOutcome,
/// Result of the catalog-qualified `status` operation.
pub catalog_status: String,
/// Result of the audit-qualified `status` operation.
pub audit_status: String,
/// Stable failure kind produced by the deliberate host/backend failure.
pub host_failure: CallErrorKind,
/// A protocol failure whose operation effects cannot be guaranteed absent.
pub protocol_failure: ProtocolError,
/// Authorization failure after a fully qualified valid request.
pub permission_failure: ProtocolErrorCode,
/// Recovery signal for a stale object validator.
pub validator_failure: ProtocolErrorCode,
/// Failure for a known but unexposed interface reference.
pub interface_mismatch: ProtocolErrorCode,
/// Failure for an unknown interface observation reference.
pub interface_not_found: ProtocolErrorCode,
/// First failure for a request with an invalid path and later invalid fields.
pub precedence_failure: ProtocolErrorCode,
}
/// Runs the complete end-to-end conformance example.
///
/// The provider resolves the current object from a Worldspace path for each
/// call. Interface observations remain separate from object projection, and all
/// successful calls carry independent object and interface validators.
///
/// # Errors
///
/// Returns an error if registration, observation, path resolution, dispatch, or
/// application-value decoding fails unexpectedly.
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
let mut registry = InterfaceRegistry::new();
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
let audit = registry.register(AuditDefinition, None)?;
let diagnostics = registry.register(DiagnosticsDefinition, None)?;
let provider = ApplicationProvider {
catalog: catalog.clone(),
audit: audit.clone(),
};
let object = provider.fetch(OBJECT_PATH)?;
let catalog_observation = registry.fetch_interface(
object
.interfaces
.first()
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
)?;
let audit_observation = registry.fetch_interface(
object
.interfaces
.get(1)
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
)?;
let published = dispatch_publish(
&provider,
catalog.reference(),
PublishRequest {
title: "Public APIs".into(),
body: Some("protocol values in, validated values out".into()),
source: wip::Entry::new("/drafts/public-apis")?,
visibility: Visibility::Public,
metadata: wip::JsonValue::Object(vec![wip::JsonMember {
name: "reviewed".into(),
value: wip::JsonValue::Boolean(true),
}]),
},
)?;
let rejected = dispatch_publish(
&provider,
catalog.reference(),
PublishRequest {
title: String::new(),
body: None,
source: wip::Entry::new("/drafts/untitled")?,
visibility: Visibility::Private,
metadata: wip::JsonValue::Null,
},
)?;
let catalog_status = dispatch_string(
&provider,
request(
OBJECT_PATH,
catalog.reference(),
Some(CATALOG_VALIDATOR),
"status",
BTreeMap::new(),
),
)?;
let audit_status = dispatch_string(
&provider,
request(
OBJECT_PATH,
audit.reference(),
None,
"status",
BTreeMap::new(),
),
)?;
let host_error = provider
.call_operation(request(
OBJECT_PATH,
catalog.reference(),
Some(CATALOG_VALIDATOR),
"backend_status",
BTreeMap::new(),
))
.expect_err("backend_status must model a host failure");
ensure_kind(&host_error, CallErrorKind::Implementation)?;
let protocol_failure = host_error.protocol_error();
let permission_failure = provider
.call_operation(request(
OBJECT_PATH,
catalog.reference(),
Some(CATALOG_VALIDATOR),
"restricted_status",
BTreeMap::new(),
))
.expect_err("restricted_status must be denied")
.protocol_error()
.code;
let validator_failure = provider
.call_operation(CallRequest {
target: Target {
path: OBJECT_PATH.into(),
validator: Some(b"stale-object".to_vec()),
},
interface: InterfaceTarget {
reference: diagnostics.reference().as_str().to_owned(),
validator: Some(b"stale-interface".to_vec()),
},
operation: "missing".into(),
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
})
.expect_err("the stale object validator must fail first")
.protocol_error()
.code;
let interface_mismatch = provider
.call_operation(request(
OBJECT_PATH,
diagnostics.reference(),
None,
"diagnostics",
BTreeMap::new(),
))
.expect_err("registered but unexposed interface must not dispatch")
.protocol_error()
.code;
let interface_not_found = registry
.fetch_interface("missing-interface")
.expect_err("unknown interface references must not resolve")
.code;
let precedence_failure = provider
.call_operation(CallRequest {
target: Target {
path: "relative/path".into(),
validator: Some(b"stale-object".to_vec()),
},
interface: InterfaceTarget {
reference: diagnostics.reference().as_str().to_owned(),
validator: Some(b"stale-interface".to_vec()),
},
operation: "missing".into(),
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
})
.expect_err("invalid path must have canonical precedence")
.protocol_error()
.code;
Ok(DemoReport {
object_name: object.name,
object_reference: object.r#ref,
object_validator: object.validator,
published_interfaces: object.interfaces,
catalog_interface_reference: catalog.reference().as_str().to_owned(),
audit_interface_reference: audit.reference().as_str().to_owned(),
catalog_descriptor_format: catalog_observation.descriptor.format,
audit_descriptor_format: audit_observation.descriptor.format,
published,
rejected,
catalog_status,
audit_status,
host_failure: host_error.kind(),
protocol_failure,
permission_failure,
validator_failure,
interface_mismatch,
interface_not_found,
precedence_failure,
})
}
fn ensure_kind(error: &wip_host::CallError, expected: CallErrorKind) -> Result<(), io::Error> {
if error.kind() == expected {
Ok(())
} else {
Err(io::Error::other(format!(
"unexpected host failure kind: {:?}",
error.kind()
)))
}
}
fn dispatch_publish(
provider: &ApplicationProvider,
catalog: &InterfaceRef,
request_value: PublishRequest,
) -> Result<PublishOutcome, Box<dyn Error>> {
let encoded_request = request_value.encode()?;
let result = provider.call_operation(request(
OBJECT_PATH,
catalog,
Some(CATALOG_VALIDATOR),
"publish",
BTreeMap::from([("request".into(), encoded_request)]),
))?;
Ok(PublishOutcome::decode(result.result)?)
}
fn dispatch_string(
provider: &ApplicationProvider,
request: CallRequest,
) -> Result<String, Box<dyn Error>> {
let result = provider.call_operation(request)?;
Ok(String::decode(result.result)?)
}
fn request(
path: &str,
interface: &InterfaceRef,
interface_validator: Option<&[u8]>,
operation: &str,
arguments: BTreeMap<String, Value>,
) -> CallRequest {
CallRequest {
target: Target {
path: path.into(),
validator: Some(OBJECT_VALIDATOR.to_vec()),
},
interface: InterfaceTarget {
reference: interface.as_str().to_owned(),
validator: interface_validator.map(<[u8]>::to_vec),
},
operation: operation.into(),
arguments,
}
}
struct ApplicationProvider {
catalog: RegisteredInterface<CatalogDefinition>,
audit: RegisteredInterface<AuditDefinition>,
}
impl ObjectProvider for ApplicationProvider {
type Object = ApplicationService;
fn with_object<R>(
&self,
path: &str,
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
) -> Option<R> {
if path != OBJECT_PATH {
return None;
}
let publication = PublishedObject::new(ApplicationService::new())
.expose(&self.catalog)
.expect("ApplicationService implements Catalog")
.expose(&self.audit)
.expect("ApplicationService implements Audit");
Some(operation(&publication))
}
fn authorize(
&self,
_: &str,
_: &ApplicationService,
_: &InterfaceRef,
operation: &str,
) -> bool {
operation != "restricted_status"
}
}
struct ApplicationService {
object_validator: Validator,
backend_connection: String,
}
impl ApplicationService {
fn new() -> Self {
Self {
object_validator: Validator::new(OBJECT_VALIDATOR),
backend_connection: "private://article-database".into(),
}
}
}
impl WipObject for ApplicationService {
fn name(&self) -> &str {
"article-service"
}
fn description(&self) -> Option<&str> {
Some("Article publication service")
}
fn reference(&self) -> Option<&str> {
Some("article-service-instance")
}
fn validator(&self) -> Option<&Validator> {
Some(&self.object_validator)
}
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
true
}
}
impl Catalog for ApplicationService {
fn publish(&self, request: PublishRequest) -> wip::OperationResult<PublishOutcome> {
if request.title.trim().is_empty() {
Ok(PublishOutcome::Rejected("a title is required".into()))
} else {
Ok(PublishOutcome::Published("article-1".into()))
}
}
fn status(&self) -> wip::OperationResult<String> {
Ok("catalog-ready".into())
}
fn backend_status(&self) -> wip::OperationResult<String> {
if self.backend_connection.starts_with("private://") {
Err(wip::HostError::new("backend unavailable"))
} else {
Ok("backend-ready".into())
}
}
fn restricted_status(&self) -> wip::OperationResult<String> {
Ok("authorization hook should prevent this call".into())
}
}
impl Audit for ApplicationService {
fn status(&self) -> wip::OperationResult<String> {
Ok("audit-ready".into())
}
}
impl Diagnostics for ApplicationService {
fn diagnostics(&self) -> wip::OperationResult<String> {
Ok("host-private".into())
}
}
+14
View File
@@ -0,0 +1,14 @@
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let report = wip_public_api_example::run()?;
println!(
"published {} interfaces; catalog={}, audit={}; domain={:?}; host={:?}",
report.published_interfaces.len(),
report.catalog_status,
report.audit_status,
report.rejected,
report.host_failure,
);
Ok(())
}
@@ -0,0 +1,239 @@
use std::collections::BTreeMap;
use wip_host::CallErrorKind;
use wip_interface::{Entry, JsonMember, JsonValue, WipType};
use wip_protocol::{INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, ProtocolErrorCode, Value};
use wip_public_api_example::{CatalogDefinition, PublishOutcome, PublishRequest, Visibility, run};
#[test]
fn public_crates_support_the_complete_qualified_end_to_end_scenario() {
let report = run().unwrap();
assert_eq!(report.object_name, "article-service");
assert_eq!(
report.object_reference.as_deref(),
Some("article-service-instance")
);
assert_eq!(
report.object_validator.as_deref(),
Some(b"object-v1".as_slice())
);
assert_eq!(
report.published_interfaces,
[
report.catalog_interface_reference.clone(),
report.audit_interface_reference.clone(),
],
"interfaces must retain explicit publication order"
);
assert_ne!(
report.catalog_interface_reference, report.audit_interface_reference,
"interfaces form an ordered set of distinct opaque references"
);
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
assert_eq!(
report.published,
PublishOutcome::Published("article-1".into())
);
assert_eq!(
report.rejected,
PublishOutcome::Rejected("a title is required".into())
);
assert_eq!(report.catalog_status, "catalog-ready");
assert_eq!(report.audit_status, "audit-ready");
}
#[test]
fn domain_host_permission_and_validator_failures_remain_distinct() {
let report = run().unwrap();
assert!(matches!(report.rejected, PublishOutcome::Rejected(_)));
assert_eq!(report.host_failure, CallErrorKind::Implementation);
assert_eq!(
report.protocol_failure.code,
ProtocolErrorCode::OperationOutcomeUnknown
);
assert_eq!(
report.permission_failure,
ProtocolErrorCode::PermissionDenied
);
assert_eq!(
report.validator_failure,
ProtocolErrorCode::ValidatorMismatch,
"validator recovery signals must not collapse to InvalidRequest"
);
}
#[test]
fn interface_mismatch_is_not_interface_not_found() {
let report = run().unwrap();
assert_eq!(
report.interface_mismatch,
ProtocolErrorCode::InterfaceMismatch
);
assert_eq!(
report.interface_not_found,
ProtocolErrorCode::InterfaceNotFound
);
assert_ne!(report.interface_mismatch, report.interface_not_found);
}
#[test]
fn invalid_path_keeps_canonical_failure_precedence() {
let report = run().unwrap();
assert_eq!(report.precedence_failure, ProtocolErrorCode::InvalidRequest);
assert_ne!(report.precedence_failure, report.validator_failure);
assert_ne!(report.precedence_failure, report.interface_mismatch);
}
#[test]
fn object_fields_keep_path_context_and_optional_ref_separate() {
// Listing every field makes this test fail to compile if a mandatory
// ObjectId is reintroduced into the canonical object DTO.
let object = Object {
name: "article".into(),
description: None,
interfaces: vec!["catalog-ref".into(), "audit-ref".into()],
r#ref: None,
validator: None,
};
object.validate_at_path("/library/article").unwrap();
assert_eq!(object.name, "article");
assert_eq!(object.r#ref, None);
assert_eq!(object.interfaces, ["catalog-ref", "audit-ref"]);
}
#[test]
fn interface_reference_is_observed_separately_from_descriptor_fields() {
// An exact destructuring pattern is compile-time coverage that the
// descriptor has no trait-name or opaque-reference `name` field.
let InterfaceDescriptor {
format,
documentation,
types,
operations,
} = CatalogDefinition::descriptor();
assert_eq!(format, INTERFACE_FORMAT_V1);
assert!(documentation.is_some());
assert!(!types.is_empty());
assert_eq!(
operations
.iter()
.map(|operation| operation.name.as_str())
.collect::<Vec<_>>(),
["publish", "status", "backend_status", "restricted_status"]
);
}
#[test]
fn application_record_enum_union_entry_and_json_use_schema_neutral_values() {
let request = PublishRequest {
title: "Canonical values".into(),
body: None,
source: Entry::new("/drafts/canonical-values").unwrap(),
visibility: Visibility::Public,
metadata: JsonValue::Object(vec![
JsonMember {
name: "tags".into(),
value: JsonValue::Array(vec![JsonValue::String("wip".into()), JsonValue::Null]),
},
JsonMember {
name: "ready".into(),
value: JsonValue::Boolean(true),
},
]),
};
let encoded = request.encode().unwrap();
assert_schema_neutral(&encoded);
let Value::Record(fields) = encoded else {
panic!("derived DTO record must use Value::Record")
};
assert_eq!(
fields.get("title"),
Some(&Value::String("Canonical values".into()))
);
assert!(!fields.contains_key("body"));
assert_eq!(
fields.get("source"),
Some(&Value::String("/drafts/canonical-values".into()))
);
assert_eq!(
fields.get("visibility"),
Some(&Value::String("Public".into()))
);
assert_eq!(
fields.get("metadata"),
Some(&Value::Record(BTreeMap::from([
("ready".into(), Value::Boolean(true)),
(
"tags".into(),
Value::List(vec![Value::String("wip".into()), Value::Unit])
),
])))
);
let outcome = PublishOutcome::Rejected("policy".into()).encode().unwrap();
assert_schema_neutral(&outcome);
assert_eq!(
outcome,
Value::Record(BTreeMap::from([
("$case".into(), Value::String("Rejected".into())),
("value".into(), Value::String("policy".into())),
]))
);
}
#[test]
fn entry_is_a_validated_canonical_absolute_path_string() {
let entry = Entry::new("/articles/one").unwrap();
assert_eq!(
entry.encode().unwrap(),
Value::String("/articles/one".into())
);
for invalid in [
"articles/one",
"/articles/",
"/articles//one",
"/articles/./one",
"/articles/../one",
] {
assert!(
Entry::new(invalid).is_err(),
"accepted invalid path {invalid}"
);
assert!(
Entry::decode(Value::String(invalid.into())).is_err(),
"decoded invalid path {invalid}"
);
}
}
fn assert_schema_neutral(value: &Value) {
// This exhaustive match is a compile-time regression guard: reintroducing
// semantic Entry/Enum/Union/Json variants makes the consumer non-exhaustive.
match value {
Value::Unit
| Value::Boolean(_)
| Value::Integer(_)
| Value::Number(_)
| Value::String(_)
| Value::Bytes(_) => {}
Value::Record(fields) => {
for value in fields.values() {
assert_schema_neutral(value);
}
}
Value::List(values) => {
for value in values {
assert_schema_neutral(value);
}
}
}
}
-3
View File
@@ -1,3 +0,0 @@
fn main() {
println!("Hello, world!");
}