Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6de58da17d | ||
|
|
027555eb4e | ||
|
|
75119f23e5 | ||
|
|
653a1171a2 | ||
|
|
2efda433e7 | ||
|
|
2d524723a4 | ||
|
|
7f4e0e4460 | ||
|
|
4f0552c48f | ||
|
|
0705101c97 | ||
|
|
5992322371 | ||
|
|
d0683f0b6d | ||
|
|
f9f083d4c6 | ||
|
|
32f3fb6fb1 |
Generated
+12
-1
@@ -238,6 +238,15 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
|
||||
[[package]]
|
||||
name = "wip-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"trybuild",
|
||||
"wip-interface",
|
||||
"wip-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wip-interface"
|
||||
version = "0.1.0"
|
||||
@@ -261,9 +270,11 @@ name = "wip-protocol"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "wip-rs"
|
||||
name = "wip-public-api-example"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"wip-host",
|
||||
"wip-interface",
|
||||
"wip-protocol",
|
||||
]
|
||||
|
||||
|
||||
+1
-14
@@ -1,16 +1,3 @@
|
||||
[workspace]
|
||||
members = [
|
||||
".",
|
||||
"crates/wip-interface",
|
||||
"crates/wip-interface-macros",
|
||||
"crates/wip-protocol",
|
||||
]
|
||||
members = ["crates/*"]
|
||||
resolver = "3"
|
||||
|
||||
[package]
|
||||
name = "wip-rs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
wip-protocol = { path = "crates/wip-protocol" }
|
||||
|
||||
@@ -2,6 +2,83 @@
|
||||
|
||||
Rust building blocks for the Web Interface Protocol (WIP).
|
||||
|
||||
The repository is a resolver-3 virtual Cargo workspace whose packages all live
|
||||
under `crates/*`. It provides a transport-independent protocol model, a Rust
|
||||
interface-authoring facade, a request-scoped host runtime, and a private
|
||||
public-API conformance consumer. The repository root is not itself a package.
|
||||
HTTP and other transport bindings are intentionally outside the supported
|
||||
slice.
|
||||
|
||||
## Crate graph and responsibilities
|
||||
|
||||
```text
|
||||
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
||||
├── wip-protocol logical declarations, values, calls, and validation
|
||||
├── wip-interface application DTO codecs and interface authoring facade
|
||||
│ ├── wip-protocol
|
||||
│ └── wip-interface-macros proc-macro implementation detail
|
||||
└── wip-host descriptor registry, publication, and qualified dispatch
|
||||
├── wip-interface
|
||||
└── wip-protocol
|
||||
```
|
||||
|
||||
| Crate | Responsibility | Does not own |
|
||||
| --- | --- | --- |
|
||||
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
||||
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
||||
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
||||
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, and interface-qualified dispatch against one host-owned instance. | Backend atomicity, global object lookup, or network serving. |
|
||||
| `wip-public-api-example` | An independently compiled consumer of only the three public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
|
||||
|
||||
The boundary is intentional: protocol types describe what can cross a
|
||||
transport; application DTOs opt into that model with `WipType`; a host-private
|
||||
implementation owns credentials, handles, and backend state; and a future
|
||||
transport maps its own routes/envelopes to `CallOperationRequest` and
|
||||
`CallOperationResponse` without placing transport-specific types in descriptors
|
||||
or application traits.
|
||||
|
||||
## End-to-end example
|
||||
|
||||
[`crates/wip-public-api-example/src/lib.rs`](crates/wip-public-api-example/src/lib.rs)
|
||||
is the complete public-API example and
|
||||
[`crates/wip-public-api-example/src/main.rs`](crates/wip-public-api-example/src/main.rs)
|
||||
runs it. It demonstrates all of the following:
|
||||
|
||||
1. public application DTOs derived as `WipType` records, enums, and unions,
|
||||
including canonical entry paths and schema-opaque JSON;
|
||||
2. two public traits declared with `#[wip::interface]`;
|
||||
3. a private host struct implementing both traits;
|
||||
4. explicit publication of both interfaces as an ordered set on one object;
|
||||
5. separate observation of opaque interface references, descriptors, and
|
||||
descriptor validators;
|
||||
6. calls qualified by `target.path`, object validator, interface reference and
|
||||
validator, operation, and schema-neutral `Value` arguments;
|
||||
7. validated result values decoded back to the typed application result;
|
||||
8. independent dispatch of the same `status` operation name on both interfaces;
|
||||
9. distinct domain rejection, rollback-confirmed and outcome-unknown
|
||||
host/backend failures, `PermissionDenied`, stale validator recovery, interface
|
||||
membership, and lookup failure codes; and
|
||||
10. canonical failure precedence when several request fields are invalid.
|
||||
|
||||
Run it inside the development shell:
|
||||
|
||||
```console
|
||||
nix develop
|
||||
cargo run --package wip-public-api-example
|
||||
```
|
||||
|
||||
The public-only conformance suite is in
|
||||
[`crates/wip-public-api-example/tests/end_to_end.rs`](crates/wip-public-api-example/tests/end_to_end.rs).
|
||||
It covers canonical object/descriptor shape, ordered interfaces,
|
||||
schema-neutral record/enum/union/entry/JSON values, fully qualified calls, and
|
||||
the distinct domain, host, authorization, validator-recovery, and interface
|
||||
failure classes. Exhaustive public type construction and matching make legacy
|
||||
ObjectId, descriptor `name`, and semantic `Value` variants compile-time
|
||||
regressions. Unit tests in the public crates additionally cover every host
|
||||
dispatch failure, `InvalidRequest` versus descriptor-bound `InvalidArguments`,
|
||||
invalid local responses, validators, same-named operations, and exhaustive
|
||||
per-interaction protocol error-code sets.
|
||||
|
||||
## Interface authoring
|
||||
|
||||
Applications depend on `wip-interface`, normally imported as `wip`:
|
||||
@@ -30,38 +107,152 @@ pub trait Messenger {
|
||||
```
|
||||
|
||||
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
||||
users do not import `wip-interface-macros` directly. The generated
|
||||
`MessengerDefinition` constructs an `InterfaceDescriptor`, decodes named
|
||||
arguments, encodes results, validates both boundaries, and provides typed
|
||||
dispatch for any `T: Messenger`.
|
||||
users do not import `wip-interface-macros` or generated private support symbols.
|
||||
The generated `MessengerDefinition` constructs an `InterfaceDescriptor`,
|
||||
decodes named arguments, encodes results, validates both boundaries, and
|
||||
provides typed dispatch for any `T: Messenger`.
|
||||
|
||||
### Type mapping
|
||||
### Supported Rust syntax
|
||||
|
||||
A supported interface is a public, non-generic trait containing methods with:
|
||||
|
||||
- exactly an immutable `&self` receiver;
|
||||
- simple named, owned parameters;
|
||||
- an explicit `wip::OperationResult<T>` return;
|
||||
- `()` only as the application return when no value is produced; and
|
||||
- direct `Option<T>` only for an omittable parameter.
|
||||
|
||||
`WipType` derives support named-field structs, all-unit enums, and unions whose
|
||||
cases may be unit variants or variants containing exactly one unnamed payload.
|
||||
The macros reject private,
|
||||
generic, inherited, unsafe, auto, or associated-item traits; const, async,
|
||||
unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
|
||||
borrowed/custom-lifetime values; tuple/unit/generic structs; Rust unions;
|
||||
named-field/multi-field enum variants; explicit discriminants; nested `Option`; and
|
||||
`Option` in returns, collections, entries, or union payloads. These diagnostics
|
||||
are compile-fail tested under `crates/wip-interface/tests/ui`.
|
||||
|
||||
### Rust type mapping
|
||||
|
||||
| Rust | Protocol |
|
||||
| --- | --- |
|
||||
| `()` as an operation result | no returned value |
|
||||
| `()` | unit / `Value::Unit` |
|
||||
| `bool` | boolean |
|
||||
| integer primitives | JavaScript-lossless integer |
|
||||
| `f32`, `f64` | finite number |
|
||||
| `String` | string |
|
||||
| `wip::Bytes` | bytes |
|
||||
| `wip::wip_protocol::JsonValue` | JSON |
|
||||
| `wip::Entry<K, V>` | entry |
|
||||
| `wip::JsonValue` | JSON interpreted over the schema-neutral `Value` tree |
|
||||
| `wip::Entry` | canonical absolute Worldspace path encoded as a string |
|
||||
| `Vec<T>` | list |
|
||||
| named-field `#[derive(wip::WipType)]` struct | named record |
|
||||
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
||||
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
||||
| all-unit `#[derive(wip::WipType)]` enum | named enum encoded as a string |
|
||||
| mixed unit/newtype or all-newtype enum | named union encoded as a discriminator record |
|
||||
|
||||
`Option<T>` is accepted only for a direct DTO field or operation parameter and
|
||||
means that the named value may be omitted. It is not protocol null. Domain
|
||||
failures are modeled in the application result (usually a derived union) and
|
||||
returned through `Ok`; `wip::HostError` is only for host/runtime failures.
|
||||
`Option<T>` means that a direct DTO field or operation parameter may be
|
||||
omitted; it is not protocol null. JSON null remains available inside
|
||||
`wip::JsonValue`.
|
||||
|
||||
#### Migration from the pre-canonical value API
|
||||
|
||||
The old generic `wip::Entry<K, V>` represented an application key/value pair
|
||||
and is no longer available. Use `wip::Entry::new("/canonical/path")` for a
|
||||
Worldspace entry path and place any associated application data in a record.
|
||||
`Entry` encodes as `Value::String` and validates the canonical absolute path.
|
||||
|
||||
The semantic `Value::Json`, `Value::Entry`, `Value::Enum`, and `Value::Union`
|
||||
variants have also been removed. JSON recursively uses `Unit`, primitive,
|
||||
`List`, and `Record` values and rejects `Bytes`; enums use `String`; unions use
|
||||
a `Record` containing `$case` and, for payload-bearing cases, `value`. Unit
|
||||
operation results are represented explicitly as `Value::Unit`.
|
||||
|
||||
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
||||
section documents the return declaration; text before that section documents
|
||||
the operation itself.
|
||||
|
||||
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
|
||||
|
||||
Applications use `wip-host` to register generated definitions and explicitly
|
||||
choose the ordered interface set for each object publication:
|
||||
|
||||
```rust,ignore
|
||||
let mut interfaces = wip_host::InterfaceRegistry::new();
|
||||
let messenger = interfaces.register(MessengerDefinition, None)?;
|
||||
|
||||
let published = wip_host::PublishedObject::new(request_scoped_object)
|
||||
.expose(&messenger)?;
|
||||
let protocol_object = published.protocol_object();
|
||||
```
|
||||
|
||||
`expose` compiles only when the object implements the generated definition's
|
||||
interface trait. Implementing a trait does not expose it automatically, empty
|
||||
interface sets are valid, insertion order is preserved, and duplicate
|
||||
references are rejected. Registry references are opaque and remain outside the
|
||||
descriptor; generated descriptors contain neither those references nor Rust
|
||||
trait identity.
|
||||
|
||||
Dispatch is qualified by interface reference and operation name and targets a
|
||||
canonical Worldspace path. An `ObjectProvider` validates that path before
|
||||
resolution, maps malformed paths to `InvalidRequest`, then resolves a valid path
|
||||
exactly once inside `with_object`; the host checks the supplied object validator,
|
||||
current interface membership, interface validator, descriptor operation,
|
||||
operation-specific object-validator policy, arguments, and authorization in
|
||||
canonical precedence. Path and children remain provider resolution context and
|
||||
are never projected by `WipObject`; host-private fields and backend handles are
|
||||
also excluded.
|
||||
|
||||
Application domain failures belong in a derived result union and are returned
|
||||
through `Ok`. `wip::HostError` is reserved for runtime/backend failures. A
|
||||
structurally malformed call is `InvalidRequest`; only argument values checked
|
||||
after the current Interface Descriptor is fixed are `InvalidArguments`. A Host
|
||||
must never return a wire `InvalidResult`: Clients keep invalid Object,
|
||||
Descriptor, operation-result, and error responses as local `InvalidResponse`
|
||||
failures, while unsupported descriptor formats remain local
|
||||
`UnsupportedDescriptorFormat` failures.
|
||||
|
||||
For operation calls, `Internal` and `ResourceLimitExceeded` guarantee that the
|
||||
operation did not run or that its effects were rolled back.
|
||||
`OperationOutcomeUnknown` is the only protocol code that makes no such
|
||||
guarantee, so Clients must not automatically retry it. `wip::HostError`
|
||||
therefore requires both a `HostErrorKind` and an `EffectGuarantee`; implementation
|
||||
panic, result encoding, and result validation default to an unknown outcome.
|
||||
Host-private diagnostics are bounded locally but never copied into protocol
|
||||
messages.
|
||||
|
||||
`ExecutionContext` carries a runtime-neutral cancellation token, monotonic
|
||||
deadline, and optional Host-defined resource budget through resolution and
|
||||
execution. Cancellation and deadlines are cooperative: the runtime checks them
|
||||
immediately before typed invocation, while providers enforce them during backend
|
||||
work. A pre-invocation limit failure is `ResourceLimitExceeded`; after invocation
|
||||
it is safe to use that code only when non-commit or rollback is confirmed.
|
||||
|
||||
Providers remain responsible for backend atomicity. `with_object` returns a typed
|
||||
`ProviderResult`, and `execute_operation` receives an `OperationAttempt` that
|
||||
separates `NotStarted` from `Started`. A transactional provider holds its
|
||||
transaction across the callback, commits successful attempts, and may call
|
||||
`OperationAttempt::confirm_rollback` only after every operation effect has been
|
||||
rolled back. Without that proof, post-invocation failures remain
|
||||
`OperationOutcomeUnknown`. Mutable operations must still make validator
|
||||
comparison and backend commit atomic and return a validator describing the state
|
||||
that becomes committed.
|
||||
|
||||
## Validation
|
||||
|
||||
Enter the dev shell and run the acceptance commands exactly:
|
||||
|
||||
```console
|
||||
nix develop
|
||||
cargo fmt --all -- --check
|
||||
cargo check --workspace --all-targets
|
||||
cargo test --workspace --all-targets
|
||||
cargo test --workspace --doc
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps
|
||||
cargo run --package wip-public-api-example
|
||||
git diff --check
|
||||
```
|
||||
|
||||
`cargo test --workspace --all-targets` includes the public-only conformance
|
||||
consumer, runtime failure tests, and `trybuild` compile-fail suites. The separate
|
||||
doctest, rustdoc, executable, and whitespace checks are all required acceptance
|
||||
steps.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "wip-host"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Host-side object publication and operation dispatch for WIP"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
wip-interface = { path = "../wip-interface" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
#[test]
|
||||
fn rejects_exposing_an_unimplemented_interface() {
|
||||
let tests = trybuild::TestCases::new();
|
||||
tests.compile_fail("tests/ui/unimplemented_interface.rs");
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use wip_host::{
|
||||
CallError, CallErrorKind, CallRequest, CancellationToken, ExecutionContext, InterfaceRef,
|
||||
InterfaceRegistry, InterfaceTarget, ObjectProvider, OperationAttempt, ProviderResult,
|
||||
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
||||
};
|
||||
use wip_interface::{
|
||||
CodecError, EffectGuarantee, HostError, OperationResult, TypeDeclaration, TypeExpr, Value,
|
||||
WipType, interface,
|
||||
};
|
||||
use wip_protocol::ProtocolErrorCode;
|
||||
|
||||
#[interface]
|
||||
pub trait Reader {
|
||||
/// Returns the reader-qualified label.
|
||||
fn label(&self) -> OperationResult<String>;
|
||||
|
||||
/// Adds two integers.
|
||||
fn add(&self, left: i64, right: i64) -> OperationResult<i64>;
|
||||
|
||||
/// Reports a backend failure.
|
||||
fn fail(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
#[interface]
|
||||
pub trait Writer {
|
||||
/// Returns the writer-qualified label.
|
||||
fn label(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
#[interface]
|
||||
pub trait Hidden {
|
||||
/// Returns a hidden value.
|
||||
fn hidden(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
#[interface]
|
||||
pub trait Broken {
|
||||
/// Returns a deliberately invalid encoded value.
|
||||
fn broken(&self) -> OperationResult<BadValue>;
|
||||
|
||||
/// Produces a result codec failure after implementation invocation.
|
||||
fn encode_failure(&self) -> OperationResult<EncodeFailure>;
|
||||
|
||||
/// Panics after implementation invocation begins.
|
||||
fn panic_after_call(&self) -> OperationResult<String>;
|
||||
|
||||
/// Reports an internal failure without an effect guarantee.
|
||||
fn unknown_internal(&self) -> OperationResult<String>;
|
||||
|
||||
/// Reports an internal failure with a non-commit guarantee.
|
||||
fn safe_internal(&self) -> OperationResult<String>;
|
||||
|
||||
/// Reports a resource failure without an effect guarantee.
|
||||
fn unknown_resource(&self) -> OperationResult<String>;
|
||||
|
||||
/// Reports a resource failure with a non-commit guarantee.
|
||||
fn safe_resource(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BadValue;
|
||||
|
||||
impl WipType for BadValue {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Integer
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::String("not an integer".into()))
|
||||
}
|
||||
|
||||
fn decode(_: Value) -> Result<Self, CodecError> {
|
||||
Ok(Self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EncodeFailure;
|
||||
|
||||
impl WipType for EncodeFailure {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::String
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Err(CodecError::new("private://backend/result could not encode"))
|
||||
}
|
||||
|
||||
fn decode(_: Value) -> Result<Self, CodecError> {
|
||||
Ok(Self)
|
||||
}
|
||||
}
|
||||
|
||||
struct Document {
|
||||
name: String,
|
||||
description: Option<String>,
|
||||
reference: Option<String>,
|
||||
validator: Option<Validator>,
|
||||
require_validator: bool,
|
||||
calls: Rc<Cell<usize>>,
|
||||
private_backend_handle: String,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
fn open(name: &str, reference: Option<&str>, calls: Rc<Cell<usize>>) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
description: Some("public document".into()),
|
||||
reference: reference.map(str::to_owned),
|
||||
validator: None,
|
||||
require_validator: false,
|
||||
calls,
|
||||
private_backend_handle: "/private/backend/path".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn strict(name: &str, reference: &str, validator: &[u8], calls: Rc<Cell<usize>>) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
description: Some("public document".into()),
|
||||
reference: Some(reference.into()),
|
||||
validator: Some(Validator::new(validator)),
|
||||
require_validator: true,
|
||||
calls,
|
||||
private_backend_handle: "secret-handle".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_call(&self) {
|
||||
self.calls.set(self.calls.get() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
impl WipObject for Document {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn description(&self) -> Option<&str> {
|
||||
self.description.as_deref()
|
||||
}
|
||||
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.reference.as_deref()
|
||||
}
|
||||
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
self.validator.as_ref()
|
||||
}
|
||||
|
||||
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
|
||||
self.require_validator
|
||||
}
|
||||
}
|
||||
|
||||
impl Reader for Document {
|
||||
fn label(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Ok("reader".into())
|
||||
}
|
||||
|
||||
fn add(&self, left: i64, right: i64) -> OperationResult<i64> {
|
||||
self.record_call();
|
||||
Ok(left + right)
|
||||
}
|
||||
|
||||
fn fail(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Err(HostError::internal(
|
||||
"backend unavailable",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer for Document {
|
||||
fn label(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Ok("writer".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Hidden for Document {
|
||||
fn hidden(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Ok("hidden".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Broken for Document {
|
||||
fn broken(&self) -> OperationResult<BadValue> {
|
||||
self.record_call();
|
||||
Ok(BadValue)
|
||||
}
|
||||
|
||||
fn encode_failure(&self) -> OperationResult<EncodeFailure> {
|
||||
self.record_call();
|
||||
Ok(EncodeFailure)
|
||||
}
|
||||
|
||||
fn panic_after_call(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
panic!("private://backend panic with credential=secret")
|
||||
}
|
||||
|
||||
fn unknown_internal(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Err(HostError::internal(
|
||||
"private://backend/path credential=secret",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
|
||||
fn safe_internal(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Err(HostError::internal(
|
||||
"private://backend/path credential=secret",
|
||||
EffectGuarantee::NotCommitted,
|
||||
))
|
||||
}
|
||||
|
||||
fn unknown_resource(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Err(HostError::resource_limit(
|
||||
"private scheduler deadline details",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
|
||||
fn safe_resource(&self) -> OperationResult<String> {
|
||||
self.record_call();
|
||||
Err(HostError::resource_limit(
|
||||
"private scheduler deadline details",
|
||||
EffectGuarantee::NotCommitted,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct TestProvider {
|
||||
reader: RegisteredInterface<ReaderDefinition>,
|
||||
writer: RegisteredInterface<WriterDefinition>,
|
||||
broken: RegisteredInterface<BrokenDefinition>,
|
||||
calls: Rc<Cell<usize>>,
|
||||
resolutions: Cell<usize>,
|
||||
authorization_checks: Cell<usize>,
|
||||
deny: Cell<bool>,
|
||||
switched: Cell<bool>,
|
||||
confirm_rollback: Cell<bool>,
|
||||
provider_failure: Cell<Option<(bool, EffectGuarantee)>>,
|
||||
observed_budget: Cell<Option<u64>>,
|
||||
observed_deadline: Cell<Option<Instant>>,
|
||||
observed_cancelled: Cell<bool>,
|
||||
}
|
||||
|
||||
impl TestProvider {
|
||||
fn new(
|
||||
reader: RegisteredInterface<ReaderDefinition>,
|
||||
writer: RegisteredInterface<WriterDefinition>,
|
||||
broken: RegisteredInterface<BrokenDefinition>,
|
||||
) -> Self {
|
||||
Self {
|
||||
reader,
|
||||
writer,
|
||||
broken,
|
||||
calls: Rc::new(Cell::new(0)),
|
||||
resolutions: Cell::new(0),
|
||||
authorization_checks: Cell::new(0),
|
||||
deny: Cell::new(false),
|
||||
switched: Cell::new(false),
|
||||
confirm_rollback: Cell::new(false),
|
||||
provider_failure: Cell::new(None),
|
||||
observed_budget: Cell::new(None),
|
||||
observed_deadline: Cell::new(None),
|
||||
observed_cancelled: Cell::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectProvider for TestProvider {
|
||||
type Object = Document;
|
||||
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
self.observed_budget.set(context.resource_budget());
|
||||
self.observed_deadline.set(context.deadline());
|
||||
self.observed_cancelled
|
||||
.set(context.cancellation().is_cancelled());
|
||||
self.resolutions.set(self.resolutions.get() + 1);
|
||||
let (document, interfaces) = match path {
|
||||
"/document" => (
|
||||
Document::strict(
|
||||
"document",
|
||||
"document-ref",
|
||||
b"object-v1",
|
||||
Rc::clone(&self.calls),
|
||||
),
|
||||
2,
|
||||
),
|
||||
"/open" => (
|
||||
Document::open("open", Some("open-ref"), Rc::clone(&self.calls)),
|
||||
2,
|
||||
),
|
||||
"/left/document" | "/right/document" => (
|
||||
Document::strict(
|
||||
"document",
|
||||
"shared-ref",
|
||||
b"shared-v1",
|
||||
Rc::clone(&self.calls),
|
||||
),
|
||||
2,
|
||||
),
|
||||
"/switch" => {
|
||||
let switched = self.switched.replace(true);
|
||||
let (reference, validator) = if switched {
|
||||
("second-ref", b"second".as_slice())
|
||||
} else {
|
||||
("first-ref", b"first".as_slice())
|
||||
};
|
||||
(
|
||||
Document::strict("switch", reference, validator, Rc::clone(&self.calls)),
|
||||
2,
|
||||
)
|
||||
}
|
||||
"/empty" => (Document::open("empty", None, Rc::clone(&self.calls)), 0),
|
||||
"/invalid-object" => (
|
||||
Document::open("wrong-name", None, Rc::clone(&self.calls)),
|
||||
0,
|
||||
),
|
||||
"/broken" => (
|
||||
Document::open("broken", Some("broken-ref"), Rc::clone(&self.calls)),
|
||||
3,
|
||||
),
|
||||
_ => return ProviderResult::NotFound,
|
||||
};
|
||||
|
||||
let publication = PublishedObject::new(document);
|
||||
let publication = match interfaces {
|
||||
0 => publication,
|
||||
2 => publication
|
||||
.expose(&self.writer)
|
||||
.unwrap()
|
||||
.expose(&self.reader)
|
||||
.unwrap(),
|
||||
3 => publication.expose(&self.broken).unwrap(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
ProviderResult::Found(operation(&publication))
|
||||
}
|
||||
|
||||
fn execute_operation(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
|
||||
) -> ProviderResult<OperationAttempt> {
|
||||
let result = self.with_object(context, path, operation);
|
||||
if let Some((resource, guarantee)) = self.provider_failure.get() {
|
||||
let error = if resource {
|
||||
HostError::resource_limit("private provider scheduler state", guarantee)
|
||||
} else {
|
||||
HostError::internal("private provider transaction path", guarantee)
|
||||
};
|
||||
return ProviderResult::Failure(error);
|
||||
}
|
||||
if self.confirm_rollback.get() {
|
||||
match result {
|
||||
ProviderResult::Found(attempt) => ProviderResult::Found(attempt.confirm_rollback()),
|
||||
other => other,
|
||||
}
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn authorize(&self, _: &str, _: &Document, _: &InterfaceRef, _: &str) -> bool {
|
||||
self.authorization_checks
|
||||
.set(self.authorization_checks.get() + 1);
|
||||
!self.deny.get()
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_and_provider() -> (
|
||||
InterfaceRegistry,
|
||||
TestProvider,
|
||||
RegisteredInterface<HiddenDefinition>,
|
||||
) {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let reader = registry
|
||||
.register(ReaderDefinition, Some(Validator::new(b"schema-v1")))
|
||||
.unwrap();
|
||||
let writer = registry.register(WriterDefinition, None).unwrap();
|
||||
let hidden = registry.register(HiddenDefinition, None).unwrap();
|
||||
let broken = registry.register(BrokenDefinition, None).unwrap();
|
||||
let provider = TestProvider::new(reader, writer, broken);
|
||||
(registry, provider, hidden)
|
||||
}
|
||||
|
||||
fn request(
|
||||
path: &str,
|
||||
object_validator: Option<&[u8]>,
|
||||
reference: &InterfaceRef,
|
||||
interface_validator: Option<&[u8]>,
|
||||
operation: &str,
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> CallRequest {
|
||||
CallRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: object_validator.map(<[u8]>::to_vec),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: reference.as_str().to_owned(),
|
||||
validator: interface_validator.map(<[u8]>::to_vec),
|
||||
},
|
||||
operation: operation.into(),
|
||||
arguments,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_failure(error: CallError, kind: CallErrorKind, code: ProtocolErrorCode) {
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.protocol_error().code, code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor() {
|
||||
let (registry, provider, _) = registry_and_provider();
|
||||
let reference = provider.reader.reference();
|
||||
|
||||
assert_ne!(reference.as_str(), "Reader");
|
||||
let observation = registry.fetch_interface(reference.as_str()).unwrap();
|
||||
assert_eq!(observation.reference, *reference);
|
||||
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
|
||||
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
|
||||
let response = observation.protocol_response().unwrap();
|
||||
assert_eq!(response.interface, reference.as_str());
|
||||
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
|
||||
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
|
||||
response.descriptor.validate().unwrap();
|
||||
|
||||
let mut invalid_observation = registry.fetch_interface(reference.as_str()).unwrap();
|
||||
let duplicate_operation = invalid_observation.descriptor.operations[0].clone();
|
||||
invalid_observation
|
||||
.descriptor
|
||||
.operations
|
||||
.push(duplicate_operation);
|
||||
let invalid_response = invalid_observation.protocol_response().unwrap_err();
|
||||
assert_eq!(invalid_response.code, ProtocolErrorCode::Internal);
|
||||
|
||||
let error = registry.fetch_interface("unknown").unwrap_err();
|
||||
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_object_projection_supports_optional_metadata_and_ordered_sets() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
let object = provider.fetch("/document").unwrap();
|
||||
|
||||
assert_eq!(object.name, "document");
|
||||
assert_eq!(object.description.as_deref(), Some("public document"));
|
||||
assert_eq!(object.r#ref.as_deref(), Some("document-ref"));
|
||||
assert_eq!(object.validator.as_deref(), Some(b"object-v1".as_slice()));
|
||||
assert_eq!(
|
||||
object.interfaces,
|
||||
vec![
|
||||
provider.writer.reference().as_str().to_owned(),
|
||||
provider.reader.reference().as_str().to_owned(),
|
||||
]
|
||||
);
|
||||
assert!(!format!("{object:?}").contains("secret-handle"));
|
||||
assert!(!format!("{object:?}").contains("/document"));
|
||||
|
||||
let empty = provider.fetch("/empty").unwrap();
|
||||
assert!(empty.interfaces.is_empty());
|
||||
assert_eq!(empty.r#ref, None);
|
||||
assert_eq!(empty.validator, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_exposure_is_rejected_and_private_state_is_not_projected() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
let publication = PublishedObject::new(Document::open(
|
||||
"duplicate",
|
||||
None,
|
||||
Rc::clone(&provider.calls),
|
||||
))
|
||||
.expose(&provider.reader)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
publication.implementation().private_backend_handle,
|
||||
"/private/backend/path"
|
||||
);
|
||||
let error = match publication.expose(&provider.reader) {
|
||||
Ok(_) => panic!("duplicate exposure unexpectedly succeeded"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains(provider.reader.reference().as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_resolution_context_not_object_identity() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
|
||||
let left = provider.fetch("/left/document").unwrap();
|
||||
let right = provider.fetch("/right/document").unwrap();
|
||||
assert_eq!(left, right);
|
||||
assert_eq!(left.r#ref.as_deref(), Some("shared-ref"));
|
||||
|
||||
let first = provider.fetch("/switch").unwrap();
|
||||
let second = provider.fetch("/switch").unwrap();
|
||||
assert_ne!(first.r#ref, second.r#ref);
|
||||
assert_ne!(first.validator, second.validator);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_dispatch_is_interface_qualified_and_resolves_once_per_call() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
let before = provider.resolutions.get();
|
||||
|
||||
let writer = provider
|
||||
.call_operation(request(
|
||||
"/open",
|
||||
None,
|
||||
provider.writer.reference(),
|
||||
None,
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let reader = provider
|
||||
.call_operation(request(
|
||||
"/open",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let strict = provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(writer.result, Value::String("writer".into()));
|
||||
assert_eq!(reader.result, Value::String("reader".into()));
|
||||
assert_eq!(strict.result, Value::String("reader".into()));
|
||||
assert_eq!(strict.validator.as_deref(), Some(b"object-v1".as_slice()));
|
||||
assert_eq!(provider.resolutions.get() - before, 3);
|
||||
assert_eq!(provider.calls.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_failures_follow_canonical_precedence_without_execution() {
|
||||
let (_, provider, hidden) = registry_and_provider();
|
||||
|
||||
let resolutions = provider.resolutions.get();
|
||||
for invalid_path in [
|
||||
"relative",
|
||||
"/trailing/",
|
||||
"/double//segment",
|
||||
"/dot/./segment",
|
||||
"/parent/../segment",
|
||||
] {
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
invalid_path,
|
||||
Some(b"stale"),
|
||||
hidden.reference(),
|
||||
Some(b"stale"),
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InvalidRequest,
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
);
|
||||
}
|
||||
assert_eq!(provider.resolutions.get(), resolutions);
|
||||
assert_failure(
|
||||
provider.fetch("/invalid/").unwrap_err(),
|
||||
CallErrorKind::InvalidRequest,
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
);
|
||||
assert_eq!(provider.resolutions.get(), resolutions);
|
||||
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/missing",
|
||||
Some(b"stale"),
|
||||
hidden.reference(),
|
||||
Some(b"stale"),
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::NotFound,
|
||||
ProtocolErrorCode::NotFound,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"stale"),
|
||||
hidden.reference(),
|
||||
None,
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::ValidatorMismatch,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
hidden.reference(),
|
||||
None,
|
||||
"hidden",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InterfaceMismatch,
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
provider.reader.reference(),
|
||||
None,
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InterfaceValidatorRequired,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
provider.reader.reference(),
|
||||
Some(b"stale-schema"),
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"missing",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::OperationNotFound,
|
||||
ProtocolErrorCode::OperationNotFound,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"add",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::ValidatorRequired,
|
||||
ProtocolErrorCode::ValidatorRequired,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"add",
|
||||
BTreeMap::from([("left".into(), Value::String("wrong".into()))]),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InvalidArguments,
|
||||
ProtocolErrorCode::InvalidArguments,
|
||||
);
|
||||
|
||||
provider.deny.set(true);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/document",
|
||||
Some(b"object-v1"),
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::PermissionDenied,
|
||||
ProtocolErrorCode::PermissionDenied,
|
||||
);
|
||||
assert_eq!(provider.authorization_checks.get(), 1);
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immutable_interface_rejects_a_supplied_validator() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/open",
|
||||
None,
|
||||
provider.writer.reference(),
|
||||
Some(b"unexpected"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
);
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_host_responses_and_uncertain_operation_failures_use_canonical_codes() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
|
||||
assert_failure(
|
||||
provider.fetch("/invalid-object").unwrap_err(),
|
||||
CallErrorKind::Internal,
|
||||
ProtocolErrorCode::Internal,
|
||||
);
|
||||
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/broken",
|
||||
None,
|
||||
provider.broken.reference(),
|
||||
None,
|
||||
"broken",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/open",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"fail",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err(),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
}
|
||||
|
||||
fn call_broken(provider: &TestProvider, operation: &str) -> CallError {
|
||||
provider
|
||||
.call_operation(request(
|
||||
"/broken",
|
||||
None,
|
||||
provider.broken.reference(),
|
||||
None,
|
||||
operation,
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_implementation_failures_map_only_with_a_non_commit_guarantee() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
|
||||
let unknown_internal = call_broken(&provider, "unknown_internal");
|
||||
assert_failure(
|
||||
unknown_internal.clone(),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
assert!(!unknown_internal.message().contains("private://"));
|
||||
assert!(
|
||||
!unknown_internal
|
||||
.protocol_error()
|
||||
.message
|
||||
.contains("credential")
|
||||
);
|
||||
|
||||
assert_failure(
|
||||
call_broken(&provider, "safe_internal"),
|
||||
CallErrorKind::Internal,
|
||||
ProtocolErrorCode::Internal,
|
||||
);
|
||||
assert_failure(
|
||||
call_broken(&provider, "unknown_resource"),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
assert_failure(
|
||||
call_broken(&provider, "safe_resource"),
|
||||
CallErrorKind::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_invocation_result_and_panic_failures_require_provider_rollback() {
|
||||
for operation in ["broken", "encode_failure", "panic_after_call"] {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
let error = call_broken(&provider, operation);
|
||||
assert_failure(
|
||||
error.clone(),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
assert!(!error.message().contains("private://"));
|
||||
assert!(!error.message().contains("credential"));
|
||||
|
||||
provider.confirm_rollback.set(true);
|
||||
assert_failure(
|
||||
call_broken(&provider, operation),
|
||||
CallErrorKind::Internal,
|
||||
ProtocolErrorCode::Internal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_failures_after_invocation_use_the_provider_effect_guarantee() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
|
||||
provider
|
||||
.provider_failure
|
||||
.set(Some((false, EffectGuarantee::Unknown)));
|
||||
assert_failure(
|
||||
call_broken(&provider, "safe_internal"),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
|
||||
provider
|
||||
.provider_failure
|
||||
.set(Some((false, EffectGuarantee::NotCommitted)));
|
||||
let internal = call_broken(&provider, "unknown_internal");
|
||||
assert_failure(
|
||||
internal.clone(),
|
||||
CallErrorKind::Internal,
|
||||
ProtocolErrorCode::Internal,
|
||||
);
|
||||
assert!(!internal.message().contains("transaction"));
|
||||
|
||||
provider
|
||||
.provider_failure
|
||||
.set(Some((true, EffectGuarantee::Unknown)));
|
||||
assert_failure(
|
||||
call_broken(&provider, "safe_resource"),
|
||||
CallErrorKind::OperationOutcomeUnknown,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
);
|
||||
|
||||
provider
|
||||
.provider_failure
|
||||
.set(Some((true, EffectGuarantee::NotCommitted)));
|
||||
assert_failure(
|
||||
call_broken(&provider, "unknown_resource"),
|
||||
CallErrorKind::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execution_context_is_propagated_and_preflight_prevents_invocation() {
|
||||
let (_, provider, _) = registry_and_provider();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let context = ExecutionContext::new()
|
||||
.with_deadline(deadline)
|
||||
.with_resource_budget(17);
|
||||
|
||||
provider
|
||||
.call_operation_with_context(
|
||||
&context,
|
||||
request(
|
||||
"/open",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(provider.observed_deadline.get(), Some(deadline));
|
||||
assert_eq!(provider.observed_budget.get(), Some(17));
|
||||
assert!(!provider.observed_cancelled.get());
|
||||
|
||||
let calls = provider.calls.get();
|
||||
let cancellation = CancellationToken::new();
|
||||
cancellation.cancel();
|
||||
let cancelled = ExecutionContext::new().with_cancellation(cancellation);
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation_with_context(
|
||||
&cancelled,
|
||||
request(
|
||||
"/open",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)
|
||||
.unwrap_err(),
|
||||
CallErrorKind::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
);
|
||||
assert_eq!(provider.calls.get(), calls);
|
||||
assert!(provider.observed_cancelled.get());
|
||||
|
||||
let expired = ExecutionContext::new().with_deadline(Instant::now() - Duration::from_secs(1));
|
||||
assert_failure(
|
||||
provider
|
||||
.call_operation_with_context(
|
||||
&expired,
|
||||
request(
|
||||
"/open",
|
||||
None,
|
||||
provider.reader.reference(),
|
||||
Some(b"schema-v1"),
|
||||
"label",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)
|
||||
.unwrap_err(),
|
||||
CallErrorKind::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
);
|
||||
assert_eq!(provider.calls.get(), calls);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use wip_host::{InterfaceRegistry, PublishedObject, WipObject};
|
||||
use wip_interface::{OperationResult, interface};
|
||||
|
||||
#[interface]
|
||||
pub trait Search {
|
||||
fn search(&self) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
struct Object;
|
||||
|
||||
impl WipObject for Object {
|
||||
fn name(&self) -> &str {
|
||||
"object"
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let search = registry.register(SearchDefinition, None).unwrap();
|
||||
let _published = PublishedObject::new(Object).expose(&search).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
error[E0277]: the trait bound `Object: Search` is not satisfied
|
||||
--> tests/ui/unimplemented_interface.rs:20:58
|
||||
|
|
||||
20 | let _published = PublishedObject::new(Object).expose(&search).unwrap();
|
||||
| ------ ^^^^^^^ unsatisfied trait bound
|
||||
| |
|
||||
| required by a bound introduced by this call
|
||||
|
|
||||
help: the trait `Search` is not implemented for `Object`
|
||||
--> tests/ui/unimplemented_interface.rs:9:1
|
||||
|
|
||||
9 | struct Object;
|
||||
| ^^^^^^^^^^^^^
|
||||
help: this trait has no implementations, consider adding one
|
||||
--> tests/ui/unimplemented_interface.rs:5:1
|
||||
|
|
||||
5 | pub trait Search {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
note: required for `SearchDefinition` to implement `InterfaceImplementation<Object>`
|
||||
--> tests/ui/unimplemented_interface.rs:4:1
|
||||
|
|
||||
4 | #[interface]
|
||||
| ^^^^^^^^^^^^
|
||||
5 | pub trait Search {
|
||||
| ^^^^^^
|
||||
note: required by a bound in `PublishedObject::<T>::expose`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
|
||||
| ------ required by a bound in this associated function
|
||||
| where
|
||||
| D: InterfaceImplementation<T>,
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `PublishedObject::<T>::expose`
|
||||
= note: this error originates in the attribute macro `interface` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
@@ -1,4 +1,10 @@
|
||||
//! 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;
|
||||
|
||||
@@ -162,14 +168,40 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
||||
#(#declaration_collectors)*
|
||||
|
||||
::wip_interface::wip_protocol::InterfaceDescriptor {
|
||||
name: ::std::string::String::from(stringify!(#trait_ident)),
|
||||
format: ::std::string::String::from(
|
||||
::wip_interface::wip_protocol::INTERFACE_FORMAT_V1,
|
||||
),
|
||||
documentation: #trait_doc,
|
||||
declarations,
|
||||
types: declarations,
|
||||
operations: ::std::vec![#(#operation_declarations),*],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: #trait_ident> ::wip_interface::InterfaceImplementation<T> for #definition_ident {
|
||||
fn dispatch(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::DispatchError,
|
||||
> {
|
||||
let descriptor = Self::descriptor();
|
||||
match operation {
|
||||
#(#dispatch_arms)*
|
||||
_ => ::std::result::Result::Err(
|
||||
::wip_interface::DispatchError::UnknownOperation(
|
||||
::std::string::String::from(operation),
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl #definition_ident {
|
||||
/// Builds the interface descriptor generated from the trait declaration.
|
||||
pub fn descriptor() -> ::wip_interface::wip_protocol::InterfaceDescriptor {
|
||||
@@ -180,20 +212,19 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
||||
pub fn dispatch<T: #trait_ident>(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: ::std::vec::Vec<::wip_interface::wip_protocol::NamedValue>,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<
|
||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::DispatchError,
|
||||
> {
|
||||
let descriptor = Self::descriptor();
|
||||
match operation {
|
||||
#(#dispatch_arms)*
|
||||
_ => ::std::result::Result::Err(
|
||||
::wip_interface::DispatchError::UnknownOperation(
|
||||
::std::string::String::from(operation),
|
||||
),
|
||||
),
|
||||
}
|
||||
<Self as ::wip_interface::InterfaceImplementation<T>>::dispatch(
|
||||
implementation,
|
||||
operation,
|
||||
arguments,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,13 +484,18 @@ fn parse_operation_result(output: &ReturnType) -> syn::Result<Type> {
|
||||
_ => None,
|
||||
});
|
||||
let result = types.next().cloned();
|
||||
if arguments.args.len() != 1 || result.is_none() || types.next().is_some() {
|
||||
if arguments.args.len() != 1 || types.next().is_some() {
|
||||
return Err(Error::new_spanned(
|
||||
arguments,
|
||||
"`OperationResult` must have exactly one application result type",
|
||||
));
|
||||
}
|
||||
let result = result.expect("checked above");
|
||||
let result = result.ok_or_else(|| {
|
||||
Error::new_spanned(
|
||||
arguments,
|
||||
"`OperationResult` must have exactly one application result type",
|
||||
)
|
||||
})?;
|
||||
if direct_option(&result)?.is_some() || contains_option(&result) {
|
||||
return Err(Error::new_spanned(
|
||||
result,
|
||||
@@ -473,8 +509,13 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
let arguments_ident = &operation.arguments_ident;
|
||||
let fields = operation.parameters.iter().map(|parameter| {
|
||||
let ident = ¶meter.ident;
|
||||
let name = ¶meter.name;
|
||||
let ty = parameter_rust_type(parameter);
|
||||
quote!(pub #ident: #ty)
|
||||
let documentation = format!("Decoded `{name}` operation argument.");
|
||||
quote!(
|
||||
#[doc = #documentation]
|
||||
pub #ident: #ty
|
||||
)
|
||||
});
|
||||
let decoders = operation.parameters.iter().map(|parameter| {
|
||||
let ident = ¶meter.ident;
|
||||
@@ -490,12 +531,11 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
let encode_result = if operation.unit_result {
|
||||
quote! {
|
||||
let () = result;
|
||||
::std::result::Result::Ok(::std::option::Option::None)
|
||||
::std::result::Result::Ok(::wip_interface::wip_protocol::Value::Unit)
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
<#result_ty as ::wip_interface::WipType>::encode(result)
|
||||
.map(::std::option::Option::Some)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -508,9 +548,12 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
impl #arguments_ident {
|
||||
/// Decodes named logical values into typed operation arguments.
|
||||
pub fn decode(
|
||||
arguments: ::std::vec::Vec<::wip_interface::wip_protocol::NamedValue>,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(arguments)?;
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(arguments);
|
||||
let decoded = Self {
|
||||
#(#decoders,)*
|
||||
};
|
||||
@@ -522,7 +565,7 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
pub fn encode_result(
|
||||
result: #result_ty,
|
||||
) -> ::std::result::Result<
|
||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::CodecError,
|
||||
> {
|
||||
#encode_result
|
||||
@@ -542,22 +585,18 @@ fn operation_declaration(operation: &Operation) -> TokenStream2 {
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::ParameterDeclaration {
|
||||
name: ::std::string::String::from(#parameter_name),
|
||||
required: !#optional,
|
||||
documentation: #parameter_doc,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
optional: #optional,
|
||||
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
}
|
||||
});
|
||||
let returns = if operation.unit_result {
|
||||
quote!(::std::option::Option::None)
|
||||
} else {
|
||||
let result_ty = &operation.result_ty;
|
||||
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
||||
quote! {
|
||||
::std::option::Option::Some(::wip_interface::wip_protocol::ReturnDeclaration {
|
||||
documentation: #return_doc,
|
||||
ty: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
||||
})
|
||||
let result_ty = &operation.result_ty;
|
||||
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
||||
let returns = quote! {
|
||||
::wip_interface::wip_protocol::ReturnDeclaration {
|
||||
documentation: #return_doc,
|
||||
r#type: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -608,14 +647,17 @@ fn dispatch_arm(operation: &Operation) -> TokenStream2 {
|
||||
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
||||
let decoded = #arguments_ident::decode(arguments)
|
||||
.map_err(::wip_interface::DispatchError::Decode)?;
|
||||
let result = implementation.#method_ident(#(#arguments),*)
|
||||
.map_err(::wip_interface::DispatchError::Host)?;
|
||||
let encoded = #arguments_ident::encode_result(result)
|
||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||
descriptor
|
||||
.validate_return(#operation_name, encoded.as_ref())
|
||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
||||
::std::result::Result::Ok(encoded)
|
||||
::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
|
||||
let result = implementation.#method_ident(#(#arguments),*)
|
||||
.map_err(::wip_interface::DispatchError::Host)?;
|
||||
let encoded = #arguments_ident::encode_result(result)
|
||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||
descriptor
|
||||
.validate_result(#operation_name, &encoded)
|
||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
||||
::std::result::Result::Ok(encoded)
|
||||
}))
|
||||
.map_err(|_| ::wip_interface::DispatchError::Panic)?
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,7 +723,12 @@ fn derive_record(
|
||||
let mut parsed_fields = Vec::new();
|
||||
let mut names = HashSet::new();
|
||||
for field in fields {
|
||||
let field_ident = field.ident.clone().expect("named fields have identifiers");
|
||||
let Some(field_ident) = field.ident.clone() else {
|
||||
return Err(Error::new_spanned(
|
||||
field,
|
||||
"`WipType` record fields must be named",
|
||||
));
|
||||
};
|
||||
let name = source_name(&field_ident);
|
||||
if !names.insert(name.clone()) {
|
||||
return Err(Error::new(
|
||||
@@ -709,9 +756,9 @@ fn derive_record(
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::FieldDeclaration {
|
||||
name: ::std::string::String::from(#name),
|
||||
required: !#optional,
|
||||
documentation: #documentation,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
optional: #optional,
|
||||
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -727,18 +774,18 @@ fn derive_record(
|
||||
if field.optional {
|
||||
quote! {
|
||||
if let ::std::option::Option::Some(value) = #field_ident {
|
||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
||||
name: ::std::string::String::from(#field_name),
|
||||
value: <#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
});
|
||||
fields.insert(
|
||||
::std::string::String::from(#field_name),
|
||||
<#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
||||
name: ::std::string::String::from(#field_name),
|
||||
value: <#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
||||
});
|
||||
fields.insert(
|
||||
::std::string::String::from(#field_name),
|
||||
<#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -756,9 +803,9 @@ fn derive_record(
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -766,13 +813,13 @@ fn derive_record(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Record(
|
||||
::wip_interface::wip_protocol::RecordDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Record {
|
||||
fields: ::std::vec![#(#field_declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||
#(#dependency_collectors)*
|
||||
}
|
||||
@@ -785,7 +832,7 @@ fn derive_record(
|
||||
::wip_interface::CodecError,
|
||||
> {
|
||||
let Self { #(#destructured_fields),* } = self;
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
#(#encoders)*
|
||||
::std::result::Result::Ok(
|
||||
::wip_interface::wip_protocol::Value::Record(fields),
|
||||
@@ -797,7 +844,7 @@ fn derive_record(
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Record(fields) => {
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(fields)?;
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(fields);
|
||||
let decoded = Self {
|
||||
#(#decoders,)*
|
||||
};
|
||||
@@ -832,14 +879,14 @@ fn derive_enum(
|
||||
.variants
|
||||
.iter()
|
||||
.all(|variant| matches!(variant.fields, Fields::Unit));
|
||||
let all_payload = !data.variants.is_empty()
|
||||
&& data.variants.iter().all(|variant| {
|
||||
matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
||||
});
|
||||
let valid_union = data.variants.iter().all(|variant| {
|
||||
matches!(variant.fields, Fields::Unit)
|
||||
|| matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
||||
});
|
||||
|
||||
if all_unit {
|
||||
derive_unit_enum(ident, type_name, type_documentation, data)
|
||||
} else if all_payload {
|
||||
} else if valid_union {
|
||||
derive_union_enum(ident, type_name, type_documentation, data)
|
||||
} else {
|
||||
let span = data
|
||||
@@ -852,7 +899,7 @@ fn derive_enum(
|
||||
.map_or_else(|| data.enum_token.span, Spanned::span);
|
||||
Err(Error::new(
|
||||
span,
|
||||
"a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported",
|
||||
"a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -868,7 +915,7 @@ fn derive_unit_enum(
|
||||
let name = source_name(&variant.ident);
|
||||
let documentation = documentation_tokens(documentation(&variant.attrs).as_ref());
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::EnumVariantDeclaration {
|
||||
::wip_interface::wip_protocol::EnumCase {
|
||||
name: ::std::string::String::from(#name),
|
||||
documentation: #documentation,
|
||||
}
|
||||
@@ -888,9 +935,9 @@ fn derive_unit_enum(
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -898,13 +945,13 @@ fn derive_unit_enum(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Enum(
|
||||
::wip_interface::wip_protocol::EnumDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
variants: ::std::vec![#(#declarations),*],
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Enum {
|
||||
cases: ::std::vec![#(#declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
let _ = ::wip_interface::__private::register_declaration(
|
||||
declarations,
|
||||
declaration,
|
||||
@@ -921,7 +968,7 @@ fn derive_unit_enum(
|
||||
#(#encoders,)*
|
||||
};
|
||||
::std::result::Result::Ok(
|
||||
::wip_interface::wip_protocol::Value::Enum(
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(variant),
|
||||
),
|
||||
)
|
||||
@@ -931,7 +978,7 @@ fn derive_unit_enum(
|
||||
value: ::wip_interface::wip_protocol::Value,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Enum(variant) => {
|
||||
::wip_interface::wip_protocol::Value::String(variant) => {
|
||||
match variant.as_str() {
|
||||
#(#decoders,)*
|
||||
_ => ::std::result::Result::Err(
|
||||
@@ -960,30 +1007,36 @@ fn derive_union_enum(
|
||||
struct Variant<'a> {
|
||||
ident: &'a Ident,
|
||||
name: String,
|
||||
ty: &'a Type,
|
||||
payload: Option<&'a Type>,
|
||||
documentation: Option<Documentation>,
|
||||
}
|
||||
|
||||
let mut variants = Vec::new();
|
||||
for variant in &data.variants {
|
||||
let Fields::Unnamed(fields) = &variant.fields else {
|
||||
unreachable!("enum shape was checked before union generation");
|
||||
let payload = match &variant.fields {
|
||||
Fields::Unit => None,
|
||||
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
||||
let field = fields.unnamed.first().expect("length checked");
|
||||
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
||||
return Err(Error::new_spanned(
|
||||
&field.ty,
|
||||
"`Option<T>` is only supported directly on DTO fields and operation parameters",
|
||||
));
|
||||
}
|
||||
validate_value_type(&field.ty, "union case payload")?;
|
||||
Some(&field.ty)
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
variant,
|
||||
"a `WipType` union case must be unit-like or contain exactly one unnamed payload",
|
||||
));
|
||||
}
|
||||
};
|
||||
let field = fields
|
||||
.unnamed
|
||||
.first()
|
||||
.expect("union variants have one field");
|
||||
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
||||
return Err(Error::new_spanned(
|
||||
&field.ty,
|
||||
"`Option<T>` is only supported directly on DTO fields and operation parameters",
|
||||
));
|
||||
}
|
||||
validate_value_type(&field.ty, "union variant payload")?;
|
||||
variants.push(Variant {
|
||||
ident: &variant.ident,
|
||||
name: source_name(&variant.ident),
|
||||
ty: &field.ty,
|
||||
payload,
|
||||
documentation: documentation(&variant.attrs),
|
||||
});
|
||||
}
|
||||
@@ -992,50 +1045,95 @@ fn derive_union_enum(
|
||||
let declarations = variants.iter().map(|variant| {
|
||||
let name = &variant.name;
|
||||
let documentation = documentation_tokens(variant.documentation.as_ref());
|
||||
let ty = variant.ty;
|
||||
let payload = match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
::std::option::Option::Some(
|
||||
<#ty as ::wip_interface::WipType>::type_expr(),
|
||||
)
|
||||
},
|
||||
None => quote!(::std::option::Option::None),
|
||||
};
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::UnionVariantDeclaration {
|
||||
::wip_interface::wip_protocol::UnionCase {
|
||||
name: ::std::string::String::from(#name),
|
||||
documentation: #documentation,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
payload: #payload,
|
||||
}
|
||||
}
|
||||
});
|
||||
let dependency_collectors = variants.iter().map(|variant| {
|
||||
let ty = variant.ty;
|
||||
quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);)
|
||||
let dependency_collectors = variants.iter().filter_map(|variant| {
|
||||
variant.payload.map(
|
||||
|ty| quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);),
|
||||
)
|
||||
});
|
||||
let encoders = variants.iter().map(|variant| {
|
||||
let variant_ident = variant.ident;
|
||||
let name = &variant.name;
|
||||
let ty = variant.ty;
|
||||
quote! {
|
||||
Self::#variant_ident(value) => {
|
||||
::wip_interface::wip_protocol::Value::Union {
|
||||
variant: ::std::string::String::from(#name),
|
||||
value: ::std::boxed::Box::new(
|
||||
match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
Self::#variant_ident(value) => {
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
),
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(#name),
|
||||
),
|
||||
);
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_VALUE_FIELD,
|
||||
),
|
||||
<#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
),
|
||||
);
|
||||
::wip_interface::wip_protocol::Value::Record(fields)
|
||||
}
|
||||
}
|
||||
},
|
||||
None => quote! {
|
||||
Self::#variant_ident => {
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
),
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(#name),
|
||||
),
|
||||
);
|
||||
::wip_interface::wip_protocol::Value::Record(fields)
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
let decoders = variants.iter().map(|variant| {
|
||||
let variant_ident = variant.ident;
|
||||
let name = &variant.name;
|
||||
let ty = variant.ty;
|
||||
quote! {
|
||||
#name => <#ty as ::wip_interface::WipType>::decode(*value)
|
||||
.map(Self::#variant_ident)
|
||||
match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
#name => {
|
||||
let value = decoder.required::<#ty>(
|
||||
::wip_interface::wip_protocol::UNION_VALUE_FIELD,
|
||||
)?;
|
||||
decoder.finish()?;
|
||||
::std::result::Result::Ok(Self::#variant_ident(value))
|
||||
}
|
||||
},
|
||||
None => quote! {
|
||||
#name => {
|
||||
decoder.finish()?;
|
||||
::std::result::Result::Ok(Self::#variant_ident)
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -1043,13 +1141,13 @@ fn derive_union_enum(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Union(
|
||||
::wip_interface::wip_protocol::UnionDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
variants: ::std::vec![#(#declarations),*],
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Union {
|
||||
cases: ::std::vec![#(#declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||
#(#dependency_collectors)*
|
||||
}
|
||||
@@ -1071,26 +1169,30 @@ fn derive_union_enum(
|
||||
value: ::wip_interface::wip_protocol::Value,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Union { variant, value } => {
|
||||
match variant.as_str() {
|
||||
::wip_interface::wip_protocol::Value::Record(fields) => {
|
||||
let mut decoder =
|
||||
::wip_interface::__private::RecordDecoder::new(fields);
|
||||
let case = decoder.required::<::std::string::String>(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
)?;
|
||||
match case.as_str() {
|
||||
#(#decoders,)*
|
||||
_ => ::std::result::Result::Err(
|
||||
::wip_interface::__private::decode_unknown_variant(
|
||||
#type_name,
|
||||
variant,
|
||||
case,
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
actual => ::std::result::Result::Err(
|
||||
::wip_interface::__private::decode_type_mismatch("union", actual),
|
||||
::wip_interface::__private::decode_type_mismatch("union record", actual),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_type(ty: &Type, context: &str) -> syn::Result<(bool, Type)> {
|
||||
if let Some(inner) = direct_option(ty)? {
|
||||
if contains_option(&inner) {
|
||||
|
||||
+369
-110
@@ -30,37 +30,65 @@
|
||||
//!
|
||||
//! | Rust type | Protocol type/value |
|
||||
//! | --- | --- |
|
||||
//! | `()` as an operation result | no return declaration / no value |
|
||||
//! | `()` | `Unit` |
|
||||
//! | `bool` | `Boolean` |
|
||||
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
||||
//! | `f32`, `f64` | finite `Number` |
|
||||
//! | `String` | `String` |
|
||||
//! | [`Bytes`] | `Bytes` |
|
||||
//! | [`wip_protocol::JsonValue`] | `Json` |
|
||||
//! | [`Entry<K, V>`] | `Entry<K, V>` |
|
||||
//! | [`JsonValue`] | schema-neutral `Json` value tree |
|
||||
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
|
||||
//! | `Vec<T>` | `List<T>` |
|
||||
//! | a named-field struct deriving [`WipType`] | named record |
|
||||
//! | an all-unit enum deriving [`WipType`] | named enum |
|
||||
//! | an all-newtype enum deriving [`WipType`] | named tagged union |
|
||||
//! | an enum mixing unit and single-payload cases deriving [`WipType`] | named union |
|
||||
//!
|
||||
//! `Option<T>` is supported only directly as a record field or operation
|
||||
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||
//! an application return enum/union and is returned as `Ok(value)`.
|
||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
|
||||
//! [`HostErrorKind`] plus [`EffectGuarantee`]. The required [`OperationResult`]
|
||||
//! convention therefore keeps domain failures separate from runtime failures and
|
||||
//! makes outcome uncertainty visible to Host dispatch.
|
||||
//!
|
||||
//! # Migration to canonical values
|
||||
//!
|
||||
//! Earlier releases exposed `Entry<K, V>` and semantic `Value::Json`,
|
||||
//! `Value::Entry`, `Value::Enum`, and `Value::Union` variants. Those forms are
|
||||
//! intentionally gone: [`Entry`] is now one validated absolute Worldspace path,
|
||||
//! while JSON, enum, and union meaning comes only from the descriptor. Codecs
|
||||
//! exchange only raw [`Value`] strings, records, lists, and primitives. Unit
|
||||
//! operation results now cross the boundary as [`Value::Unit`] rather than an
|
||||
//! absent value.
|
||||
//!
|
||||
//! # Supported interface syntax
|
||||
//!
|
||||
//! An interface is a public, non-generic trait whose operations use exactly
|
||||
//! `&self`, simple named owned parameters, and an explicit
|
||||
//! `OperationResult<T>`. `WipType` derives support named-field structs,
|
||||
//! all-unit enums as protocol enums, and enums made from any mix of unit and
|
||||
//! single-payload cases as protocol unions.
|
||||
//!
|
||||
//! The macros reject trait inheritance and associated items; const, async,
|
||||
//! unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
|
||||
//! borrowed values and custom lifetimes; tuple, unit, or generic structs;
|
||||
//! unsupported named-field or multi-field enum variants; explicit discriminants; Rust unions;
|
||||
//! and `Option` anywhere except a direct DTO field or operation parameter.
|
||||
//! Unsupported inputs produce source-located compile errors rather than
|
||||
//! generating a partial interface.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
pub use wip_interface_macros::{WipType, interface};
|
||||
pub use wip_protocol;
|
||||
pub use wip_protocol::{
|
||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
||||
JsonMember, JsonValue, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NamedValue, OperationDeclaration,
|
||||
ParameterDeclaration, RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
||||
UnionDeclaration, UnionVariantDeclaration, ValidationError, Value,
|
||||
Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
|
||||
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
|
||||
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
|
||||
};
|
||||
|
||||
/// Converts one Rust application type to and from its protocol representation.
|
||||
@@ -92,35 +120,128 @@ pub trait InterfaceDefinition {
|
||||
fn descriptor() -> InterfaceDescriptor;
|
||||
}
|
||||
|
||||
/// Typed dispatch implemented by every generated interface companion.
|
||||
///
|
||||
/// `T` must implement the Rust interface trait associated with this definition.
|
||||
/// Host runtimes use this bound when an interface is explicitly exposed, so an
|
||||
/// object that does not implement that interface is rejected at compile time.
|
||||
pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
||||
/// Validates, decodes, and dispatches one operation to `implementation`,
|
||||
/// then encodes and validates its result.
|
||||
fn dispatch(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> Result<Value, DispatchError>;
|
||||
}
|
||||
|
||||
/// Result convention required for generated interface operations.
|
||||
///
|
||||
/// `Ok(T)` is an application result, including domain-failure union cases.
|
||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||
pub type OperationResult<T> = Result<T, HostError>;
|
||||
|
||||
/// A host/runtime failure, kept separate from the operation's application
|
||||
/// Whether an operation failure proves that no effects were committed.
|
||||
///
|
||||
/// This guarantee is consumed by Host dispatch when choosing a protocol failure:
|
||||
/// only [`NotCommitted`](Self::NotCommitted) failures may become `Internal` or
|
||||
/// `ResourceLimitExceeded`; [`Unknown`](Self::Unknown) failures must become
|
||||
/// `OperationOutcomeUnknown`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EffectGuarantee {
|
||||
/// The operation was not invoked, or every effect was rolled back.
|
||||
NotCommitted,
|
||||
/// The operation may have committed effects.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Host/runtime failure category used when effects are known not to be committed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostErrorKind {
|
||||
/// The Host or backend encountered an internal failure.
|
||||
Internal,
|
||||
/// A cancellation, deadline, or bounded resource limit was exceeded.
|
||||
ResourceLimitExceeded,
|
||||
}
|
||||
|
||||
/// A typed host/runtime failure, kept separate from the operation's application
|
||||
/// return type.
|
||||
///
|
||||
/// The effect guarantee is mandatory. Host runtimes must ignore the diagnostic
|
||||
/// when producing a wire response; it is bounded here for local observability but
|
||||
/// can still contain backend-private information.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostError {
|
||||
kind: HostErrorKind,
|
||||
effect_guarantee: EffectGuarantee,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl HostError {
|
||||
/// Creates a host failure with a human-readable diagnostic.
|
||||
/// Creates an internal Host failure with an explicit effect guarantee.
|
||||
#[must_use]
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||
Self::new(HostErrorKind::Internal, effect_guarantee, message)
|
||||
}
|
||||
|
||||
/// Creates a resource-limit Host failure with an explicit effect guarantee.
|
||||
#[must_use]
|
||||
pub fn resource_limit(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||
Self::new(
|
||||
HostErrorKind::ResourceLimitExceeded,
|
||||
effect_guarantee,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
fn new(
|
||||
kind: HostErrorKind,
|
||||
effect_guarantee: EffectGuarantee,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
kind,
|
||||
effect_guarantee,
|
||||
message: bounded_diagnostic(message.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the diagnostic message.
|
||||
/// Returns the typed Host failure category.
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> HostErrorKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// Returns the operation-effect guarantee attached by the implementation.
|
||||
#[must_use]
|
||||
pub fn effect_guarantee(&self) -> EffectGuarantee {
|
||||
self.effect_guarantee
|
||||
}
|
||||
|
||||
/// Returns the bounded local diagnostic message.
|
||||
///
|
||||
/// Host runtimes must not place this value in protocol responses because it
|
||||
/// can contain backend paths, credentials, or other private details.
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_DIAGNOSTIC_BYTES: usize = 512;
|
||||
|
||||
fn bounded_diagnostic(mut message: String) -> String {
|
||||
if message.len() <= MAX_DIAGNOSTIC_BYTES {
|
||||
return message;
|
||||
}
|
||||
let mut end = MAX_DIAGNOSTIC_BYTES;
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
message.truncate(end);
|
||||
message
|
||||
}
|
||||
|
||||
impl Display for HostError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
@@ -200,12 +321,59 @@ pub enum DispatchError {
|
||||
Decode(CodecError),
|
||||
/// The implementation reported a host/runtime failure.
|
||||
Host(HostError),
|
||||
/// The implementation panicked after invocation began.
|
||||
///
|
||||
/// Panic payloads are deliberately discarded because they can contain
|
||||
/// backend-private diagnostics.
|
||||
Panic,
|
||||
/// The Rust result could not be encoded.
|
||||
Encode(CodecError),
|
||||
/// The encoded result did not match the generated declaration.
|
||||
InvalidResult(wip_protocol::ValidationError),
|
||||
}
|
||||
|
||||
/// Whether generated dispatch failed before or after typed implementation
|
||||
/// invocation began.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DispatchPhase {
|
||||
/// Typed implementation code was not invoked.
|
||||
BeforeInvocation,
|
||||
/// Typed implementation invocation began, so effects require an explicit
|
||||
/// non-commit or rollback guarantee.
|
||||
AfterInvocation,
|
||||
}
|
||||
|
||||
impl DispatchError {
|
||||
/// Returns the execution phase in which this dispatch failure occurred.
|
||||
#[must_use]
|
||||
pub fn phase(&self) -> DispatchPhase {
|
||||
match self {
|
||||
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => {
|
||||
DispatchPhase::BeforeInvocation
|
||||
}
|
||||
Self::Host(_) | Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||
DispatchPhase::AfterInvocation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a post-invocation effect guarantee when the implementation
|
||||
/// supplied one.
|
||||
///
|
||||
/// Panic, encode, and result-validation failures default to `Unknown` until
|
||||
/// a provider confirms rollback. Pre-invocation failures return `None`.
|
||||
#[must_use]
|
||||
pub fn effect_guarantee(&self) -> Option<EffectGuarantee> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => None,
|
||||
Self::Host(error) => Some(error.effect_guarantee()),
|
||||
Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||
Some(EffectGuarantee::Unknown)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DispatchError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
@@ -215,6 +383,7 @@ impl Display for DispatchError {
|
||||
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
||||
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
||||
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
|
||||
Self::Panic => formatter.write_str("operation implementation panicked"),
|
||||
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
||||
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
||||
}
|
||||
@@ -224,7 +393,7 @@ impl Display for DispatchError {
|
||||
impl Error for DispatchError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) => None,
|
||||
Self::UnknownOperation(_) | Self::Panic => None,
|
||||
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
||||
Self::Decode(error) | Self::Encode(error) => Some(error),
|
||||
Self::Host(error) => Some(error),
|
||||
@@ -251,13 +420,101 @@ impl From<Bytes> for Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed protocol key/value entry.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry<K, V> {
|
||||
/// Entry key.
|
||||
pub key: K,
|
||||
/// Entry value.
|
||||
pub value: V,
|
||||
/// A canonical absolute path to an entry in the current Worldspace.
|
||||
///
|
||||
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
|
||||
/// entry from a path such as `/articles/1`; application data associated with
|
||||
/// that entry belongs in an ordinary record alongside this value.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Entry(String);
|
||||
|
||||
impl Entry {
|
||||
/// Validates and creates an entry path.
|
||||
pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
|
||||
let path = path.into();
|
||||
validate_entry_path(&path)?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
/// Returns the canonical absolute Worldspace path.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Consumes the entry and returns its path.
|
||||
#[must_use]
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Entry {
|
||||
type Error = CodecError;
|
||||
|
||||
fn try_from(path: String) -> Result<Self, Self::Error> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Entry {
|
||||
type Err = CodecError;
|
||||
|
||||
fn from_str(path: &str) -> Result<Self, Self::Err> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// One member in a [`JsonValue::Object`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct JsonMember {
|
||||
/// Member name.
|
||||
pub name: String,
|
||||
/// Member value.
|
||||
pub value: JsonValue,
|
||||
}
|
||||
|
||||
/// JSON data represented independently of any application schema.
|
||||
///
|
||||
/// Its codec uses the ordinary schema-neutral [`Value`] variants. JSON null is
|
||||
/// [`Value::Unit`], arrays are [`Value::List`], and objects are
|
||||
/// [`Value::Record`]. Protocol bytes have no JSON representation and decoding
|
||||
/// a tree containing [`Value::Bytes`] is rejected.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum JsonValue {
|
||||
/// JSON null.
|
||||
Null,
|
||||
/// A JSON boolean.
|
||||
Boolean(bool),
|
||||
/// An interoperable integral JSON number.
|
||||
Integer(i64),
|
||||
/// A finite non-integral JSON number.
|
||||
Number(f64),
|
||||
/// A JSON string.
|
||||
String(String),
|
||||
/// A JSON array.
|
||||
Array(Vec<JsonValue>),
|
||||
/// A JSON object. Duplicate member names are rejected while encoding.
|
||||
Object(Vec<JsonMember>),
|
||||
}
|
||||
|
||||
impl WipType for () {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Unit
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Unit)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Unit => Ok(()),
|
||||
other => Err(CodecError::expected("unit", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for bool {
|
||||
@@ -426,52 +683,87 @@ impl WipType for JsonValue {
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
validate_json(&self)?;
|
||||
Ok(Value::Json(self))
|
||||
encode_json(self)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Json(value) => {
|
||||
validate_json(&value)?;
|
||||
Ok(value)
|
||||
decode_json(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_json(value: JsonValue) -> Result<Value, CodecError> {
|
||||
match value {
|
||||
JsonValue::Null => Ok(Value::Unit),
|
||||
JsonValue::Boolean(value) => Ok(Value::Boolean(value)),
|
||||
JsonValue::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(Value::Integer(value))
|
||||
}
|
||||
JsonValue::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(Value::Number(value))
|
||||
}
|
||||
JsonValue::String(value) => Ok(Value::String(value)),
|
||||
JsonValue::Array(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| encode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(Value::List),
|
||||
JsonValue::Object(members) => {
|
||||
let mut fields = BTreeMap::new();
|
||||
for member in members {
|
||||
let name = member.name;
|
||||
let value = encode_json(member.value).map_err(|error| error.at(name.clone()))?;
|
||||
if fields.insert(name.clone(), value).is_some() {
|
||||
return Err(CodecError::new(format!("duplicate JSON member `{name}`")).at(name));
|
||||
}
|
||||
}
|
||||
other => Err(CodecError::expected("json", &other)),
|
||||
Ok(Value::Record(fields))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_json(value: &JsonValue) -> Result<(), CodecError> {
|
||||
fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
|
||||
match value {
|
||||
JsonValue::Integer(value) => ensure_safe_integer(*value),
|
||||
JsonValue::Number(value) => ensure_finite(*value),
|
||||
JsonValue::Array(values) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
validate_json(value).map_err(|error| error.at(index.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Unit => Ok(JsonValue::Null),
|
||||
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
|
||||
Value::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(JsonValue::Integer(value))
|
||||
}
|
||||
JsonValue::Object(members) => {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for member in members {
|
||||
if !names.insert(member.name.as_str()) {
|
||||
return Err(CodecError::new(format!(
|
||||
"duplicate JSON member `{}`",
|
||||
member.name
|
||||
))
|
||||
.at(member.name.clone()));
|
||||
}
|
||||
validate_json(&member.value).map_err(|error| error.at(member.name.clone()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(JsonValue::Number(value))
|
||||
}
|
||||
JsonValue::Null | JsonValue::Boolean(_) | JsonValue::String(_) => Ok(()),
|
||||
Value::String(value) => Ok(JsonValue::String(value)),
|
||||
Value::Bytes(_) => Err(CodecError::new("bytes are not valid inside JSON")),
|
||||
Value::List(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| decode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Array),
|
||||
Value::Record(fields) => fields
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
decode_json(value)
|
||||
.map(|value| JsonMember {
|
||||
name: name.clone(),
|
||||
value,
|
||||
})
|
||||
.map_err(|error| error.at(name))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Object),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: WipType> WipType for Vec<T> {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::List(Box::new(T::type_expr()))
|
||||
TypeExpr::List {
|
||||
items: Box::new(T::type_expr()),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
@@ -498,37 +790,31 @@ impl<T: WipType> WipType for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
impl WipType for Entry {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Entry {
|
||||
key: Box::new(K::type_expr()),
|
||||
value: Box::new(V::type_expr()),
|
||||
}
|
||||
TypeExpr::Entry
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
K::collect_declarations(declarations);
|
||||
V::collect_declarations(declarations);
|
||||
}
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Entry {
|
||||
key: Box::new(self.key.encode().map_err(|error| error.at("key"))?),
|
||||
value: Box::new(self.value.encode().map_err(|error| error.at("value"))?),
|
||||
})
|
||||
validate_entry_path(&self.0)?;
|
||||
Ok(Value::String(self.0))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::Entry { key, value } = value else {
|
||||
return Err(CodecError::expected("entry", &value));
|
||||
let Value::String(path) = value else {
|
||||
return Err(CodecError::expected("entry path string", &value));
|
||||
};
|
||||
Ok(Self {
|
||||
key: K::decode(*key).map_err(|error| error.at("key"))?,
|
||||
value: V::decode(*value).map_err(|error| error.at("value"))?,
|
||||
})
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_entry_path(path: &str) -> Result<(), CodecError> {
|
||||
wip_protocol::validate_path(path)
|
||||
.map_err(|error| CodecError::new(format!("invalid canonical Worldspace path: {error}")))
|
||||
}
|
||||
|
||||
/// Implementation details used by code emitted from the facade's macros.
|
||||
///
|
||||
/// These APIs are public only because macro expansions execute in the
|
||||
@@ -536,12 +822,9 @@ impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
/// and are not intended for direct use.
|
||||
#[doc(hidden)]
|
||||
pub mod __private {
|
||||
use std::collections::HashSet;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_protocol::{
|
||||
InterfaceDescriptor, NamedValue, ObjectId, OperationCall, OperationTarget, TypeDeclaration,
|
||||
ValidationError, Value,
|
||||
};
|
||||
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
|
||||
|
||||
use crate::{CodecError, Documentation, WipType};
|
||||
|
||||
@@ -576,16 +859,9 @@ pub mod __private {
|
||||
pub fn validate_arguments(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
arguments: &[NamedValue],
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(&OperationCall {
|
||||
target: OperationTarget {
|
||||
object: ObjectId("<typed-dispatch>".into()),
|
||||
interface: descriptor.name.clone(),
|
||||
operation: operation.into(),
|
||||
},
|
||||
arguments: arguments.to_vec(),
|
||||
})
|
||||
descriptor.validate_arguments(operation, arguments)
|
||||
}
|
||||
|
||||
/// Builds a codec error for a generated structural mismatch.
|
||||
@@ -603,22 +879,13 @@ pub mod __private {
|
||||
|
||||
/// Decoder for a protocol record or operation's named argument collection.
|
||||
pub struct RecordDecoder {
|
||||
fields: Vec<NamedValue>,
|
||||
seen: HashSet<String>,
|
||||
fields: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
impl RecordDecoder {
|
||||
/// Starts decoding record fields or named operation arguments and
|
||||
/// rejects duplicate names.
|
||||
pub fn new(fields: Vec<NamedValue>) -> Result<Self, CodecError> {
|
||||
let mut seen = HashSet::new();
|
||||
for field in &fields {
|
||||
if !seen.insert(field.name.clone()) {
|
||||
return Err(CodecError::new(format!("duplicate field `{}`", field.name))
|
||||
.at(field.name.clone()));
|
||||
}
|
||||
}
|
||||
Ok(Self { fields, seen })
|
||||
/// Starts decoding record fields or named operation arguments.
|
||||
pub fn new(fields: BTreeMap<String, Value>) -> Self {
|
||||
Self { fields }
|
||||
}
|
||||
|
||||
/// Decodes a required field.
|
||||
@@ -639,23 +906,15 @@ pub mod __private {
|
||||
|
||||
/// Rejects any fields that were not consumed by generated code.
|
||||
pub fn finish(self) -> Result<(), CodecError> {
|
||||
if let Some(field) = self.fields.first() {
|
||||
Err(CodecError::new(format!("unknown field `{}`", field.name))
|
||||
.at(field.name.clone()))
|
||||
if let Some(name) = self.fields.keys().next() {
|
||||
Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, name: &str) -> Option<Value> {
|
||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
||||
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
|
||||
self.fields.remove(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use wip_interface::wip_protocol::{
|
||||
EnumDeclaration, JsonMember, JsonValue, NamedValue, RecordDeclaration, TypeDeclaration,
|
||||
TypeExpr, UnionDeclaration, Value,
|
||||
};
|
||||
use wip_interface::{Bytes, Entry, WipType};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, Value};
|
||||
use wip_interface::{Bytes, Entry, JsonMember, JsonValue, WipType};
|
||||
|
||||
/// A request record.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -11,8 +10,8 @@ struct Request {
|
||||
title: String,
|
||||
/// Optional priority.
|
||||
priority: Option<i32>,
|
||||
/// Related entries.
|
||||
related: Vec<Entry<String, bool>>,
|
||||
/// Related Worldspace entries.
|
||||
related: Vec<Entry>,
|
||||
/// Opaque bytes.
|
||||
body: Bytes,
|
||||
/// Arbitrary metadata.
|
||||
@@ -38,33 +37,53 @@ struct Receipt {
|
||||
/// Application-level publication outcome.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
enum PublishOutcome {
|
||||
/// Work has not completed and carries no payload.
|
||||
Pending,
|
||||
/// Application success.
|
||||
Published(Receipt),
|
||||
/// Domain rejection, not a host failure.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
fn field<'a>(record: &'a BTreeMap<String, Value>, name: &str) -> &'a Value {
|
||||
record
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("missing `{name}`"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_values_round_trip() {
|
||||
fn primitive_unit_record_list_entry_and_json_values_round_trip() {
|
||||
assert_eq!(().encode().unwrap(), Value::Unit);
|
||||
assert_eq!(<()>::decode(Value::Unit).unwrap(), ());
|
||||
assert_eq!(<()>::type_expr(), TypeExpr::Unit);
|
||||
|
||||
let request = Request {
|
||||
title: "hello".into(),
|
||||
priority: None,
|
||||
related: vec![Entry {
|
||||
key: "/articles/1".into(),
|
||||
value: true,
|
||||
}],
|
||||
related: vec![Entry::new("/articles/1").unwrap()],
|
||||
body: Bytes(vec![1, 2, 3]),
|
||||
metadata: JsonValue::Object(vec![JsonMember {
|
||||
name: "source".into(),
|
||||
value: JsonValue::String("test".into()),
|
||||
value: JsonValue::Array(vec![JsonValue::String("test".into()), JsonValue::Null]),
|
||||
}]),
|
||||
};
|
||||
|
||||
let encoded = request.clone().encode().unwrap();
|
||||
let Value::Record(fields) = &encoded else {
|
||||
panic!("record derive must encode a protocol record")
|
||||
panic!("record derive must encode a raw protocol record")
|
||||
};
|
||||
assert!(fields.iter().all(|field| field.name != "priority"));
|
||||
assert!(!fields.contains_key("priority"));
|
||||
assert_eq!(
|
||||
field(fields, "related"),
|
||||
&Value::List(vec![Value::String("/articles/1".into())])
|
||||
);
|
||||
assert_eq!(
|
||||
field(fields, "metadata"),
|
||||
&Value::Record(BTreeMap::from([(
|
||||
"source".into(),
|
||||
Value::List(vec![Value::String("test".into()), Value::Unit]),
|
||||
)]))
|
||||
);
|
||||
assert_eq!(Request::decode(encoded).unwrap(), request);
|
||||
|
||||
let number = 42.5_f64;
|
||||
@@ -77,92 +96,136 @@ fn supported_values_round_trip() {
|
||||
f32::decode(narrow_number.encode().unwrap()).unwrap(),
|
||||
narrow_number
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enums_are_strings_and_unions_are_discriminated_records() {
|
||||
for color in [Color::Red, Color::Blue] {
|
||||
let encoded = color.clone().encode().unwrap();
|
||||
let decoded = Color::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, color);
|
||||
assert!(matches!(encoded, Value::String(_)));
|
||||
assert_eq!(Color::decode(encoded).unwrap(), color);
|
||||
}
|
||||
|
||||
let pending = PublishOutcome::Pending.encode().unwrap();
|
||||
assert_eq!(
|
||||
pending,
|
||||
Value::Record(BTreeMap::from([(
|
||||
UNION_CASE_FIELD.into(),
|
||||
Value::String("Pending".into()),
|
||||
)]))
|
||||
);
|
||||
|
||||
let published = PublishOutcome::Published(Receipt { number: 7 })
|
||||
.encode()
|
||||
.unwrap();
|
||||
let Value::Record(fields) = &published else {
|
||||
panic!("union must encode as a record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields.get(UNION_CASE_FIELD),
|
||||
Some(&Value::String("Published".into()))
|
||||
);
|
||||
assert!(matches!(
|
||||
fields.get(UNION_VALUE_FIELD),
|
||||
Some(Value::Record(_))
|
||||
));
|
||||
|
||||
for outcome in [
|
||||
PublishOutcome::Pending,
|
||||
PublishOutcome::Published(Receipt { number: 7 }),
|
||||
PublishOutcome::Rejected("policy".into()),
|
||||
] {
|
||||
let encoded = outcome.clone().encode().unwrap();
|
||||
let decoded = PublishOutcome::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, outcome);
|
||||
assert_eq!(PublishOutcome::decode(encoded).unwrap(), outcome);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_declarations_include_docs_optionality_and_dependencies() {
|
||||
fn derived_declarations_use_canonical_named_type_expressions() {
|
||||
let mut declarations = Vec::new();
|
||||
Request::collect_declarations(&mut declarations);
|
||||
Color::collect_declarations(&mut declarations);
|
||||
PublishOutcome::collect_declarations(&mut declarations);
|
||||
|
||||
let TypeDeclaration::Record(RecordDeclaration {
|
||||
documentation,
|
||||
fields,
|
||||
..
|
||||
}) = &declarations[0]
|
||||
else {
|
||||
let request = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name == "Request")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request.documentation.as_ref().unwrap().summary,
|
||||
"A request record."
|
||||
);
|
||||
let TypeExpr::Record { fields } = &request.definition else {
|
||||
panic!("Request must be a record declaration")
|
||||
};
|
||||
assert_eq!(documentation.as_ref().unwrap().summary, "A request record.");
|
||||
assert_eq!(
|
||||
fields[0].documentation.as_ref().unwrap().summary,
|
||||
"Required title."
|
||||
);
|
||||
assert!(!fields[0].optional);
|
||||
assert!(fields[1].optional);
|
||||
assert_eq!(fields[1].ty, TypeExpr::Integer);
|
||||
assert!(fields[0].required);
|
||||
assert!(!fields[1].required);
|
||||
assert_eq!(fields[1].r#type, TypeExpr::Integer);
|
||||
assert_eq!(
|
||||
fields[2].ty,
|
||||
TypeExpr::List(Box::new(TypeExpr::Entry {
|
||||
key: Box::new(TypeExpr::String),
|
||||
value: Box::new(TypeExpr::Boolean),
|
||||
}))
|
||||
fields[2].r#type,
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Entry),
|
||||
}
|
||||
);
|
||||
|
||||
let color = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "Color")
|
||||
.find(|declaration| declaration.name == "Color")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Enum(EnumDeclaration { variants, .. }) = color else {
|
||||
let TypeExpr::Enum { cases } = &color.definition else {
|
||||
panic!("Color must be an enum declaration")
|
||||
};
|
||||
assert_eq!(
|
||||
variants[0].documentation.as_ref().unwrap().summary,
|
||||
cases[0].documentation.as_ref().unwrap().summary,
|
||||
"Warm red."
|
||||
);
|
||||
|
||||
let outcome = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "PublishOutcome")
|
||||
.find(|declaration| declaration.name == "PublishOutcome")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Union(UnionDeclaration { variants, .. }) = outcome else {
|
||||
let TypeExpr::Union { cases } = &outcome.definition else {
|
||||
panic!("PublishOutcome must be a union declaration")
|
||||
};
|
||||
assert_eq!(variants[0].ty, TypeExpr::Named("Receipt".into()));
|
||||
assert_eq!(cases[0].payload, None);
|
||||
assert_eq!(
|
||||
cases[1].payload,
|
||||
Some(TypeExpr::Named {
|
||||
name: "Receipt".into(),
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
declarations
|
||||
.iter()
|
||||
.any(|declaration| declaration.name() == "Receipt")
|
||||
.any(|declaration| declaration.name == "Receipt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_reject_invalid_boundaries() {
|
||||
fn codecs_reject_invalid_boundaries_and_json_bytes() {
|
||||
assert!(i64::MAX.encode().is_err());
|
||||
assert!(f64::NAN.encode().is_err());
|
||||
assert!(Request::decode(Value::Record(vec![])).is_err());
|
||||
assert!(Request::decode(Value::Record(BTreeMap::new())).is_err());
|
||||
assert!(
|
||||
Request::decode(Value::Record(vec![NamedValue {
|
||||
name: "unknown".into(),
|
||||
value: Value::String("value".into()),
|
||||
}]))
|
||||
Request::decode(Value::Record(BTreeMap::from([(
|
||||
"unknown".into(),
|
||||
Value::String("value".into()),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::String("Green".into())).is_err());
|
||||
assert!(Entry::new("articles/1").is_err());
|
||||
assert!(Entry::decode(Value::String("/articles/../1".into())).is_err());
|
||||
assert!(JsonValue::decode(Value::Bytes(vec![1])).is_err());
|
||||
assert!(
|
||||
JsonValue::decode(Value::Record(BTreeMap::from([(
|
||||
"nested".into(),
|
||||
Value::List(vec![Value::Bytes(vec![1])]),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::Enum("Green".into())).is_err());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
use wip_interface::wip_protocol::{NamedValue, TypeDeclaration, TypeExpr, Value};
|
||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||
use wip_interface::{
|
||||
DispatchError, DispatchPhase, EffectGuarantee, HostError, HostErrorKind, OperationResult,
|
||||
WipType, interface,
|
||||
};
|
||||
|
||||
/// Publication request.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -36,7 +41,7 @@ pub trait Catalog {
|
||||
note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome>;
|
||||
|
||||
/// Checks connectivity without returning an application value.
|
||||
/// Checks connectivity without returning application data.
|
||||
fn ping(&self) -> OperationResult<()>;
|
||||
|
||||
/// Demonstrates a host/runtime failure.
|
||||
@@ -64,7 +69,10 @@ impl Catalog for AcceptingCatalog {
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
Err(HostError::new("backend unavailable"))
|
||||
Err(HostError::internal(
|
||||
"backend unavailable",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,36 +96,49 @@ impl Catalog for RejectingCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
fn named(name: &str, value: Value) -> NamedValue {
|
||||
NamedValue {
|
||||
name: name.into(),
|
||||
value,
|
||||
struct PanickingCatalog;
|
||||
|
||||
impl Catalog for PanickingCatalog {
|
||||
fn publish(
|
||||
&self,
|
||||
_request: PublishRequest,
|
||||
_note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn ping(&self) -> OperationResult<()> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_arguments(with_note: bool) -> Vec<NamedValue> {
|
||||
let mut arguments = vec![named(
|
||||
"request",
|
||||
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||
let mut arguments = BTreeMap::from([(
|
||||
"request".into(),
|
||||
PublishRequest {
|
||||
title: "example".into(),
|
||||
}
|
||||
.encode()
|
||||
.unwrap(),
|
||||
)];
|
||||
)]);
|
||||
if with_note {
|
||||
arguments.push(named("note", Value::String("audit".into())));
|
||||
arguments.insert("note".into(), Value::String("audit".into()));
|
||||
}
|
||||
arguments
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
fn descriptor_is_canonical_and_generated_only_from_the_trait_declaration() {
|
||||
let first = CatalogDefinition::descriptor();
|
||||
let second = CatalogDefinition::descriptor();
|
||||
assert_eq!(first, second);
|
||||
first.validate().unwrap();
|
||||
|
||||
assert_eq!(first.name, "Catalog");
|
||||
assert_eq!(first.format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
first.documentation.as_ref().unwrap().summary,
|
||||
"Catalog editing capability."
|
||||
@@ -139,84 +160,110 @@ fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
.summary,
|
||||
"Item to publish."
|
||||
);
|
||||
assert!(!publish.parameters[0].optional);
|
||||
assert!(publish.parameters[1].optional);
|
||||
assert!(publish.parameters[0].required);
|
||||
assert!(!publish.parameters[1].required);
|
||||
assert_eq!(
|
||||
publish
|
||||
.returns
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.summary,
|
||||
publish.returns.documentation.as_ref().unwrap().summary,
|
||||
"The application publication outcome."
|
||||
);
|
||||
assert_eq!(
|
||||
publish.returns.as_ref().unwrap().ty,
|
||||
TypeExpr::Named("PublishOutcome".into())
|
||||
publish.returns.r#type,
|
||||
TypeExpr::Named {
|
||||
name: "PublishOutcome".into(),
|
||||
}
|
||||
);
|
||||
assert!(first.operations[1].returns.is_none());
|
||||
assert_eq!(first.operations[1].returns.r#type, TypeExpr::Unit);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Record(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Record { .. }))
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Union(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Union { .. }))
|
||||
);
|
||||
|
||||
// Both implementation types satisfy the same generated dispatch boundary;
|
||||
// neither can affect the descriptor shape.
|
||||
// Both implementation types satisfy one immutable generated definition;
|
||||
// implementation selection cannot contribute fields to the descriptor.
|
||||
fn accepts_definition<T: Catalog>(_: &T) {}
|
||||
accepts_definition(&AcceptingCatalog);
|
||||
accepts_definition(&RejectingCatalog);
|
||||
assert_eq!(CatalogDefinition::descriptor(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_argument_decoder_and_result_encoder_round_trip() {
|
||||
fn generated_argument_decoder_and_result_encoder_use_raw_values() {
|
||||
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
|
||||
assert_eq!(decoded.request.title, "example");
|
||||
assert_eq!(decoded.note, None);
|
||||
|
||||
let encoded = CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let encoded =
|
||||
CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into())).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(encoded).unwrap(),
|
||||
PublishOutcome::Rejected("domain".into())
|
||||
);
|
||||
assert_eq!(
|
||||
CatalogPingArguments::encode_result(()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||
let value = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let value =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true)).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(value).unwrap(),
|
||||
PublishOutcome::Published(true)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", vec![]).unwrap(),
|
||||
None
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", BTreeMap::new()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
|
||||
let invalid = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", vec![]).unwrap_err();
|
||||
let invalid =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||
assert_eq!(invalid.phase(), DispatchPhase::BeforeInvocation);
|
||||
assert_eq!(invalid.effect_guarantee(), None);
|
||||
|
||||
let host = CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", vec![]).unwrap_err();
|
||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
||||
let host =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(
|
||||
matches!(&host, DispatchError::Host(error) if error.message() == "backend unavailable")
|
||||
);
|
||||
assert_eq!(host.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(host.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
|
||||
let unknown = CatalogDefinition::dispatch(&AcceptingCatalog, "missing", vec![]).unwrap_err();
|
||||
let panic =
|
||||
CatalogDefinition::dispatch(&PanickingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(panic, DispatchError::Panic));
|
||||
assert_eq!(panic.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(panic.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
assert!(!panic.to_string().contains("private panic payload"));
|
||||
|
||||
let unknown =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_errors_require_a_typed_kind_and_effect_guarantee() {
|
||||
let internal = HostError::internal("x".repeat(4_096), EffectGuarantee::NotCommitted);
|
||||
assert_eq!(internal.kind(), HostErrorKind::Internal);
|
||||
assert_eq!(internal.effect_guarantee(), EffectGuarantee::NotCommitted);
|
||||
assert!(internal.message().len() <= 512);
|
||||
|
||||
let resource = HostError::resource_limit("deadline", EffectGuarantee::Unknown);
|
||||
assert_eq!(resource.kind(), HostErrorKind::ResourceLimitExceeded);
|
||||
assert_eq!(resource.effect_guarantee(), EffectGuarantee::Unknown);
|
||||
}
|
||||
|
||||
/// Operations whose distinct source names normalize to the same PascalCase.
|
||||
#[interface]
|
||||
pub trait DistinctOperations {
|
||||
@@ -245,12 +292,12 @@ fn distinct_operation_names_always_generate_distinct_public_items() {
|
||||
assert_eq!(descriptor.operations[0].name, "item");
|
||||
assert_eq!(descriptor.operations[1].name, "item_");
|
||||
|
||||
let first = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let second = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let first =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", BTreeMap::new())
|
||||
.unwrap();
|
||||
let second =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", BTreeMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(first, Value::String("item".into()));
|
||||
assert_eq!(second, Value::String("item_".into()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::interface;
|
||||
|
||||
#[interface]
|
||||
pub trait AsyncOperation {
|
||||
async fn status(&self) -> wip_interface::OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: async operations are not supported
|
||||
--> tests/ui/async_operation.rs:5:5
|
||||
|
|
||||
5 | async fn status(&self) -> wip_interface::OperationResult<String>;
|
||||
| ^^^^^
|
||||
@@ -0,0 +1,10 @@
|
||||
use wip_interface::interface;
|
||||
|
||||
#[interface]
|
||||
pub trait DefaultMethod {
|
||||
fn status(&self) -> wip_interface::OperationResult<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
error: WIP operation methods must not have a body
|
||||
--> tests/ui/default_method.rs:5:64
|
||||
|
|
||||
5 | fn status(&self) -> wip_interface::OperationResult<String> {
|
||||
| ________________________________________________________________^
|
||||
6 | | Ok(String::new())
|
||||
7 | | }
|
||||
| |_____^
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
struct GenericDto<T> {
|
||||
value: T,
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: generic DTOs are not supported by `WipType`
|
||||
--> tests/ui/generic_dto.rs:4:18
|
||||
|
|
||||
4 | struct GenericDto<T> {
|
||||
| ^^^
|
||||
@@ -1,9 +1,9 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
enum MixedEnum {
|
||||
enum UnsupportedEnum {
|
||||
Empty,
|
||||
Payload(String),
|
||||
Payload { value: String },
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:4:1
|
||||
error: a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:6:5
|
||||
|
|
||||
4 | enum MixedEnum {
|
||||
| ^^^^
|
||||
6 | Payload { value: String },
|
||||
| ^^^^^^^
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
struct NestedOption {
|
||||
values: Vec<Option<String>>,
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: `Option<T>` must appear directly as the DTO field type
|
||||
--> tests/ui/nested_option.rs:5:13
|
||||
|
|
||||
5 | values: Vec<Option<String>>,
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
@@ -4,16 +4,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||
--> tests/ui/unsupported_type.rs:5:26
|
||||
@@ -24,16 +19,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
||||
--> src/lib.rs
|
||||
|
|
||||
|
||||
@@ -8,79 +8,65 @@ pub enum NameNamespace {
|
||||
TypeDeclaration,
|
||||
/// Operations in an interface descriptor.
|
||||
Operation,
|
||||
/// Fields in a record declaration.
|
||||
/// Fields in an inline or named record type.
|
||||
Field,
|
||||
/// Parameters in an operation declaration.
|
||||
Parameter,
|
||||
/// Variants in an enum declaration.
|
||||
EnumVariant,
|
||||
/// Variants in a union declaration.
|
||||
UnionVariant,
|
||||
/// Fields supplied in a record value.
|
||||
RecordValueField,
|
||||
/// Arguments supplied in an operation call.
|
||||
Argument,
|
||||
/// Members in a logical JSON object.
|
||||
JsonMember,
|
||||
/// Descriptors in an interface observation.
|
||||
InterfaceDescriptor,
|
||||
/// Cases in an enum type.
|
||||
EnumCase,
|
||||
/// Cases in a union type.
|
||||
UnionCase,
|
||||
/// Child object names beneath one tree node.
|
||||
ChildObject,
|
||||
}
|
||||
|
||||
/// Structural kind of a logical protocol value.
|
||||
/// Structural kind of a schema-neutral logical value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueKind {
|
||||
/// String value.
|
||||
String,
|
||||
/// Unit value.
|
||||
Unit,
|
||||
/// Boolean value.
|
||||
Boolean,
|
||||
/// Integer value.
|
||||
Integer,
|
||||
/// Floating-point number value.
|
||||
Number,
|
||||
/// String value.
|
||||
String,
|
||||
/// Byte sequence.
|
||||
Bytes,
|
||||
/// List value.
|
||||
List,
|
||||
/// Key/value entry.
|
||||
Entry,
|
||||
/// Record value.
|
||||
Record,
|
||||
/// Enum value.
|
||||
Enum,
|
||||
/// Tagged-union value.
|
||||
Union,
|
||||
/// Logical JSON value.
|
||||
Json,
|
||||
/// List value.
|
||||
List,
|
||||
}
|
||||
|
||||
/// A typed segment identifying a declaration or value location.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PathSegment {
|
||||
/// Interface descriptor.
|
||||
Interface(String),
|
||||
/// Descriptor root.
|
||||
Descriptor,
|
||||
/// Named type declaration.
|
||||
Declaration(String),
|
||||
/// Operation declaration or call.
|
||||
Operation(String),
|
||||
/// Record field declaration or value.
|
||||
Field(String),
|
||||
/// Operation parameter declaration or argument.
|
||||
/// Operation parameter or argument.
|
||||
Parameter(String),
|
||||
/// Enum or union variant.
|
||||
Variant(String),
|
||||
/// List or JSON array index.
|
||||
/// Enum or union case.
|
||||
Case(String),
|
||||
/// List index.
|
||||
Index(usize),
|
||||
/// Entry key.
|
||||
EntryKey,
|
||||
/// Entry value.
|
||||
EntryValue,
|
||||
/// Operation return value.
|
||||
Return,
|
||||
/// JSON object member.
|
||||
JsonMember(String),
|
||||
/// Object at a Worldspace path.
|
||||
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)]
|
||||
pub enum ValidationErrorKind {
|
||||
/// A name occurred more than once in one namespace.
|
||||
@@ -117,11 +103,15 @@ pub enum ValidationErrorKind {
|
||||
/// Missing field name.
|
||||
name: String,
|
||||
},
|
||||
/// An enum or union value selected an undeclared variant.
|
||||
UnknownVariant {
|
||||
/// Unknown variant name.
|
||||
/// An enum or union selected an undeclared case.
|
||||
UnknownCase {
|
||||
/// Unknown case name.
|
||||
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.
|
||||
UnknownParameter {
|
||||
/// Unknown parameter name.
|
||||
@@ -132,44 +122,66 @@ pub enum ValidationErrorKind {
|
||||
/// Missing parameter name.
|
||||
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 {
|
||||
/// Rejected integer.
|
||||
value: i64,
|
||||
},
|
||||
/// A numeric value is NaN or infinite.
|
||||
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.
|
||||
DuplicateInterface {
|
||||
/// Duplicate interface name.
|
||||
name: String,
|
||||
/// Duplicate opaque interface reference.
|
||||
reference: String,
|
||||
},
|
||||
/// An observation omits a descriptor named by its object.
|
||||
MissingInterfaceDescriptor {
|
||||
/// Missing interface name.
|
||||
name: String,
|
||||
/// A string is not a canonical absolute Worldspace path.
|
||||
InvalidPath {
|
||||
/// Rejected path.
|
||||
path: String,
|
||||
},
|
||||
/// An observation contains a descriptor not named by its object.
|
||||
UnexpectedInterfaceDescriptor {
|
||||
/// Unexpected interface name.
|
||||
name: String,
|
||||
},
|
||||
/// A call targets an interface other than the descriptor being used.
|
||||
InterfaceMismatch {
|
||||
/// Descriptor interface name.
|
||||
/// An object name does not match the path where it was observed.
|
||||
ObjectNameMismatch {
|
||||
/// Name required by the observation path.
|
||||
expected: String,
|
||||
/// Call target interface name.
|
||||
/// Name supplied by the object.
|
||||
actual: String,
|
||||
},
|
||||
/// An operation is not declared by the interface.
|
||||
UnknownOperation {
|
||||
/// Unknown operation name.
|
||||
name: String,
|
||||
/// Equivalent ref/validator observations disagree on object representation.
|
||||
InconsistentObjectObservation {
|
||||
/// Shared opaque object reference.
|
||||
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.
|
||||
@@ -211,30 +223,152 @@ impl Display for ValidationError {
|
||||
|
||||
impl Error for ValidationError {}
|
||||
|
||||
/// Stable category of an error returned by a protocol host runtime.
|
||||
/// One core interaction whose failure codes form a closed set.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProtocolErrorCategory {
|
||||
/// The request is structurally invalid.
|
||||
InvalidRequest,
|
||||
/// The target object is not published.
|
||||
ObjectNotFound,
|
||||
/// The target interface is not implemented by the object.
|
||||
InterfaceNotFound,
|
||||
/// The target operation is not declared by the interface.
|
||||
OperationNotFound,
|
||||
/// Supplied operation arguments are invalid.
|
||||
InvalidArguments,
|
||||
/// The implementation rejected the call for a domain reason.
|
||||
OperationFailed,
|
||||
/// The host encountered an internal failure.
|
||||
Internal,
|
||||
pub enum ProtocolInteraction {
|
||||
/// Fetch one object by its Worldspace path.
|
||||
Fetch,
|
||||
/// Fetch a bounded tree of objects.
|
||||
FetchTree,
|
||||
/// Fetch one interface descriptor by its opaque reference.
|
||||
FetchInterface,
|
||||
/// Invoke one operation on a path-targeted object.
|
||||
CallOperation,
|
||||
}
|
||||
|
||||
/// Transport-independent protocol failure returned by a host runtime.
|
||||
/// Stable protocol failure code returned by a host.
|
||||
///
|
||||
/// This is the complete wire-level code set. A Client treats a malformed success
|
||||
/// or failure response, including a code disallowed for its interaction, as a
|
||||
/// Client-local `InvalidResponse`. An unsupported descriptor format is likewise
|
||||
/// a Client-local `UnsupportedDescriptorFormat`; neither condition is a code a
|
||||
/// Host can return.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProtocolErrorCode {
|
||||
/// The request is structurally invalid before an operation descriptor is fixed.
|
||||
InvalidRequest,
|
||||
/// The target object is not published.
|
||||
NotFound,
|
||||
/// The interface reference is not currently published.
|
||||
InterfaceNotFound,
|
||||
/// The selected interface is not on the current object.
|
||||
InterfaceMismatch,
|
||||
/// The selected operation is not declared by the current interface.
|
||||
OperationNotFound,
|
||||
/// Supplied arguments do not match the fixed operation declaration.
|
||||
InvalidArguments,
|
||||
/// The operation requires an object validator and none was supplied.
|
||||
ValidatorRequired,
|
||||
/// The supplied object validator does not match current state.
|
||||
ValidatorMismatch,
|
||||
/// A mutable interface requires its validator and none was supplied.
|
||||
InterfaceValidatorRequired,
|
||||
/// The supplied interface validator does not match the descriptor.
|
||||
InterfaceValidatorMismatch,
|
||||
/// A published operation is not permitted for the caller.
|
||||
PermissionDenied,
|
||||
/// A bounded protocol resource limit was exceeded.
|
||||
///
|
||||
/// For `call_operation`, the Host guarantees that the operation was not run
|
||||
/// or that all of its effects were rolled back.
|
||||
ResourceLimitExceeded,
|
||||
/// The Host encountered an internal failure.
|
||||
///
|
||||
/// For `call_operation`, the Host guarantees that the operation was not run
|
||||
/// or that all of its effects were rolled back.
|
||||
Internal,
|
||||
/// The Host cannot guarantee that the operation was not run or rolled back.
|
||||
///
|
||||
/// A Client must not automatically retry because the operation may have
|
||||
/// committed effects even though no success response was available.
|
||||
OperationOutcomeUnknown,
|
||||
}
|
||||
|
||||
impl ProtocolErrorCode {
|
||||
/// Every canonical wire-level error code.
|
||||
pub const ALL: [Self; 14] = [
|
||||
Self::InvalidRequest,
|
||||
Self::NotFound,
|
||||
Self::InterfaceNotFound,
|
||||
Self::InterfaceMismatch,
|
||||
Self::OperationNotFound,
|
||||
Self::InvalidArguments,
|
||||
Self::ValidatorRequired,
|
||||
Self::ValidatorMismatch,
|
||||
Self::InterfaceValidatorRequired,
|
||||
Self::InterfaceValidatorMismatch,
|
||||
Self::PermissionDenied,
|
||||
Self::ResourceLimitExceeded,
|
||||
Self::Internal,
|
||||
Self::OperationOutcomeUnknown,
|
||||
];
|
||||
|
||||
/// Whether a Host may return this code for `interaction`.
|
||||
///
|
||||
/// `false` identifies an invalid error response; it does not turn that
|
||||
/// response into another wire-level protocol failure.
|
||||
#[must_use]
|
||||
pub const fn is_allowed_for(self, interaction: ProtocolInteraction) -> bool {
|
||||
use ProtocolErrorCode::{
|
||||
InterfaceMismatch, InterfaceNotFound, InterfaceValidatorMismatch,
|
||||
InterfaceValidatorRequired, Internal, InvalidArguments, InvalidRequest, NotFound,
|
||||
OperationNotFound, OperationOutcomeUnknown, PermissionDenied, ResourceLimitExceeded,
|
||||
ValidatorMismatch, ValidatorRequired,
|
||||
};
|
||||
use ProtocolInteraction::{CallOperation, Fetch, FetchInterface, FetchTree};
|
||||
|
||||
match (interaction, self) {
|
||||
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
|
||||
(Fetch | FetchTree, NotFound) => true,
|
||||
(FetchInterface, InterfaceNotFound) => true,
|
||||
(
|
||||
CallOperation,
|
||||
NotFound
|
||||
| InterfaceMismatch
|
||||
| OperationNotFound
|
||||
| InvalidArguments
|
||||
| ValidatorRequired
|
||||
| ValidatorMismatch
|
||||
| InterfaceValidatorRequired
|
||||
| InterfaceValidatorMismatch
|
||||
| PermissionDenied
|
||||
| OperationOutcomeUnknown,
|
||||
) => true,
|
||||
(
|
||||
_,
|
||||
NotFound
|
||||
| InterfaceNotFound
|
||||
| InterfaceMismatch
|
||||
| OperationNotFound
|
||||
| InvalidArguments
|
||||
| ValidatorRequired
|
||||
| ValidatorMismatch
|
||||
| InterfaceValidatorRequired
|
||||
| InterfaceValidatorMismatch
|
||||
| PermissionDenied
|
||||
| OperationOutcomeUnknown,
|
||||
) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport-independent protocol failure.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProtocolError {
|
||||
/// Stable programmatic category.
|
||||
pub category: ProtocolErrorCategory,
|
||||
/// Human-readable diagnostic. Consumers must not branch on this text.
|
||||
/// Stable programmatic code. Consumers must branch on this field.
|
||||
pub code: ProtocolErrorCode,
|
||||
/// Bounded human-readable diagnostic. Consumers must not branch on it.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Display for ProtocolError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"protocol failure ({:?}): {}",
|
||||
self.code, self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ProtocolError {}
|
||||
|
||||
@@ -1,9 +1,45 @@
|
||||
//! Transport-independent logical types for the Web Interface Protocol (WIP).
|
||||
//! Canonical transport-independent logical types for the Web Interface Protocol.
|
||||
//!
|
||||
//! This crate deliberately models interface declarations, published objects,
|
||||
//! operation calls, and operation results without assigning them HTTP routes,
|
||||
//! methods, headers, or JSON envelopes. A transport can encode these values,
|
||||
//! but the encoding is outside this crate's contract.
|
||||
//! This crate follows the Core Model and `3-protocol.md` without assigning HTTP
|
||||
//! routes, methods, headers, URL encodings, or JSON envelopes. The correspondence
|
||||
//! between canonical logical concepts and this crate is direct:
|
||||
//!
|
||||
//! | Canonical protocol concept | Rust API |
|
||||
//! | --- | --- |
|
||||
//! | Object projection and ordered interface set | [`Object`] |
|
||||
//! | Optional object identity / state precondition | `Object::ref` / [`Object::validator`] |
|
||||
//! | Interface Descriptor | [`InterfaceDescriptor`] |
|
||||
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
|
||||
//! | Schema-neutral primitive/composite value | [`Value`] |
|
||||
//! | `fetch` | [`FetchRequest`] / [`FetchResponse`] |
|
||||
//! | `fetch_tree` | [`FetchTreeRequest`] / [`FetchTreeResponse`] |
|
||||
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
||||
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
||||
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
||||
//! | Stable Host failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
||||
//! | Per-interaction allowed failure codes | [`ProtocolInteraction`] / [`ProtocolErrorCode::is_allowed_for`] |
|
||||
//!
|
||||
//! [`ProtocolErrorCode`] is a closed set of Host-returned wire failures. After a
|
||||
//! Client receives a response, an invalid Object, Descriptor, operation result,
|
||||
//! malformed error, or error code disallowed by [`ProtocolInteraction`] is a
|
||||
//! Client-local `InvalidResponse`, not another wire error. A descriptor whose
|
||||
//! `format` is not supported is a Client-local `UnsupportedDescriptorFormat`.
|
||||
//!
|
||||
//! For `call_operation`, [`ProtocolErrorCode::Internal`] and
|
||||
//! [`ProtocolErrorCode::ResourceLimitExceeded`] guarantee that the operation did
|
||||
//! not run or that all effects were rolled back. Only
|
||||
//! [`ProtocolErrorCode::OperationOutcomeUnknown`] means the Host cannot make that
|
||||
//! guarantee; Clients must not automatically retry it.
|
||||
//!
|
||||
//! Paths, object refs, interface refs, and validators remain separate concepts.
|
||||
//! They are represented by ordinary protocol strings/bytes in the corresponding
|
||||
//! fields. In particular, object refs are optional, operation targeting uses a
|
||||
//! path, and this crate defines no interaction that fetches an object by ref.
|
||||
//!
|
||||
//! [`Value`] contains only the canonical raw value kinds. A descriptor interprets
|
||||
//! enum values as strings, entries as canonical-path strings, and unions as
|
||||
//! records with a `$case` string plus an optional `value` payload. JSON uses the
|
||||
//! same value tree (`Unit` is JSON null) and rejects bytes.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
@@ -12,19 +48,33 @@ mod model;
|
||||
mod validation;
|
||||
|
||||
pub use error::{
|
||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCategory, ValidationError,
|
||||
ValidationErrorKind, ValueKind,
|
||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
ValidationError, ValidationErrorKind, ValueKind,
|
||||
};
|
||||
pub use model::{
|
||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
||||
InterfaceObservation, JsonMember, JsonValue, NamedValue, Object, ObjectId, OperationCall,
|
||||
OperationDeclaration, OperationOutcome, OperationResult, OperationTarget, ParameterDeclaration,
|
||||
RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr, UnionDeclaration,
|
||||
UnionVariantDeclaration, Value,
|
||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest, FetchTreeResponse,
|
||||
FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object, ObjectTreeNode,
|
||||
OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
|
||||
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;
|
||||
|
||||
/// 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;
|
||||
|
||||
+308
-253
@@ -1,6 +1,8 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
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)]
|
||||
pub struct Documentation {
|
||||
/// A short, self-contained description.
|
||||
@@ -9,242 +11,194 @@ pub struct Documentation {
|
||||
pub details: Option<String>,
|
||||
}
|
||||
|
||||
/// Stable logical identity of a published object.
|
||||
#[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 protocol projection currently published at one Worldspace path.
|
||||
///
|
||||
/// The vector order is significant. Call [`Object::validate`] before
|
||||
/// publication to reject duplicate interface names.
|
||||
/// `name` is a path segment, `interfaces` is an ordered set of opaque interface
|
||||
/// 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)]
|
||||
pub struct Object {
|
||||
/// Logical object identity.
|
||||
pub id: ObjectId,
|
||||
/// Interface names in publication order.
|
||||
/// Path-segment name. The root object's name is empty.
|
||||
pub name: String,
|
||||
/// Short public description of the object.
|
||||
pub description: Option<String>,
|
||||
/// Opaque interface references in host publication order.
|
||||
pub interfaces: Vec<String>,
|
||||
}
|
||||
|
||||
/// A complete logical observation of an object and its interface descriptors.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct InterfaceObservation {
|
||||
/// Observed object.
|
||||
pub object: Object,
|
||||
/// Descriptors corresponding to `object.interfaces`.
|
||||
pub descriptors: Vec<InterfaceDescriptor>,
|
||||
/// Optional opaque identity within one client-facing Worldspace.
|
||||
pub r#ref: Option<String>,
|
||||
/// Optional opaque validator for the object's observed state.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Interface name.
|
||||
pub name: String,
|
||||
/// Descriptor format version understood by clients and hosts.
|
||||
pub format: String,
|
||||
/// Optional interface documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Named type declarations local to this descriptor.
|
||||
pub declarations: Vec<TypeDeclaration>,
|
||||
/// Named declarations local to this descriptor.
|
||||
pub types: Vec<TypeDeclaration>,
|
||||
/// Operations exposed by this interface.
|
||||
pub operations: Vec<OperationDeclaration>,
|
||||
}
|
||||
|
||||
/// A named type declaration local to an interface descriptor.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum 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 {
|
||||
/// A descriptor-local named type declaration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TypeDeclaration {
|
||||
/// Descriptor-local type name.
|
||||
pub name: String,
|
||||
/// Optional record documentation.
|
||||
/// Optional type documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Fields in declaration order.
|
||||
pub fields: Vec<FieldDeclaration>,
|
||||
/// Definition associated with `name`.
|
||||
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.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FieldDeclaration {
|
||||
/// Field name.
|
||||
pub name: String,
|
||||
/// Whether the field must be present.
|
||||
pub required: bool,
|
||||
/// Optional field documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Field value type.
|
||||
pub ty: TypeExpr,
|
||||
/// Whether the field may be omitted.
|
||||
///
|
||||
/// Optionality represents absence, not a `null` value.
|
||||
pub optional: bool,
|
||||
pub r#type: TypeExpr,
|
||||
}
|
||||
|
||||
/// Declaration of an enumeration.
|
||||
/// One payload-free enum case.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EnumDeclaration {
|
||||
/// Descriptor-local type name.
|
||||
pub struct EnumCase {
|
||||
/// Case name.
|
||||
pub name: String,
|
||||
/// Optional enum documentation.
|
||||
/// Optional case 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)]
|
||||
pub struct EnumVariantDeclaration {
|
||||
/// Variant name.
|
||||
pub struct UnionCase {
|
||||
/// Case name.
|
||||
pub name: String,
|
||||
/// Optional variant documentation.
|
||||
/// Optional case documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
/// Optional payload type.
|
||||
pub payload: Option<TypeExpr>,
|
||||
}
|
||||
|
||||
/// Declaration of one interface operation.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OperationDeclaration {
|
||||
/// Operation name, unique within its interface.
|
||||
/// Operation name, unique within its descriptor.
|
||||
pub name: String,
|
||||
/// Optional operation documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Parameters in declaration order.
|
||||
pub parameters: Vec<ParameterDeclaration>,
|
||||
/// Return declaration, or `None` for an operation with no return value.
|
||||
pub returns: Option<ReturnDeclaration>,
|
||||
/// Return declaration. No-data operations return [`TypeExpr::Unit`].
|
||||
pub returns: ReturnDeclaration,
|
||||
}
|
||||
|
||||
/// Declaration of one operation parameter.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParameterDeclaration {
|
||||
/// Parameter name.
|
||||
pub name: String,
|
||||
/// Whether the parameter must be present.
|
||||
pub required: bool,
|
||||
/// Optional parameter documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Parameter value type.
|
||||
pub ty: TypeExpr,
|
||||
/// Whether the parameter may be omitted.
|
||||
///
|
||||
/// Optionality represents absence, not a `null` value.
|
||||
pub optional: bool,
|
||||
pub r#type: TypeExpr,
|
||||
}
|
||||
|
||||
/// Declaration of an operation return value.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReturnDeclaration {
|
||||
/// Optional return-value documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// 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
|
||||
/// parameters are omitted. JSON null remains available inside [`Value::Json`].
|
||||
/// Enum cases, union cases, entries, and JSON are interpretations imposed by a
|
||||
/// descriptor. They are deliberately not variants of this enum. Record key
|
||||
/// ordering is not protocol-significant.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
/// A UTF-8 string.
|
||||
String(String),
|
||||
/// A value carrying no data; it also represents JSON null under `Json`.
|
||||
Unit,
|
||||
/// A boolean.
|
||||
Boolean(bool),
|
||||
/// An integer, validated against the JavaScript safe integer range.
|
||||
/// A JavaScript-lossless integer.
|
||||
Integer(i64),
|
||||
/// A number, validated to be finite.
|
||||
/// A finite IEEE-754 binary64 number.
|
||||
Number(f64),
|
||||
/// A Unicode string.
|
||||
String(String),
|
||||
/// An opaque byte sequence.
|
||||
Bytes(Vec<u8>),
|
||||
/// String-keyed fields with order-insensitive semantics.
|
||||
Record(BTreeMap<String, Value>),
|
||||
/// An ordered sequence.
|
||||
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 {
|
||||
@@ -252,132 +206,233 @@ impl Value {
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> crate::ValueKind {
|
||||
match self {
|
||||
Self::String(_) => crate::ValueKind::String,
|
||||
Self::Unit => crate::ValueKind::Unit,
|
||||
Self::Boolean(_) => crate::ValueKind::Boolean,
|
||||
Self::Integer(_) => crate::ValueKind::Integer,
|
||||
Self::Number(_) => crate::ValueKind::Number,
|
||||
Self::String(_) => crate::ValueKind::String,
|
||||
Self::Bytes(_) => crate::ValueKind::Bytes,
|
||||
Self::List(_) => crate::ValueKind::List,
|
||||
Self::Entry { .. } => crate::ValueKind::Entry,
|
||||
Self::Record(_) => crate::ValueKind::Record,
|
||||
Self::Enum(_) => crate::ValueKind::Enum,
|
||||
Self::Union { .. } => crate::ValueKind::Union,
|
||||
Self::Json(_) => crate::ValueKind::Json,
|
||||
Self::List(_) => crate::ValueKind::List,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A named value used by records and operation arguments.
|
||||
#[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.
|
||||
/// Request for the object currently published at one path.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OperationTarget {
|
||||
/// Target object.
|
||||
pub object: ObjectId,
|
||||
/// Target interface name.
|
||||
pub struct FetchRequest {
|
||||
/// Canonical absolute Worldspace path.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// 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,
|
||||
/// 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)]
|
||||
pub struct OperationCall {
|
||||
/// Logical call target.
|
||||
pub target: OperationTarget,
|
||||
/// Named arguments. Optional arguments are represented by omission.
|
||||
pub arguments: Vec<NamedValue>,
|
||||
pub struct CallOperationResponse {
|
||||
/// Application result validated against the operation return declaration.
|
||||
pub result: Value,
|
||||
/// Optional validator for the object state observed after execution.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Successful or failed logical outcome of an operation.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum OperationOutcome {
|
||||
/// Operation returned. `None` represents a declared no-return operation.
|
||||
Returned(Option<Value>),
|
||||
/// Operation failed with a protocol-level error.
|
||||
Failed(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,
|
||||
/// Logical outcome of any core interaction.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ProtocolResult<T> {
|
||||
/// The interaction succeeded.
|
||||
Success(T),
|
||||
/// The interaction failed at the protocol boundary.
|
||||
Failure(ProtocolError),
|
||||
}
|
||||
|
||||
impl Object {
|
||||
/// Validates ordered-set interface semantics.
|
||||
/// Validates the object-independent name and ordered-interface-set rules.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_object(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl InterfaceObservation {
|
||||
/// Validates the object, descriptor structure, and their correspondence.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_observation(self)
|
||||
/// Validates this object as the response observed at `path`.
|
||||
pub fn validate_at_path(&self, path: &str) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_object_at_path(self, path)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Validates declaration structure, references, and absence of recursion.
|
||||
/// Validates declaration structure, named references, and absence of cycles.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_descriptor(self)
|
||||
}
|
||||
|
||||
/// Validates a value against a type expression in this descriptor.
|
||||
pub fn validate_value(&self, ty: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_root_value(self, ty, value)
|
||||
/// Validates a raw value against a type expression in this descriptor.
|
||||
pub fn validate_value(&self, r#type: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_root_value(self, r#type, value)
|
||||
}
|
||||
|
||||
/// Validates a call target and arguments against this descriptor.
|
||||
pub fn validate_call(&self, call: &OperationCall) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_call(self, call)
|
||||
}
|
||||
|
||||
/// Validates an operation's returned value against this descriptor.
|
||||
pub fn validate_return(
|
||||
/// Validates named arguments for one declared operation.
|
||||
pub fn validate_arguments(
|
||||
&self,
|
||||
operation: &str,
|
||||
value: Option<&Value>,
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_return(self, operation, value)
|
||||
crate::validation::validate_arguments(self, operation, arguments)
|
||||
}
|
||||
|
||||
/// Validates one operation result against its return declaration.
|
||||
pub fn validate_result(&self, operation: &str, result: &Value) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_result(self, operation, result)
|
||||
}
|
||||
|
||||
/// Validates the path, operation, and arguments in a call request.
|
||||
pub fn validate_call(&self, request: &CallOperationRequest) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_call(self, request)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchRequest {
|
||||
/// Validates the request path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_path(&self.path)
|
||||
}
|
||||
|
||||
/// Validates an object returned for this request.
|
||||
///
|
||||
/// Failure means the Client received an invalid success response; it is not a
|
||||
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||
pub fn validate_response(&self, response: &FetchResponse) -> Result<(), ValidationError> {
|
||||
response.validate_at_path(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchTreeRequest {
|
||||
/// Validates the request path and nonzero node limit.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_fetch_tree_request(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchTreeResponse {
|
||||
/// Validates tree shape, names, depth, and node limit for `request`.
|
||||
///
|
||||
/// Failure means the Client received an invalid success response; it is not a
|
||||
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||
pub fn validate_for(&self, request: &FetchTreeRequest) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_fetch_tree_response(self, request)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchInterfaceResponse {
|
||||
/// Validates request correspondence and descriptor semantics.
|
||||
///
|
||||
/// Failure means the Client received an invalid success response; it is not a
|
||||
/// Host-returned [`crate::ProtocolErrorCode`]. Descriptor format support is a
|
||||
/// separate Client concern: an otherwise valid descriptor with an unsupported
|
||||
/// `format` is a Client-local `UnsupportedDescriptorFormat`.
|
||||
pub fn validate_for(&self, request: &FetchInterfaceRequest) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_fetch_interface_response(self, request)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallOperationRequest {
|
||||
/// Validates this call against the descriptor selected by `interface`.
|
||||
pub fn validate_with(&self, descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallOperationResponse {
|
||||
/// Validates this result against the named operation in `descriptor`.
|
||||
///
|
||||
/// Failure means the Client received an invalid success response; it is not a
|
||||
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||
pub fn validate_for(
|
||||
&self,
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_result(operation, &self.result)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "wip-public-api-example"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
wip-host = { path = "../wip-host" }
|
||||
wip-interface = { path = "../wip-interface" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Public-only conformance consumer for the WIP Rust crates.
|
||||
//!
|
||||
//! # Architectural boundary
|
||||
//!
|
||||
//! This package is an ordinary application consumer. Its direct dependencies are
|
||||
//! the public `wip-protocol`, `wip-interface`, and `wip-host` crates; it neither
|
||||
//! imports workspace-private modules nor depends on `wip-interface-macros`.
|
||||
//! `wip-protocol` owns transport-independent DTOs and schema-neutral values,
|
||||
//! while this package owns its application DTOs and interface traits. The
|
||||
//! request-scoped implementation, backend handle, authorization policy, and
|
||||
//! publication wiring remain host-private. A transport binding would translate
|
||||
//! its own wire routes and envelopes to the protocol call DTOs; no HTTP type is
|
||||
//! part of an application trait or interface descriptor.
|
||||
//!
|
||||
//! # Breaking migration exercised here
|
||||
//!
|
||||
//! The canonical API targets operations by `target.path` rather than a mandatory
|
||||
//! object identifier. Object `ref` and object/interface validators are separate,
|
||||
//! optional observation fields. Interface references are opaque values observed
|
||||
//! separately from descriptors, and descriptors contain neither a Rust trait
|
||||
//! name nor an opaque-reference `name` field. Application records, enums,
|
||||
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
|
||||
//! variants: entries and enums are strings, unions are discriminator records,
|
||||
//! and JSON recursively uses ordinary records/lists/primitives. The former
|
||||
//! `Entry<K, V>` and semantic `Value::Entry`, `Value::Enum`, `Value::Union`, and
|
||||
//! `Value::Json` forms are intentionally unsupported.
|
||||
//!
|
||||
//! # Supported authoring subset
|
||||
//!
|
||||
//! Public, non-generic traits use immutable `&self` receivers, owned named
|
||||
//! parameters, and explicit `wip::OperationResult<T>` returns. Derived DTOs are
|
||||
//! named-field records, all-unit enums, or unions with unit and single-payload
|
||||
//! cases. A direct `Option<T>` means field/argument omission, never protocol
|
||||
//! null. See `wip-interface` for the complete rejected-syntax list.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
|
||||
use wip_host::{
|
||||
CallErrorKind, CallRequest, ExecutionContext, InterfaceRef, InterfaceRegistry, InterfaceTarget,
|
||||
ObjectProvider, ProviderResult, PublishedObject, RegisteredInterface, Target, Validator,
|
||||
WipObject,
|
||||
};
|
||||
use wip_interface as wip;
|
||||
use wip_interface::WipType;
|
||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, Value};
|
||||
|
||||
const OBJECT_PATH: &str = "/article-service";
|
||||
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
||||
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
|
||||
|
||||
/// Publication visibility represented as a protocol enum string.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||
pub enum Visibility {
|
||||
/// Visible to every authorized caller.
|
||||
Public,
|
||||
/// Visible only inside the application domain.
|
||||
Private,
|
||||
}
|
||||
|
||||
/// An application-owned request DTO mapped to a protocol record.
|
||||
#[derive(Debug, Clone, PartialEq, wip::WipType)]
|
||||
pub struct PublishRequest {
|
||||
/// Title of the article to publish.
|
||||
pub title: String,
|
||||
/// Optional article body; omission is distinct from JSON null.
|
||||
pub body: Option<String>,
|
||||
/// Canonical Worldspace path to the source entry.
|
||||
pub source: wip::Entry,
|
||||
/// Application enum represented by a schema-neutral string.
|
||||
pub visibility: Visibility,
|
||||
/// Schema-opaque JSON represented by ordinary protocol values.
|
||||
pub metadata: wip::JsonValue,
|
||||
}
|
||||
|
||||
/// The application domain result of a publication attempt.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||
pub enum PublishOutcome {
|
||||
/// Publication succeeded and returned its application identifier.
|
||||
Published(String),
|
||||
/// An application policy rejected the publication.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
/// Article publication operations.
|
||||
#[wip::interface]
|
||||
pub trait Catalog {
|
||||
/// Publishes an article or reports an application-domain rejection.
|
||||
///
|
||||
/// # Returns
|
||||
/// The typed application outcome.
|
||||
fn publish(
|
||||
&self,
|
||||
/// Application publication request.
|
||||
request: PublishRequest,
|
||||
) -> wip::OperationResult<PublishOutcome>;
|
||||
|
||||
/// Returns the catalog-qualified status.
|
||||
fn status(&self) -> wip::OperationResult<String>;
|
||||
|
||||
/// Demonstrates a rollback-confirmed host/backend failure.
|
||||
fn backend_status(&self) -> wip::OperationResult<String>;
|
||||
|
||||
/// Demonstrates a host/backend failure with an unknown operation outcome.
|
||||
fn uncertain_backend_status(&self) -> wip::OperationResult<String>;
|
||||
|
||||
/// Demonstrates denial after every structural precondition succeeds.
|
||||
fn restricted_status(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// Audit operations exposed by the same object.
|
||||
#[wip::interface]
|
||||
pub trait Audit {
|
||||
/// Returns the audit-qualified status.
|
||||
fn status(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// A registered but deliberately unexposed interface.
|
||||
#[wip::interface]
|
||||
pub trait Diagnostics {
|
||||
/// Returns host-private diagnostics when explicitly exposed.
|
||||
fn diagnostics(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// Observable outcomes from the complete public-API scenario.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DemoReport {
|
||||
/// Path-segment name from the canonical object projection.
|
||||
pub object_name: String,
|
||||
/// Optional object identity, distinct from the resolution path.
|
||||
pub object_reference: Option<String>,
|
||||
/// Optional object-state validator.
|
||||
pub object_validator: Option<Vec<u8>>,
|
||||
/// Opaque interface references published by the object, in exposure order.
|
||||
pub published_interfaces: Vec<String>,
|
||||
/// Opaque reference assigned to the catalog descriptor.
|
||||
pub catalog_interface_reference: String,
|
||||
/// Opaque reference assigned to the audit descriptor.
|
||||
pub audit_interface_reference: String,
|
||||
/// Descriptor format observed separately for the catalog reference.
|
||||
pub catalog_descriptor_format: String,
|
||||
/// Descriptor format observed separately for the audit reference.
|
||||
pub audit_descriptor_format: String,
|
||||
/// Typed successful application result decoded from a validated [`Value`].
|
||||
pub published: PublishOutcome,
|
||||
/// Typed application-domain rejection decoded from a validated [`Value`].
|
||||
pub rejected: PublishOutcome,
|
||||
/// Result of the catalog-qualified `status` operation.
|
||||
pub catalog_status: String,
|
||||
/// Result of the audit-qualified `status` operation.
|
||||
pub audit_status: String,
|
||||
/// Stable failure kind produced by the deliberate host/backend failure.
|
||||
pub host_failure: CallErrorKind,
|
||||
/// Protocol failure whose operation effects are guaranteed not committed.
|
||||
pub protocol_failure: ProtocolError,
|
||||
/// Protocol failure whose operation effects cannot be proven absent.
|
||||
pub unknown_protocol_failure: ProtocolError,
|
||||
/// Authorization failure after a fully qualified valid request.
|
||||
pub permission_failure: ProtocolErrorCode,
|
||||
/// Recovery signal for a stale object validator.
|
||||
pub validator_failure: ProtocolErrorCode,
|
||||
/// Failure for a known but unexposed interface reference.
|
||||
pub interface_mismatch: ProtocolErrorCode,
|
||||
/// Failure for an unknown interface observation reference.
|
||||
pub interface_not_found: ProtocolErrorCode,
|
||||
/// First failure for a request with an invalid path and later invalid fields.
|
||||
pub precedence_failure: ProtocolErrorCode,
|
||||
}
|
||||
|
||||
/// Runs the complete end-to-end conformance example.
|
||||
///
|
||||
/// The provider resolves the current object from a Worldspace path for each
|
||||
/// call. Interface observations remain separate from object projection, and all
|
||||
/// successful calls carry independent object and interface validators.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if registration, observation, path resolution, dispatch, or
|
||||
/// application-value decoding fails unexpectedly.
|
||||
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
|
||||
let audit = registry.register(AuditDefinition, None)?;
|
||||
let diagnostics = registry.register(DiagnosticsDefinition, None)?;
|
||||
let provider = ApplicationProvider {
|
||||
catalog: catalog.clone(),
|
||||
audit: audit.clone(),
|
||||
};
|
||||
|
||||
let object = provider.fetch(OBJECT_PATH)?;
|
||||
let catalog_response = registry
|
||||
.fetch_interface(
|
||||
object
|
||||
.interfaces
|
||||
.first()
|
||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
||||
)?
|
||||
.protocol_response()?;
|
||||
let audit_response = registry
|
||||
.fetch_interface(
|
||||
object
|
||||
.interfaces
|
||||
.get(1)
|
||||
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
|
||||
)?
|
||||
.protocol_response()?;
|
||||
|
||||
let published = dispatch_publish(
|
||||
&provider,
|
||||
catalog.reference(),
|
||||
PublishRequest {
|
||||
title: "Public APIs".into(),
|
||||
body: Some("protocol values in, validated values out".into()),
|
||||
source: wip::Entry::new("/drafts/public-apis")?,
|
||||
visibility: Visibility::Public,
|
||||
metadata: wip::JsonValue::Object(vec![wip::JsonMember {
|
||||
name: "reviewed".into(),
|
||||
value: wip::JsonValue::Boolean(true),
|
||||
}]),
|
||||
},
|
||||
)?;
|
||||
let rejected = dispatch_publish(
|
||||
&provider,
|
||||
catalog.reference(),
|
||||
PublishRequest {
|
||||
title: String::new(),
|
||||
body: None,
|
||||
source: wip::Entry::new("/drafts/untitled")?,
|
||||
visibility: Visibility::Private,
|
||||
metadata: wip::JsonValue::Null,
|
||||
},
|
||||
)?;
|
||||
let catalog_status = dispatch_string(
|
||||
&provider,
|
||||
request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
let audit_status = dispatch_string(
|
||||
&provider,
|
||||
request(
|
||||
OBJECT_PATH,
|
||||
audit.reference(),
|
||||
None,
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
|
||||
let host_error = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"backend_status",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("backend_status must model a host failure");
|
||||
ensure_kind(&host_error, CallErrorKind::Internal)?;
|
||||
let protocol_failure = host_error.protocol_error();
|
||||
|
||||
let unknown_protocol_failure = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"uncertain_backend_status",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("uncertain_backend_status must preserve an unknown outcome")
|
||||
.protocol_error();
|
||||
|
||||
let permission_failure = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"restricted_status",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("restricted_status must be denied")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let validator_failure = provider
|
||||
.call_operation(CallRequest {
|
||||
target: Target {
|
||||
path: OBJECT_PATH.into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: diagnostics.reference().as_str().to_owned(),
|
||||
validator: Some(b"stale-interface".to_vec()),
|
||||
},
|
||||
operation: "missing".into(),
|
||||
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||
})
|
||||
.expect_err("the stale object validator must fail first")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let interface_mismatch = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
diagnostics.reference(),
|
||||
None,
|
||||
"diagnostics",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("registered but unexposed interface must not dispatch")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let interface_not_found = registry
|
||||
.fetch_interface("missing-interface")
|
||||
.expect_err("unknown interface references must not resolve")
|
||||
.code;
|
||||
|
||||
let precedence_failure = provider
|
||||
.call_operation(CallRequest {
|
||||
target: Target {
|
||||
path: "relative/path".into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: diagnostics.reference().as_str().to_owned(),
|
||||
validator: Some(b"stale-interface".to_vec()),
|
||||
},
|
||||
operation: "missing".into(),
|
||||
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||
})
|
||||
.expect_err("invalid path must have canonical precedence")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
Ok(DemoReport {
|
||||
object_name: object.name,
|
||||
object_reference: object.r#ref,
|
||||
object_validator: object.validator,
|
||||
published_interfaces: object.interfaces,
|
||||
catalog_interface_reference: catalog.reference().as_str().to_owned(),
|
||||
audit_interface_reference: audit.reference().as_str().to_owned(),
|
||||
catalog_descriptor_format: catalog_response.descriptor.format,
|
||||
audit_descriptor_format: audit_response.descriptor.format,
|
||||
published,
|
||||
rejected,
|
||||
catalog_status,
|
||||
audit_status,
|
||||
host_failure: host_error.kind(),
|
||||
protocol_failure,
|
||||
unknown_protocol_failure,
|
||||
permission_failure,
|
||||
validator_failure,
|
||||
interface_mismatch,
|
||||
interface_not_found,
|
||||
precedence_failure,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_kind(error: &wip_host::CallError, expected: CallErrorKind) -> Result<(), io::Error> {
|
||||
if error.kind() == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(format!(
|
||||
"unexpected host failure kind: {:?}",
|
||||
error.kind()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_publish(
|
||||
provider: &ApplicationProvider,
|
||||
catalog: &InterfaceRef,
|
||||
request_value: PublishRequest,
|
||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
||||
let encoded_request = request_value.encode()?;
|
||||
let result = provider.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog,
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"publish",
|
||||
BTreeMap::from([("request".into(), encoded_request)]),
|
||||
))?;
|
||||
Ok(PublishOutcome::decode(result.result)?)
|
||||
}
|
||||
|
||||
fn dispatch_string(
|
||||
provider: &ApplicationProvider,
|
||||
request: CallRequest,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
let result = provider.call_operation(request)?;
|
||||
Ok(String::decode(result.result)?)
|
||||
}
|
||||
|
||||
fn request(
|
||||
path: &str,
|
||||
interface: &InterfaceRef,
|
||||
interface_validator: Option<&[u8]>,
|
||||
operation: &str,
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> CallRequest {
|
||||
CallRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: interface.as_str().to_owned(),
|
||||
validator: interface_validator.map(<[u8]>::to_vec),
|
||||
},
|
||||
operation: operation.into(),
|
||||
arguments,
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplicationProvider {
|
||||
catalog: RegisteredInterface<CatalogDefinition>,
|
||||
audit: RegisteredInterface<AuditDefinition>,
|
||||
}
|
||||
|
||||
impl ObjectProvider for ApplicationProvider {
|
||||
type Object = ApplicationService;
|
||||
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
_context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
if path != OBJECT_PATH {
|
||||
return ProviderResult::NotFound;
|
||||
}
|
||||
let publication = PublishedObject::new(ApplicationService::new())
|
||||
.expose(&self.catalog)
|
||||
.expect("ApplicationService implements Catalog")
|
||||
.expose(&self.audit)
|
||||
.expect("ApplicationService implements Audit");
|
||||
ProviderResult::Found(operation(&publication))
|
||||
}
|
||||
|
||||
fn authorize(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &ApplicationService,
|
||||
_: &InterfaceRef,
|
||||
operation: &str,
|
||||
) -> bool {
|
||||
operation != "restricted_status"
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplicationService {
|
||||
object_validator: Validator,
|
||||
backend_connection: String,
|
||||
}
|
||||
|
||||
impl ApplicationService {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
object_validator: Validator::new(OBJECT_VALIDATOR),
|
||||
backend_connection: "private://article-database".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipObject for ApplicationService {
|
||||
fn name(&self) -> &str {
|
||||
"article-service"
|
||||
}
|
||||
|
||||
fn description(&self) -> Option<&str> {
|
||||
Some("Article publication service")
|
||||
}
|
||||
|
||||
fn reference(&self) -> Option<&str> {
|
||||
Some("article-service-instance")
|
||||
}
|
||||
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
Some(&self.object_validator)
|
||||
}
|
||||
|
||||
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Catalog for ApplicationService {
|
||||
fn publish(&self, request: PublishRequest) -> wip::OperationResult<PublishOutcome> {
|
||||
if request.title.trim().is_empty() {
|
||||
Ok(PublishOutcome::Rejected("a title is required".into()))
|
||||
} else {
|
||||
Ok(PublishOutcome::Published("article-1".into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn status(&self) -> wip::OperationResult<String> {
|
||||
Ok("catalog-ready".into())
|
||||
}
|
||||
|
||||
fn backend_status(&self) -> wip::OperationResult<String> {
|
||||
if self.backend_connection.starts_with("private://") {
|
||||
Err(wip::HostError::internal(
|
||||
"backend unavailable",
|
||||
wip::EffectGuarantee::NotCommitted,
|
||||
))
|
||||
} else {
|
||||
Ok("backend-ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn uncertain_backend_status(&self) -> wip::OperationResult<String> {
|
||||
Err(wip::HostError::internal(
|
||||
"backend commit acknowledgement unavailable",
|
||||
wip::EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
|
||||
fn restricted_status(&self) -> wip::OperationResult<String> {
|
||||
Ok("authorization hook should prevent this call".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Audit for ApplicationService {
|
||||
fn status(&self) -> wip::OperationResult<String> {
|
||||
Ok("audit-ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Diagnostics for ApplicationService {
|
||||
fn diagnostics(&self) -> wip::OperationResult<String> {
|
||||
Ok("host-private".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::error::Error;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let report = wip_public_api_example::run()?;
|
||||
println!(
|
||||
"published {} interfaces; catalog={}, audit={}; domain={:?}; host={:?}",
|
||||
report.published_interfaces.len(),
|
||||
report.catalog_status,
|
||||
report.audit_status,
|
||||
report.rejected,
|
||||
report.host_failure,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_host::CallErrorKind;
|
||||
use wip_interface::{Entry, JsonMember, JsonValue, WipType};
|
||||
use wip_protocol::{INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, ProtocolErrorCode, Value};
|
||||
use wip_public_api_example::{CatalogDefinition, PublishOutcome, PublishRequest, Visibility, run};
|
||||
|
||||
#[test]
|
||||
fn public_crates_support_the_complete_qualified_end_to_end_scenario() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(report.object_name, "article-service");
|
||||
assert_eq!(
|
||||
report.object_reference.as_deref(),
|
||||
Some("article-service-instance")
|
||||
);
|
||||
assert_eq!(
|
||||
report.object_validator.as_deref(),
|
||||
Some(b"object-v1".as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
report.published_interfaces,
|
||||
[
|
||||
report.catalog_interface_reference.clone(),
|
||||
report.audit_interface_reference.clone(),
|
||||
],
|
||||
"interfaces must retain explicit publication order"
|
||||
);
|
||||
assert_ne!(
|
||||
report.catalog_interface_reference, report.audit_interface_reference,
|
||||
"interfaces form an ordered set of distinct opaque references"
|
||||
);
|
||||
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
report.published,
|
||||
PublishOutcome::Published("article-1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
report.rejected,
|
||||
PublishOutcome::Rejected("a title is required".into())
|
||||
);
|
||||
assert_eq!(report.catalog_status, "catalog-ready");
|
||||
assert_eq!(report.audit_status, "audit-ready");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_host_permission_and_validator_failures_remain_distinct() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert!(matches!(report.rejected, PublishOutcome::Rejected(_)));
|
||||
assert_eq!(report.host_failure, CallErrorKind::Internal);
|
||||
assert_eq!(report.protocol_failure.code, ProtocolErrorCode::Internal);
|
||||
assert_eq!(
|
||||
report.unknown_protocol_failure.code,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown
|
||||
);
|
||||
assert_eq!(
|
||||
report.permission_failure,
|
||||
ProtocolErrorCode::PermissionDenied
|
||||
);
|
||||
assert_eq!(
|
||||
report.validator_failure,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
"validator recovery signals must not collapse to InvalidRequest"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_mismatch_is_not_interface_not_found() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
report.interface_mismatch,
|
||||
ProtocolErrorCode::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(
|
||||
report.interface_not_found,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
assert_ne!(report.interface_mismatch, report.interface_not_found);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_path_keeps_canonical_failure_precedence() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(report.precedence_failure, ProtocolErrorCode::InvalidRequest);
|
||||
assert_ne!(report.precedence_failure, report.validator_failure);
|
||||
assert_ne!(report.precedence_failure, report.interface_mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_fields_keep_path_context_and_optional_ref_separate() {
|
||||
// Listing every field makes this test fail to compile if a mandatory
|
||||
// ObjectId is reintroduced into the canonical object DTO.
|
||||
let object = Object {
|
||||
name: "article".into(),
|
||||
description: None,
|
||||
interfaces: vec!["catalog-ref".into(), "audit-ref".into()],
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
};
|
||||
|
||||
object.validate_at_path("/library/article").unwrap();
|
||||
assert_eq!(object.name, "article");
|
||||
assert_eq!(object.r#ref, None);
|
||||
assert_eq!(object.interfaces, ["catalog-ref", "audit-ref"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_reference_is_observed_separately_from_descriptor_fields() {
|
||||
// An exact destructuring pattern is compile-time coverage that the
|
||||
// descriptor has no trait-name or opaque-reference `name` field.
|
||||
let InterfaceDescriptor {
|
||||
format,
|
||||
documentation,
|
||||
types,
|
||||
operations,
|
||||
} = CatalogDefinition::descriptor();
|
||||
|
||||
assert_eq!(format, INTERFACE_FORMAT_V1);
|
||||
assert!(documentation.is_some());
|
||||
assert!(!types.is_empty());
|
||||
assert_eq!(
|
||||
operations
|
||||
.iter()
|
||||
.map(|operation| operation.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"publish",
|
||||
"status",
|
||||
"backend_status",
|
||||
"uncertain_backend_status",
|
||||
"restricted_status",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_record_enum_union_entry_and_json_use_schema_neutral_values() {
|
||||
let request = PublishRequest {
|
||||
title: "Canonical values".into(),
|
||||
body: None,
|
||||
source: Entry::new("/drafts/canonical-values").unwrap(),
|
||||
visibility: Visibility::Public,
|
||||
metadata: JsonValue::Object(vec![
|
||||
JsonMember {
|
||||
name: "tags".into(),
|
||||
value: JsonValue::Array(vec![JsonValue::String("wip".into()), JsonValue::Null]),
|
||||
},
|
||||
JsonMember {
|
||||
name: "ready".into(),
|
||||
value: JsonValue::Boolean(true),
|
||||
},
|
||||
]),
|
||||
};
|
||||
|
||||
let encoded = request.encode().unwrap();
|
||||
assert_schema_neutral(&encoded);
|
||||
let Value::Record(fields) = encoded else {
|
||||
panic!("derived DTO record must use Value::Record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields.get("title"),
|
||||
Some(&Value::String("Canonical values".into()))
|
||||
);
|
||||
assert!(!fields.contains_key("body"));
|
||||
assert_eq!(
|
||||
fields.get("source"),
|
||||
Some(&Value::String("/drafts/canonical-values".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
fields.get("visibility"),
|
||||
Some(&Value::String("Public".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
fields.get("metadata"),
|
||||
Some(&Value::Record(BTreeMap::from([
|
||||
("ready".into(), Value::Boolean(true)),
|
||||
(
|
||||
"tags".into(),
|
||||
Value::List(vec![Value::String("wip".into()), Value::Unit])
|
||||
),
|
||||
])))
|
||||
);
|
||||
|
||||
let outcome = PublishOutcome::Rejected("policy".into()).encode().unwrap();
|
||||
assert_schema_neutral(&outcome);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
Value::Record(BTreeMap::from([
|
||||
("$case".into(), Value::String("Rejected".into())),
|
||||
("value".into(), Value::String("policy".into())),
|
||||
]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_is_a_validated_canonical_absolute_path_string() {
|
||||
let entry = Entry::new("/articles/one").unwrap();
|
||||
assert_eq!(
|
||||
entry.encode().unwrap(),
|
||||
Value::String("/articles/one".into())
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
"articles/one",
|
||||
"/articles/",
|
||||
"/articles//one",
|
||||
"/articles/./one",
|
||||
"/articles/../one",
|
||||
] {
|
||||
assert!(
|
||||
Entry::new(invalid).is_err(),
|
||||
"accepted invalid path {invalid}"
|
||||
);
|
||||
assert!(
|
||||
Entry::decode(Value::String(invalid.into())).is_err(),
|
||||
"decoded invalid path {invalid}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_schema_neutral(value: &Value) {
|
||||
// This exhaustive match is a compile-time regression guard: reintroducing
|
||||
// semantic Entry/Enum/Union/Json variants makes the consumer non-exhaustive.
|
||||
match value {
|
||||
Value::Unit
|
||||
| Value::Boolean(_)
|
||||
| Value::Integer(_)
|
||||
| Value::Number(_)
|
||||
| Value::String(_)
|
||||
| Value::Bytes(_) => {}
|
||||
Value::Record(fields) => {
|
||||
for value in fields.values() {
|
||||
assert_schema_neutral(value);
|
||||
}
|
||||
}
|
||||
Value::List(values) => {
|
||||
for value in values {
|
||||
assert_schema_neutral(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
Reference in New Issue
Block a user