Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f0552c48f |
Generated
+1
-3
@@ -270,11 +270,9 @@ name = "wip-protocol"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wip-public-api-example"
|
name = "wip-rs"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"wip-host",
|
|
||||||
"wip-interface",
|
|
||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+1
-6
@@ -9,14 +9,9 @@ members = [
|
|||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "wip-public-api-example"
|
name = "wip-rs"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "End-to-end example of the public WIP Rust APIs"
|
|
||||||
license = "MIT OR Apache-2.0"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
wip-host = { path = "crates/wip-host" }
|
|
||||||
wip-interface = { path = "crates/wip-interface" }
|
|
||||||
wip-protocol = { path = "crates/wip-protocol" }
|
wip-protocol = { path = "crates/wip-protocol" }
|
||||||
|
|||||||
@@ -2,65 +2,6 @@
|
|||||||
|
|
||||||
Rust building blocks for the Web Interface Protocol (WIP).
|
Rust building blocks for the Web Interface Protocol (WIP).
|
||||||
|
|
||||||
The repository currently provides a transport-independent protocol model, a
|
|
||||||
Rust interface-authoring facade, and a request-scoped host runtime. 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 `OperationCall`/`OperationResult`
|
|
||||||
without placing transport-specific types in descriptors or application traits.
|
|
||||||
|
|
||||||
## End-to-end example
|
|
||||||
|
|
||||||
[`src/lib.rs`](src/lib.rs) is the complete public-API example and
|
|
||||||
[`src/main.rs`](src/main.rs) runs it. It demonstrates all of the following:
|
|
||||||
|
|
||||||
1. public application DTOs derived as `WipType` records and unions;
|
|
||||||
2. two public traits declared with `#[wip::interface]`;
|
|
||||||
3. a private host struct implementing both traits;
|
|
||||||
4. explicit publication of both interfaces on one object;
|
|
||||||
5. registry observation and validation of generated descriptors;
|
|
||||||
6. calls made with interface references, operation names, and `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. a domain rejection returned as data and a backend failure returned as a host
|
|
||||||
error.
|
|
||||||
|
|
||||||
Run it inside the development shell:
|
|
||||||
|
|
||||||
```console
|
|
||||||
nix develop
|
|
||||||
cargo run --package wip-public-api-example
|
|
||||||
```
|
|
||||||
|
|
||||||
The normal integration test is in [`tests/end_to_end.rs`](tests/end_to_end.rs).
|
|
||||||
Unit tests beside the example additionally cover every host dispatch failure,
|
|
||||||
invalid arguments and results, interface membership, validators, and
|
|
||||||
same-named operations.
|
|
||||||
|
|
||||||
## Interface authoring
|
## Interface authoring
|
||||||
|
|
||||||
Applications depend on `wip-interface`, normally imported as `wip`:
|
Applications depend on `wip-interface`, normally imported as `wip`:
|
||||||
@@ -89,31 +30,12 @@ pub trait Messenger {
|
|||||||
```
|
```
|
||||||
|
|
||||||
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
||||||
users do not import `wip-interface-macros` or generated private support symbols.
|
users do not import `wip-interface-macros` directly. The generated
|
||||||
The generated `MessengerDefinition` constructs an `InterfaceDescriptor`,
|
`MessengerDefinition` constructs an `InterfaceDescriptor`, decodes named
|
||||||
decodes named arguments, encodes results, validates both boundaries, and
|
arguments, encodes results, validates both boundaries, and provides typed
|
||||||
provides typed dispatch for any `T: Messenger`.
|
dispatch for any `T: Messenger`.
|
||||||
|
|
||||||
### Supported Rust syntax
|
### Type mapping
|
||||||
|
|
||||||
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 enums whose
|
|
||||||
variants each contain 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;
|
|
||||||
mixed/named-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 |
|
| Rust | Protocol |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -123,21 +45,27 @@ are compile-fail tested under `crates/wip-interface/tests/ui`.
|
|||||||
| `f32`, `f64` | finite number |
|
| `f32`, `f64` | finite number |
|
||||||
| `String` | string |
|
| `String` | string |
|
||||||
| `wip::Bytes` | bytes |
|
| `wip::Bytes` | bytes |
|
||||||
| `wip::JsonValue` | JSON |
|
| `wip::wip_protocol::JsonValue` | JSON |
|
||||||
| `wip::Entry<K, V>` | entry |
|
| `wip::Entry<K, V>` | entry |
|
||||||
| `Vec<T>` | list |
|
| `Vec<T>` | list |
|
||||||
| named-field `#[derive(wip::WipType)]` struct | named record |
|
| named-field `#[derive(wip::WipType)]` struct | named record |
|
||||||
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
||||||
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
||||||
|
|
||||||
`Option<T>` means that a direct DTO field or operation parameter may be
|
`Option<T>` is accepted only for a direct DTO field or operation parameter and
|
||||||
omitted; it is not protocol null. JSON null remains available inside
|
means that the named value may be omitted. It is not protocol null. Domain
|
||||||
`wip::JsonValue`.
|
failures are modeled in the application result (usually a derived union) and
|
||||||
|
returned through `Ok`; `wip::HostError` is only for host/runtime failures.
|
||||||
|
|
||||||
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
||||||
section documents the return declaration; text before that section documents
|
section documents the return declaration; text before that section documents
|
||||||
the operation itself.
|
the operation itself.
|
||||||
|
|
||||||
|
The supported interface slice is deliberately non-generic: public traits,
|
||||||
|
`&self`, named parameters, and `OperationResult<T>`. Generic traits or methods,
|
||||||
|
associated items, custom lifetimes, inheritance, default method bodies, and
|
||||||
|
other receiver forms are rejected at their source spans.
|
||||||
|
|
||||||
## Host publication and dispatch
|
## Host publication and dispatch
|
||||||
|
|
||||||
Applications use `wip-host` to register generated definitions and explicitly
|
Applications use `wip-host` to register generated definitions and explicitly
|
||||||
@@ -156,38 +84,16 @@ let protocol_object = published.protocol_object();
|
|||||||
interface trait. Implementing a trait does not expose it automatically, empty
|
interface trait. Implementing a trait does not expose it automatically, empty
|
||||||
interface sets are valid, insertion order is preserved, and duplicate
|
interface sets are valid, insertion order is preserved, and duplicate
|
||||||
references are rejected. Registry references are opaque; descriptor names and
|
references are rejected. Registry references are opaque; descriptor names and
|
||||||
Rust type names are not used as independent wire identity.
|
Rust type names are not used as wire identity.
|
||||||
|
|
||||||
Dispatch is qualified by interface reference and operation name. The host
|
Dispatch is qualified by interface reference and operation name. The host checks
|
||||||
checks current object identity and validator policy, current interface
|
current object identity and validator policy, current interface membership,
|
||||||
membership, interface validator, descriptor operation, arguments, and result
|
interface validator, descriptor operation, arguments, and result while retaining
|
||||||
while retaining the selected object and registered artifact. Host-private
|
the selected object and registered artifact. Host-private fields and backend
|
||||||
fields and backend handles are never projected by `WipObject`.
|
handles are never projected by `WipObject`.
|
||||||
|
|
||||||
Application domain failures belong in a derived result union and are returned
|
|
||||||
through `Ok`. `wip::HostError` is reserved for runtime/backend failures. Invalid
|
|
||||||
arguments are rejected before invocation; malformed encoded results are
|
|
||||||
rejected as internal host failures and never returned as application data.
|
|
||||||
|
|
||||||
Providers remain responsible for backend atomicity. Enter a transaction, lock,
|
Providers remain responsible for backend atomicity. Enter a transaction, lock,
|
||||||
stable-handle scope, or conditional-update primitive before constructing and
|
stable-handle scope, or conditional-update primitive before constructing and
|
||||||
dispatching the request-scoped `PublishedObject`, and retain it until dispatch
|
dispatching the request-scoped `PublishedObject`, and retain it until dispatch
|
||||||
returns. The runtime never validates one object and then resolves a second
|
returns. The runtime never validates one object and then resolves a second
|
||||||
snapshot, but it cannot make an arbitrary external backend atomic by itself.
|
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 clippy --workspace --all-targets -- -D warnings
|
|
||||||
```
|
|
||||||
|
|
||||||
`cargo test --workspace --all-targets` includes the public example integration
|
|
||||||
test, runtime failure tests, and `trybuild` compile-fail suites. Run
|
|
||||||
`cargo test --workspace --doc` when validating the checked rustdoc examples
|
|
||||||
separately.
|
|
||||||
|
|||||||
@@ -208,18 +208,6 @@ impl InterfaceRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves a transport-provided opaque reference string in this registry.
|
|
||||||
///
|
|
||||||
/// The returned value is registry-scoped and suitable for observation or a
|
|
||||||
/// qualified [`CallRequest`]. Unknown or foreign references return `None`;
|
|
||||||
/// constructing arbitrary `InterfaceRef` values is intentionally not part of
|
|
||||||
/// the public API.
|
|
||||||
#[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 the descriptor and optional validator for an opaque reference.
|
/// Observes the descriptor and optional validator for an opaque reference.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn observe(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
|
pub fn observe(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
|
||||||
|
|||||||
@@ -163,11 +163,6 @@ fn registry_exposes_opaque_validated_descriptor_observations() {
|
|||||||
let reader = registry.register(ReaderDefinition, None).unwrap();
|
let reader = registry.register(ReaderDefinition, None).unwrap();
|
||||||
|
|
||||||
assert_ne!(reader.reference().as_str(), "Reader");
|
assert_ne!(reader.reference().as_str(), "Reader");
|
||||||
assert_eq!(
|
|
||||||
registry.resolve(reader.reference().as_str()).as_ref(),
|
|
||||||
Some(reader.reference())
|
|
||||||
);
|
|
||||||
assert!(registry.resolve("wip-interface:unknown:0").is_none());
|
|
||||||
let observation = registry.observe(reader.reference()).unwrap();
|
let observation = registry.observe(reader.reference()).unwrap();
|
||||||
assert_eq!(observation.reference, *reader.reference());
|
assert_eq!(observation.reference, *reader.reference());
|
||||||
assert_eq!(observation.descriptor.name, reader.reference().as_str());
|
assert_eq!(observation.descriptor.name, reader.reference().as_str());
|
||||||
@@ -179,11 +174,6 @@ fn registry_exposes_opaque_validated_descriptor_observations() {
|
|||||||
let mut other_registry = InterfaceRegistry::new();
|
let mut other_registry = InterfaceRegistry::new();
|
||||||
let other_reader = other_registry.register(ReaderDefinition, None).unwrap();
|
let other_reader = other_registry.register(ReaderDefinition, None).unwrap();
|
||||||
assert_ne!(reader.reference(), other_reader.reference());
|
assert_ne!(reader.reference(), other_reader.reference());
|
||||||
assert!(
|
|
||||||
registry
|
|
||||||
.resolve(other_reader.reference().as_str())
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,10 +1,4 @@
|
|||||||
//! Procedural macros backing the public `wip-interface` authoring facade.
|
//! Procedural macros backing the public `wip-interface` authoring facade.
|
||||||
//!
|
|
||||||
//! This is an implementation crate. Applications should depend on
|
|
||||||
//! `wip-interface`, which re-exports both macros alongside the traits and types
|
|
||||||
//! used by their generated code.
|
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
@@ -476,18 +470,13 @@ fn parse_operation_result(output: &ReturnType) -> syn::Result<Type> {
|
|||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
let result = types.next().cloned();
|
let result = types.next().cloned();
|
||||||
if arguments.args.len() != 1 || types.next().is_some() {
|
if arguments.args.len() != 1 || result.is_none() || types.next().is_some() {
|
||||||
return Err(Error::new_spanned(
|
return Err(Error::new_spanned(
|
||||||
arguments,
|
arguments,
|
||||||
"`OperationResult` must have exactly one application result type",
|
"`OperationResult` must have exactly one application result type",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let result = result.ok_or_else(|| {
|
let result = result.expect("checked above");
|
||||||
Error::new_spanned(
|
|
||||||
arguments,
|
|
||||||
"`OperationResult` must have exactly one application result type",
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
if direct_option(&result)?.is_some() || contains_option(&result) {
|
if direct_option(&result)?.is_some() || contains_option(&result) {
|
||||||
return Err(Error::new_spanned(
|
return Err(Error::new_spanned(
|
||||||
result,
|
result,
|
||||||
@@ -501,13 +490,8 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
|||||||
let arguments_ident = &operation.arguments_ident;
|
let arguments_ident = &operation.arguments_ident;
|
||||||
let fields = operation.parameters.iter().map(|parameter| {
|
let fields = operation.parameters.iter().map(|parameter| {
|
||||||
let ident = ¶meter.ident;
|
let ident = ¶meter.ident;
|
||||||
let name = ¶meter.name;
|
|
||||||
let ty = parameter_rust_type(parameter);
|
let ty = parameter_rust_type(parameter);
|
||||||
let documentation = format!("Decoded `{name}` operation argument.");
|
quote!(pub #ident: #ty)
|
||||||
quote!(
|
|
||||||
#[doc = #documentation]
|
|
||||||
pub #ident: #ty
|
|
||||||
)
|
|
||||||
});
|
});
|
||||||
let decoders = operation.parameters.iter().map(|parameter| {
|
let decoders = operation.parameters.iter().map(|parameter| {
|
||||||
let ident = ¶meter.ident;
|
let ident = ¶meter.ident;
|
||||||
@@ -714,12 +698,7 @@ fn derive_record(
|
|||||||
let mut parsed_fields = Vec::new();
|
let mut parsed_fields = Vec::new();
|
||||||
let mut names = HashSet::new();
|
let mut names = HashSet::new();
|
||||||
for field in fields {
|
for field in fields {
|
||||||
let Some(field_ident) = field.ident.clone() else {
|
let field_ident = field.ident.clone().expect("named fields have identifiers");
|
||||||
return Err(Error::new_spanned(
|
|
||||||
field,
|
|
||||||
"`WipType` record fields must be named",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
let name = source_name(&field_ident);
|
let name = source_name(&field_ident);
|
||||||
if !names.insert(name.clone()) {
|
if !names.insert(name.clone()) {
|
||||||
return Err(Error::new(
|
return Err(Error::new(
|
||||||
@@ -1005,17 +984,12 @@ fn derive_union_enum(
|
|||||||
let mut variants = Vec::new();
|
let mut variants = Vec::new();
|
||||||
for variant in &data.variants {
|
for variant in &data.variants {
|
||||||
let Fields::Unnamed(fields) = &variant.fields else {
|
let Fields::Unnamed(fields) = &variant.fields else {
|
||||||
return Err(Error::new_spanned(
|
unreachable!("enum shape was checked before union generation");
|
||||||
variant,
|
|
||||||
"a `WipType` union variant must contain exactly one unnamed field",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
let Some(field) = fields.unnamed.first() else {
|
|
||||||
return Err(Error::new_spanned(
|
|
||||||
fields,
|
|
||||||
"a `WipType` union variant must contain exactly one unnamed field",
|
|
||||||
));
|
|
||||||
};
|
};
|
||||||
|
let field = fields
|
||||||
|
.unnamed
|
||||||
|
.first()
|
||||||
|
.expect("union variants have one field");
|
||||||
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
||||||
return Err(Error::new_spanned(
|
return Err(Error::new_spanned(
|
||||||
&field.ty,
|
&field.ty,
|
||||||
|
|||||||
@@ -48,21 +48,6 @@
|
|||||||
//! an application return enum/union and is returned as `Ok(value)`.
|
//! an application return enum/union and is returned as `Ok(value)`.
|
||||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||||
//!
|
|
||||||
//! # 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, and all-single-payload enums.
|
|
||||||
//!
|
|
||||||
//! 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;
|
|
||||||
//! mixed or named-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)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
@@ -634,6 +619,7 @@ pub mod __private {
|
|||||||
/// Decoder for a protocol record or operation's named argument collection.
|
/// Decoder for a protocol record or operation's named argument collection.
|
||||||
pub struct RecordDecoder {
|
pub struct RecordDecoder {
|
||||||
fields: Vec<NamedValue>,
|
fields: Vec<NamedValue>,
|
||||||
|
seen: HashSet<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RecordDecoder {
|
impl RecordDecoder {
|
||||||
@@ -647,7 +633,7 @@ pub mod __private {
|
|||||||
.at(field.name.clone()));
|
.at(field.name.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Self { fields })
|
Ok(Self { fields, seen })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decodes a required field.
|
/// Decodes a required field.
|
||||||
@@ -680,5 +666,11 @@ pub mod __private {
|
|||||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
let index = self.fields.iter().position(|field| field.name == name)?;
|
||||||
Some(self.fields.remove(index).value)
|
Some(self.fields.remove(index).value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the set of names supplied to this decoder.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn supplied_names(&self) -> &HashSet<String> {
|
||||||
|
&self.seen
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
use wip_interface::interface;
|
|
||||||
|
|
||||||
#[interface]
|
|
||||||
pub trait AsyncOperation {
|
|
||||||
async fn status(&self) -> wip_interface::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
error: async operations are not supported
|
|
||||||
--> tests/ui/async_operation.rs:5:5
|
|
||||||
|
|
|
||||||
5 | async fn status(&self) -> wip_interface::OperationResult<String>;
|
|
||||||
| ^^^^^
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
use wip_interface::interface;
|
|
||||||
|
|
||||||
#[interface]
|
|
||||||
pub trait DefaultMethod {
|
|
||||||
fn status(&self) -> wip_interface::OperationResult<String> {
|
|
||||||
Ok(String::new())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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 | | }
|
|
||||||
| |_____^
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
use wip_interface::WipType;
|
|
||||||
|
|
||||||
#[derive(WipType)]
|
|
||||||
struct GenericDto<T> {
|
|
||||||
value: T,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
error: generic DTOs are not supported by `WipType`
|
|
||||||
--> tests/ui/generic_dto.rs:4:18
|
|
||||||
|
|
|
||||||
4 | struct GenericDto<T> {
|
|
||||||
| ^^^
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
use wip_interface::WipType;
|
|
||||||
|
|
||||||
#[derive(WipType)]
|
|
||||||
struct NestedOption {
|
|
||||||
values: Vec<Option<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
error: `Option<T>` must appear directly as the DTO field type
|
|
||||||
--> tests/ui/nested_option.rs:5:13
|
|
||||||
|
|
|
||||||
5 | values: Vec<Option<String>>,
|
|
||||||
| ^^^^^^^^^^^^^^^^^^^
|
|
||||||
@@ -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,44 @@ impl Display for ValidationError {
|
|||||||
|
|
||||||
impl Error for ValidationError {}
|
impl Error for ValidationError {}
|
||||||
|
|
||||||
/// Stable category of an error returned by a protocol host runtime.
|
/// Stable protocol failure code returned by a host or produced by a client.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ProtocolErrorCategory {
|
pub enum ProtocolErrorCode {
|
||||||
/// The request is structurally invalid.
|
/// The request is structurally invalid.
|
||||||
InvalidRequest,
|
InvalidRequest,
|
||||||
/// The target object is not published.
|
/// The target object is not published.
|
||||||
ObjectNotFound,
|
NotFound,
|
||||||
/// The target interface is not implemented by the object.
|
/// The interface reference is not currently published.
|
||||||
InterfaceNotFound,
|
InterfaceNotFound,
|
||||||
/// The target operation is not declared by the interface.
|
/// The selected interface is not on the current object.
|
||||||
|
InterfaceMismatch,
|
||||||
|
/// The selected operation is not declared by the current interface.
|
||||||
OperationNotFound,
|
OperationNotFound,
|
||||||
/// Supplied operation arguments are invalid.
|
/// Supplied operation arguments are invalid.
|
||||||
InvalidArguments,
|
InvalidArguments,
|
||||||
/// The implementation rejected the call for a domain reason.
|
/// A host result does not satisfy the declaration.
|
||||||
OperationFailed,
|
InvalidResult,
|
||||||
|
/// 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.
|
||||||
|
ResourceLimitExceeded,
|
||||||
/// The host encountered an internal failure.
|
/// The host encountered an internal failure.
|
||||||
Internal,
|
Internal,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport-independent protocol failure returned by a host runtime.
|
/// 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,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,32 @@
|
|||||||
//! 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 failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
||||||
|
//!
|
||||||
|
//! 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 +35,33 @@ mod model;
|
|||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub use error::{
|
pub use error::{
|
||||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCategory, ValidationError,
|
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ValidationError,
|
||||||
ValidationErrorKind, ValueKind,
|
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;
|
||||||
|
|||||||
+294
-253
@@ -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,219 @@ 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.
|
||||||
|
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`.
|
||||||
|
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.
|
||||||
|
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`.
|
||||||
|
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
-627
@@ -1,627 +0,0 @@
|
|||||||
//! End-to-end use of the public WIP protocol, interface, and host APIs.
|
|
||||||
//!
|
|
||||||
//! This workspace package is deliberately separate from the three library
|
|
||||||
//! crates. It defines application DTOs and interfaces with `wip-interface`,
|
|
||||||
//! keeps its implementation private, publishes that implementation with
|
|
||||||
//! `wip-host`, and crosses the call boundary only with `wip-protocol` values.
|
|
||||||
//!
|
|
||||||
//! The complete scenario can be run as a normal binary or called directly:
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//! let report = wip_public_api_example::run()?;
|
|
||||||
//!
|
|
||||||
//! assert_eq!(report.published_interfaces.len(), 2);
|
|
||||||
//! assert_eq!(report.catalog_status, "catalog-ready");
|
|
||||||
//! assert_eq!(report.audit_status, "audit-ready");
|
|
||||||
//! assert_eq!(
|
|
||||||
//! report.host_failure,
|
|
||||||
//! wip_host::CallErrorKind::Implementation,
|
|
||||||
//! );
|
|
||||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
|
||||||
|
|
||||||
use std::error::Error;
|
|
||||||
use std::io;
|
|
||||||
|
|
||||||
use wip_host::{
|
|
||||||
CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget, PublishedObject,
|
|
||||||
Validator, WipObject,
|
|
||||||
};
|
|
||||||
use wip_interface as wip;
|
|
||||||
use wip_interface::WipType;
|
|
||||||
use wip_protocol::{
|
|
||||||
InterfaceObservation, NamedValue, ObjectId, OperationOutcome, OperationResult, OperationTarget,
|
|
||||||
};
|
|
||||||
|
|
||||||
const OBJECT_ID: &str = "article-service";
|
|
||||||
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
|
||||||
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
|
|
||||||
|
|
||||||
/// An application-owned request DTO mapped to a protocol record.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, 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>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The application domain result of a publication attempt.
|
|
||||||
///
|
|
||||||
/// Rejection is an ordinary typed result. It is intentionally distinct from a
|
|
||||||
/// host or backend failure, which uses [`wip::HostError`].
|
|
||||||
#[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.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A catalog status label.
|
|
||||||
fn status(&self) -> wip::OperationResult<String>;
|
|
||||||
|
|
||||||
/// Demonstrates a host/backend failure rather than a domain result.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A backend status only when the host can reach it.
|
|
||||||
fn backend_status(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Audit operations exposed by the same object.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait Audit {
|
|
||||||
/// Returns the audit-qualified status.
|
|
||||||
///
|
|
||||||
/// This deliberately has the same operation name as [`Catalog::status`].
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// An audit status label.
|
|
||||||
fn status(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A registered but deliberately unexposed interface used to demonstrate that
|
|
||||||
/// Rust trait implementation does not imply protocol membership.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait Diagnostics {
|
|
||||||
/// Returns host-private diagnostics when the interface is explicitly exposed.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A diagnostic label.
|
|
||||||
fn diagnostics(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Observable outcomes from the complete public-API scenario.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct DemoReport {
|
|
||||||
/// Opaque interface references published by the object, in exposure order.
|
|
||||||
pub published_interfaces: Vec<String>,
|
|
||||||
/// Descriptor identity observed for the catalog interface.
|
|
||||||
pub catalog_descriptor: String,
|
|
||||||
/// Descriptor identity observed for the audit interface.
|
|
||||||
pub audit_descriptor: 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-level operation result built from the host failure.
|
|
||||||
pub protocol_failure: OperationResult,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs the complete end-to-end example.
|
|
||||||
///
|
|
||||||
/// The function registers and observes generated descriptors, explicitly
|
|
||||||
/// exposes two interfaces on one host-private object, validates the resulting
|
|
||||||
/// protocol observation, dispatches interface-qualified calls using named
|
|
||||||
/// [`wip_protocol::Value`] arguments, decodes validated values back to
|
|
||||||
/// application types, and keeps a domain rejection distinct from a host
|
|
||||||
/// failure.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
///
|
|
||||||
/// Returns an error if registration, publication, observation validation,
|
|
||||||
/// 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 publication = PublishedObject::new(ApplicationService::new())
|
|
||||||
.expose(&catalog)?
|
|
||||||
.expose(&audit)?;
|
|
||||||
let object = publication.protocol_object();
|
|
||||||
|
|
||||||
// Model a transport/provider that retained only the protocol object's
|
|
||||||
// opaque strings, then resolved them back through the registry's public API.
|
|
||||||
let catalog_wire_reference = object
|
|
||||||
.interfaces
|
|
||||||
.first()
|
|
||||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?;
|
|
||||||
let audit_wire_reference = object
|
|
||||||
.interfaces
|
|
||||||
.get(1)
|
|
||||||
.ok_or_else(|| io::Error::other("audit interface was not published"))?;
|
|
||||||
let catalog_reference = registry
|
|
||||||
.resolve(catalog_wire_reference)
|
|
||||||
.ok_or_else(|| io::Error::other("published catalog reference did not resolve"))?;
|
|
||||||
let audit_reference = registry
|
|
||||||
.resolve(audit_wire_reference)
|
|
||||||
.ok_or_else(|| io::Error::other("published audit reference did not resolve"))?;
|
|
||||||
let catalog_observation = registry
|
|
||||||
.observe(&catalog_reference)
|
|
||||||
.ok_or_else(|| io::Error::other("registered catalog descriptor was not observable"))?;
|
|
||||||
let audit_observation = registry
|
|
||||||
.observe(&audit_reference)
|
|
||||||
.ok_or_else(|| io::Error::other("registered audit descriptor was not observable"))?;
|
|
||||||
|
|
||||||
InterfaceObservation {
|
|
||||||
object: object.clone(),
|
|
||||||
descriptors: vec![
|
|
||||||
catalog_observation.descriptor.clone(),
|
|
||||||
audit_observation.descriptor.clone(),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
.validate()?;
|
|
||||||
|
|
||||||
let published = dispatch_publish(
|
|
||||||
&publication,
|
|
||||||
&catalog_observation.reference,
|
|
||||||
PublishRequest {
|
|
||||||
title: "Public APIs".into(),
|
|
||||||
body: Some("protocol values in, validated values out".into()),
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let rejected = dispatch_publish(
|
|
||||||
&publication,
|
|
||||||
&catalog_observation.reference,
|
|
||||||
PublishRequest {
|
|
||||||
title: String::new(),
|
|
||||||
body: None,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let catalog_status = dispatch_string(
|
|
||||||
&publication,
|
|
||||||
request(
|
|
||||||
catalog_observation.reference.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
),
|
|
||||||
"catalog status",
|
|
||||||
)?;
|
|
||||||
let audit_status = dispatch_string(
|
|
||||||
&publication,
|
|
||||||
request(audit_observation.reference.clone(), None, "status", vec![]),
|
|
||||||
"audit status",
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let host_error = match publication.dispatch(request(
|
|
||||||
catalog_observation.reference.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"backend_status",
|
|
||||||
vec![],
|
|
||||||
)) {
|
|
||||||
Ok(_) => {
|
|
||||||
return Err(io::Error::other(
|
|
||||||
"the deliberately unavailable example backend unexpectedly succeeded",
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
Err(error) => error,
|
|
||||||
};
|
|
||||||
if host_error.kind() != CallErrorKind::Implementation {
|
|
||||||
return Err(io::Error::other(format!(
|
|
||||||
"unexpected host failure kind: {:?}",
|
|
||||||
host_error.kind()
|
|
||||||
))
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let protocol_error = host_error.protocol_error();
|
|
||||||
let protocol_failure = OperationResult {
|
|
||||||
target: OperationTarget {
|
|
||||||
object: ObjectId(OBJECT_ID.into()),
|
|
||||||
interface: catalog_observation.reference.as_str().into(),
|
|
||||||
operation: "backend_status".into(),
|
|
||||||
},
|
|
||||||
outcome: OperationOutcome::Failed(protocol_error),
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(DemoReport {
|
|
||||||
published_interfaces: object.interfaces,
|
|
||||||
catalog_descriptor: catalog_observation.descriptor.name,
|
|
||||||
audit_descriptor: audit_observation.descriptor.name,
|
|
||||||
published,
|
|
||||||
rejected,
|
|
||||||
catalog_status,
|
|
||||||
audit_status,
|
|
||||||
host_failure: host_error.kind(),
|
|
||||||
protocol_failure,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_publish(
|
|
||||||
publication: &PublishedObject<ApplicationService>,
|
|
||||||
catalog: &InterfaceRef,
|
|
||||||
request_value: PublishRequest,
|
|
||||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
|
||||||
let encoded_request = request_value.encode()?;
|
|
||||||
let result = publication.dispatch(request(
|
|
||||||
catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"publish",
|
|
||||||
vec![NamedValue {
|
|
||||||
name: "request".into(),
|
|
||||||
value: encoded_request,
|
|
||||||
}],
|
|
||||||
))?;
|
|
||||||
let value = result
|
|
||||||
.value
|
|
||||||
.ok_or_else(|| io::Error::other("publish returned no application value"))?;
|
|
||||||
Ok(PublishOutcome::decode(value)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_string(
|
|
||||||
publication: &PublishedObject<ApplicationService>,
|
|
||||||
request: CallRequest,
|
|
||||||
context: &str,
|
|
||||||
) -> Result<String, Box<dyn Error>> {
|
|
||||||
let result = publication.dispatch(request)?;
|
|
||||||
let value = result
|
|
||||||
.value
|
|
||||||
.ok_or_else(|| io::Error::other(format!("{context} returned no value")))?;
|
|
||||||
Ok(String::decode(value)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request(
|
|
||||||
interface: InterfaceRef,
|
|
||||||
interface_validator: Option<Validator>,
|
|
||||||
operation: &str,
|
|
||||||
arguments: Vec<NamedValue>,
|
|
||||||
) -> CallRequest {
|
|
||||||
CallRequest {
|
|
||||||
object: ObjectId(OBJECT_ID.into()),
|
|
||||||
object_validator: Some(Validator::new(OBJECT_VALIDATOR)),
|
|
||||||
interface: InterfaceTarget {
|
|
||||||
reference: interface,
|
|
||||||
validator: interface_validator,
|
|
||||||
},
|
|
||||||
operation: operation.into(),
|
|
||||||
arguments,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 id(&self) -> ObjectId {
|
|
||||||
ObjectId(OBJECT_ID.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validator(&self) -> Option<&Validator> {
|
|
||||||
Some(&self.object_validator)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn requires_validator(&self) -> 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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use wip_host::CallError;
|
|
||||||
use wip_interface::{CodecError, TypeDeclaration, TypeExpr};
|
|
||||||
use wip_protocol::{ProtocolErrorCategory, Value};
|
|
||||||
|
|
||||||
/// A deliberately inconsistent custom codec used to prove result validation.
|
|
||||||
pub struct InvalidValue;
|
|
||||||
|
|
||||||
impl WipType for InvalidValue {
|
|
||||||
fn type_expr() -> TypeExpr {
|
|
||||||
TypeExpr::String
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
|
||||||
|
|
||||||
fn encode(self) -> Result<Value, CodecError> {
|
|
||||||
Ok(Value::Integer(7))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode(_: Value) -> Result<Self, CodecError> {
|
|
||||||
Ok(Self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test-only interface whose custom codec emits an invalid result.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait BrokenResult {
|
|
||||||
/// Returns a value that violates its declared protocol type.
|
|
||||||
fn broken_result(&self) -> wip::OperationResult<InvalidValue>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BrokenResult for ApplicationService {
|
|
||||||
fn broken_result(&self) -> wip::OperationResult<InvalidValue> {
|
|
||||||
Ok(InvalidValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Fixture {
|
|
||||||
publication: PublishedObject<ApplicationService>,
|
|
||||||
catalog: InterfaceRef,
|
|
||||||
audit: InterfaceRef,
|
|
||||||
diagnostics: InterfaceRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fixture() -> Fixture {
|
|
||||||
let mut registry = InterfaceRegistry::new();
|
|
||||||
let catalog = registry
|
|
||||||
.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))
|
|
||||||
.unwrap();
|
|
||||||
let audit = registry.register(AuditDefinition, None).unwrap();
|
|
||||||
let diagnostics = registry.register(DiagnosticsDefinition, None).unwrap();
|
|
||||||
let publication = PublishedObject::new(ApplicationService::new())
|
|
||||||
.expose(&catalog)
|
|
||||||
.unwrap()
|
|
||||||
.expose(&audit)
|
|
||||||
.unwrap();
|
|
||||||
Fixture {
|
|
||||||
publication,
|
|
||||||
catalog: catalog.reference().clone(),
|
|
||||||
audit: audit.reference().clone(),
|
|
||||||
diagnostics: diagnostics.reference().clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_failure(error: CallError, kind: CallErrorKind, category: ProtocolErrorCategory) {
|
|
||||||
assert_eq!(error.kind(), kind);
|
|
||||||
assert_eq!(error.protocol_error().category, category);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn interface_membership_and_same_name_operations_are_qualified() {
|
|
||||||
let fixture = fixture();
|
|
||||||
|
|
||||||
let catalog = dispatch_string(
|
|
||||||
&fixture.publication,
|
|
||||||
request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
),
|
|
||||||
"catalog status",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let audit = dispatch_string(
|
|
||||||
&fixture.publication,
|
|
||||||
request(fixture.audit.clone(), None, "status", vec![]),
|
|
||||||
"audit status",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(catalog, "catalog-ready");
|
|
||||||
assert_eq!(audit, "audit-ready");
|
|
||||||
|
|
||||||
let not_exposed = fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(fixture.diagnostics, None, "diagnostics", vec![]))
|
|
||||||
.unwrap_err();
|
|
||||||
assert_failure(
|
|
||||||
not_exposed,
|
|
||||||
CallErrorKind::InterfaceMismatch,
|
|
||||||
ProtocolErrorCategory::InterfaceNotFound,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_host_precondition_and_dispatch_failure_is_typed() {
|
|
||||||
let fixture = fixture();
|
|
||||||
|
|
||||||
let mut wrong_object = request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
wrong_object.object = ObjectId("other-object".into());
|
|
||||||
assert_failure(
|
|
||||||
fixture.publication.dispatch(wrong_object).unwrap_err(),
|
|
||||||
CallErrorKind::ObjectNotFound,
|
|
||||||
ProtocolErrorCategory::ObjectNotFound,
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut missing_object_validator = request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
missing_object_validator.object_validator = None;
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(missing_object_validator)
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::ValidatorRequired,
|
|
||||||
ProtocolErrorCategory::InvalidRequest,
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut stale_object_validator = request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
stale_object_validator.object_validator = Some(Validator::new(b"stale-object"));
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(stale_object_validator)
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::ValidatorMismatch,
|
|
||||||
ProtocolErrorCategory::InvalidRequest,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(fixture.catalog.clone(), None, "status", vec![]))
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::InterfaceValidatorRequired,
|
|
||||||
ProtocolErrorCategory::InvalidRequest,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(b"stale-interface")),
|
|
||||||
"status",
|
|
||||||
vec![],
|
|
||||||
))
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::InterfaceValidatorMismatch,
|
|
||||||
ProtocolErrorCategory::InvalidRequest,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"missing",
|
|
||||||
vec![],
|
|
||||||
))
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::OperationNotFound,
|
|
||||||
ProtocolErrorCategory::OperationNotFound,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(
|
|
||||||
fixture.catalog.clone(),
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"publish",
|
|
||||||
vec![NamedValue {
|
|
||||||
name: "request".into(),
|
|
||||||
value: Value::String("not a record".into()),
|
|
||||||
}],
|
|
||||||
))
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::InvalidArguments,
|
|
||||||
ProtocolErrorCategory::InvalidArguments,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_failure(
|
|
||||||
fixture
|
|
||||||
.publication
|
|
||||||
.dispatch(request(
|
|
||||||
fixture.catalog,
|
|
||||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
|
||||||
"backend_status",
|
|
||||||
vec![],
|
|
||||||
))
|
|
||||||
.unwrap_err(),
|
|
||||||
CallErrorKind::Implementation,
|
|
||||||
ProtocolErrorCategory::Internal,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_implementation_result_never_crosses_the_host_boundary() {
|
|
||||||
let mut registry = InterfaceRegistry::new();
|
|
||||||
let broken = registry.register(BrokenResultDefinition, None).unwrap();
|
|
||||||
let publication = PublishedObject::new(ApplicationService::new())
|
|
||||||
.expose(&broken)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let error = publication
|
|
||||||
.dispatch(request(
|
|
||||||
broken.reference().clone(),
|
|
||||||
None,
|
|
||||||
"broken_result",
|
|
||||||
vec![],
|
|
||||||
))
|
|
||||||
.unwrap_err();
|
|
||||||
assert_failure(
|
|
||||||
error,
|
|
||||||
CallErrorKind::InvalidResult,
|
|
||||||
ProtocolErrorCategory::Internal,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-13
@@ -1,14 +1,3 @@
|
|||||||
use std::error::Error;
|
fn main() {
|
||||||
|
println!("Hello, world!");
|
||||||
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(())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
use wip_host::CallErrorKind;
|
|
||||||
use wip_protocol::{OperationOutcome, ProtocolErrorCategory};
|
|
||||||
use wip_public_api_example::{PublishOutcome, run};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn public_crates_support_the_complete_end_to_end_scenario() {
|
|
||||||
let report = run().unwrap();
|
|
||||||
|
|
||||||
assert_eq!(report.published_interfaces.len(), 2);
|
|
||||||
assert_eq!(report.catalog_descriptor, report.published_interfaces[0]);
|
|
||||||
assert_eq!(report.audit_descriptor, report.published_interfaces[1]);
|
|
||||||
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");
|
|
||||||
assert_eq!(report.host_failure, CallErrorKind::Implementation);
|
|
||||||
assert!(matches!(
|
|
||||||
report.protocol_failure.outcome,
|
|
||||||
OperationOutcome::Failed(error) if error.category == ProtocolErrorCategory::Internal
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user