Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65c51006ad | ||
|
|
55c784c22d | ||
|
|
511e9fef9f | ||
|
|
06edf62d4e | ||
|
|
ea7b0f00ea | ||
|
|
2e4196a1ec | ||
|
|
de82b66de4 | ||
|
|
db2a51c824 | ||
|
|
347b92b28a | ||
|
|
e1998fb8fd | ||
|
|
b4e38fc2c2 | ||
|
|
780150d7ae | ||
|
|
f207b71f83 | ||
|
|
e5162339e9 | ||
|
|
f5034c0e4b | ||
|
|
20b3986ab6 | ||
|
|
df51da3d03 | ||
|
|
fdfaa3a685 | ||
|
|
2da2a28a67 | ||
|
|
96db3dd6a8 | ||
|
|
625f4c148d | ||
|
|
beeffae9c5 | ||
|
|
56923c1160 | ||
|
|
6de58da17d | ||
|
|
027555eb4e | ||
|
|
75119f23e5 | ||
|
|
653a1171a2 | ||
|
|
2efda433e7 | ||
|
|
2d524723a4 | ||
|
|
7f4e0e4460 | ||
|
|
4f0552c48f | ||
|
|
0705101c97 | ||
|
|
5992322371 | ||
|
|
d0683f0b6d | ||
|
|
f9f083d4c6 | ||
|
|
32f3fb6fb1 |
Generated
+1153
-3
File diff suppressed because it is too large
Load Diff
+1
-14
@@ -1,16 +1,3 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = ["crates/*"]
|
||||||
".",
|
|
||||||
"crates/wip-interface",
|
|
||||||
"crates/wip-interface-macros",
|
|
||||||
"crates/wip-protocol",
|
|
||||||
]
|
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[package]
|
|
||||||
name = "wip-rs"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
wip-protocol = { path = "crates/wip-protocol" }
|
|
||||||
|
|||||||
@@ -2,6 +2,103 @@
|
|||||||
|
|
||||||
Rust building blocks for the Web Interface Protocol (WIP).
|
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, the
|
||||||
|
standard framework-independent WIP over HTTP v1 binding, a stateful
|
||||||
|
presentation-independent client runtime, a Rust interface-authoring facade, a
|
||||||
|
request-scoped host runtime, a bounded Linux filesystem projection server, an
|
||||||
|
interactive terminal client, and a private public-API conformance consumer. The
|
||||||
|
repository root is not itself a package.
|
||||||
|
|
||||||
|
## Crate graph and responsibilities
|
||||||
|
|
||||||
|
```text
|
||||||
|
wip-tui (interactive Worldspace explorer and operation editor)
|
||||||
|
├── wip-client Known Space, request identity, validators, and calls
|
||||||
|
├── wip-http framework-neutral HTTP request/response messages
|
||||||
|
└── wip-protocol descriptors and logical values
|
||||||
|
|
||||||
|
wip-fs-server (request-time filesystem projection and loopback listener)
|
||||||
|
├── wip-http standard routes/codecs/envelopes/batching
|
||||||
|
├── wip-host request-scoped publication and dispatch
|
||||||
|
└── wip-interface macro-generated filesystem capabilities
|
||||||
|
|
||||||
|
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
||||||
|
├── wip-protocol logical declarations, values, calls, and validation
|
||||||
|
├── wip-http standard HTTP v1 routes, JSON codecs, envelopes, and batching
|
||||||
|
│ └── wip-protocol
|
||||||
|
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
|
||||||
|
│ ├── wip-http
|
||||||
|
│ └── wip-protocol
|
||||||
|
├── 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-http` | Standard WIP over HTTP v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, URL scheme or TLS policy, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
||||||
|
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
||||||
|
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTP I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
|
||||||
|
| `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, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
|
||||||
|
| `wip-fs-server` | Linux directory-handle-confined request-time projection, complete depth-bounded observations and bounded file operations, standard `wip-http` dispatch/batch handling, and a loopback HTTP binary. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, TLS termination, or filesystem-wide preregistration. |
|
||||||
|
| `wip-public-api-example` | An independently compiled consumer of the protocol, authoring, and host 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 `wip-http`
|
||||||
|
maps standard 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
|
## Interface authoring
|
||||||
|
|
||||||
Applications depend on `wip-interface`, normally imported as `wip`:
|
Applications depend on `wip-interface`, normally imported as `wip`:
|
||||||
@@ -30,38 +127,179 @@ pub trait Messenger {
|
|||||||
```
|
```
|
||||||
|
|
||||||
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
||||||
users do not import `wip-interface-macros` directly. The generated
|
users do not import `wip-interface-macros` or generated private support symbols.
|
||||||
`MessengerDefinition` constructs an `InterfaceDescriptor`, decodes named
|
The generated `MessengerDefinition` constructs an `InterfaceDescriptor`,
|
||||||
arguments, encodes results, validates both boundaries, and provides typed
|
decodes named arguments, encodes results, validates both boundaries, and
|
||||||
dispatch for any `T: Messenger`.
|
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 |
|
| Rust | Protocol |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `()` as an operation result | no returned value |
|
| `()` | unit / `Value::Unit` |
|
||||||
| `bool` | boolean |
|
| `bool` | boolean |
|
||||||
| integer primitives | JavaScript-lossless integer |
|
| integer primitives | JavaScript-lossless integer |
|
||||||
| `f32`, `f64` | finite number |
|
| `f32`, `f64` | finite number |
|
||||||
| `String` | string |
|
| `String` | string |
|
||||||
| `wip::Bytes` | bytes |
|
| `wip::Bytes` | bytes |
|
||||||
| `wip::wip_protocol::JsonValue` | JSON |
|
| `wip::JsonValue` | JSON interpreted over the schema-neutral `Value` tree |
|
||||||
| `wip::Entry<K, V>` | entry |
|
| `wip::Entry` | canonical absolute Worldspace path encoded as a string |
|
||||||
| `Vec<T>` | list |
|
| `Vec<T>` | list |
|
||||||
| named-field `#[derive(wip::WipType)]` struct | named record |
|
| named-field `#[derive(wip::WipType)]` struct | named record |
|
||||||
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
| all-unit `#[derive(wip::WipType)]` enum | named enum encoded as a string |
|
||||||
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
| 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
|
`Option<T>` means that a direct DTO field or operation parameter may be
|
||||||
means that the named value may be omitted. It is not protocol null. Domain
|
omitted; it is not protocol null. JSON null remains available inside
|
||||||
failures are modeled in the application result (usually a derived union) and
|
`wip::JsonValue`.
|
||||||
returned through `Ok`; `wip::HostError` is only for host/runtime failures.
|
|
||||||
|
#### 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`
|
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
||||||
section documents the return declaration; text before that section documents
|
section documents the return declaration; text before that section documents
|
||||||
the operation itself.
|
the operation itself.
|
||||||
|
|
||||||
The supported interface slice is deliberately non-generic: public traits,
|
## Host publication and dispatch
|
||||||
`&self`, named parameters, and `OperationResult<T>`. Generic traits or methods,
|
|
||||||
associated items, custom lifetimes, inheritance, default method bodies, and
|
Applications use `wip-host` to register generated definitions and explicitly
|
||||||
other receiver forms are rejected at their source spans.
|
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.
|
||||||
|
|
||||||
|
## Interactive terminal client
|
||||||
|
|
||||||
|
[`crates/wip-tui`](crates/wip-tui) provides the `wip-tui` executable. It starts
|
||||||
|
from Worldspace `/`, lazily expands materialized tree nodes, displays current
|
||||||
|
object/interface/operation metadata, validates all canonical descriptor types in
|
||||||
|
a field editor, and requires a separate confirmation action before every call.
|
||||||
|
It uses the stateful `wip-client` runtime for request correlation, observed
|
||||||
|
validators, stale transitions, and unknown outcomes. One canonical `http` or
|
||||||
|
`https` endpoint is used unchanged for request construction, transport, and
|
||||||
|
cache partitioning. Scheme, TLS, certificates, authentication, and proxy policy
|
||||||
|
belong to the HTTP implementation and deployment. Full startup, key binding,
|
||||||
|
layout, validator, and filesystem-operation examples are in the
|
||||||
|
[package README](crates/wip-tui/README.md).
|
||||||
|
|
||||||
|
## Filesystem projection server
|
||||||
|
|
||||||
|
[`crates/wip-fs-server`](crates/wip-fs-server) contains the practical server
|
||||||
|
binary and its full security model, configuration, curl walkthrough, and
|
||||||
|
resource/failure semantics. It resolves every object from current filesystem
|
||||||
|
state, uses pinned directory-relative handles without following symlinks, omits
|
||||||
|
non-UTF-8 backend names, returns complete recursive observations through the
|
||||||
|
requested depth or a resource-limit failure, and publishes validator-protected
|
||||||
|
replacement only in explicit read-write mode.
|
||||||
|
The built-in HTTP listener is loopback-only. Externally visible URL schemes,
|
||||||
|
TLS termination, certificates, authentication, and proxy routing are deployment
|
||||||
|
concerns rather than separate WIP profiles.
|
||||||
|
|
||||||
|
## 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,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-client"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Presentation-independent stateful WIP client runtime"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
wip-http = { path = "../wip-http" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,252 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use wip_client::{
|
||||||
|
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
|
||||||
|
ObservationState, OutcomeUnknownReason, SecurityContext,
|
||||||
|
};
|
||||||
|
use wip_http::http::{Response, StatusCode};
|
||||||
|
use wip_http::{
|
||||||
|
Limits, encode_fetch_interface_response, encode_observe_response,
|
||||||
|
encode_protocol_error_response,
|
||||||
|
};
|
||||||
|
use wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
|
Object, ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration,
|
||||||
|
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ReturnDeclaration, TypeExpr, Value,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup() -> (Client, wip_client::SessionId) {
|
||||||
|
let mut client = Client::new(ClientLimits::new(2, 16, 16, 16, 16).unwrap(), limits());
|
||||||
|
let session = client
|
||||||
|
.open_session("https://example.test/wip", SecurityContext::new("subject"))
|
||||||
|
.unwrap();
|
||||||
|
(client, session)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: StatusCode, body: &[u8]) -> Response<Vec<u8>> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object() -> Object {
|
||||||
|
Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec!["math".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: Some(b"object-v1".to_vec()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn descriptor(format: &str) -> InterfaceDescriptor {
|
||||||
|
InterfaceDescriptor {
|
||||||
|
format: format.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "calculate".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![ParameterDeclaration {
|
||||||
|
name: "value".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Integer,
|
||||||
|
}],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Integer,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_json_unknown_fields_duplicates_and_invalid_success_are_invalid_response() {
|
||||||
|
let cases: &[&[u8]] = &[
|
||||||
|
b"{not json",
|
||||||
|
br#"{"name":"item","interfaces":[],"unknown":true}"#,
|
||||||
|
br#"{"name":"item","interfaces":["math","math"]}"#,
|
||||||
|
br#"{"name":"wrong","interfaces":[]}"#,
|
||||||
|
];
|
||||||
|
for body in cases {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
let error = client
|
||||||
|
.complete(request.id, response(StatusCode::OK, body))
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(error.kind, ClientErrorKind::InvalidResponse);
|
||||||
|
assert!(matches!(
|
||||||
|
client.object(&session, "/item").unwrap().state,
|
||||||
|
ObservationState::Error(_)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disallowed_code_and_status_success_contradictions_are_invalid_response() {
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
br#"{"error":{"code":"interface_not_found","message":"wrong"}}"#.as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
br#"{"error":{"code":"not_found","message":"wrong status"}}"#.as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::CREATED,
|
||||||
|
br#"{"name":"item","interfaces":[]}"#.as_slice(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (status, body) in cases {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
client
|
||||||
|
.complete(request.id, response(status, body))
|
||||||
|
.unwrap_err()
|
||||||
|
.kind,
|
||||||
|
ClientErrorKind::InvalidResponse
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_error_envelope_is_authoritative_and_status_mismatch_is_diagnostic() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
|
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
client.complete(request.id, encoded).unwrap(),
|
||||||
|
Completion::ProtocolFailure(error)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/item").unwrap().state,
|
||||||
|
ObservationState::Stale
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||||
|
DiagnosticKind::HttpStatusMismatch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_success_without_valid_envelope_remains_transport_failure() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
let error = client
|
||||||
|
.complete(
|
||||||
|
request.id,
|
||||||
|
response(StatusCode::BAD_GATEWAY, b"gateway html"),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(error.kind, ClientErrorKind::Transport);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_descriptor_format_is_distinct_from_invalid_response() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
let logical = FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
};
|
||||||
|
let value = FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor("future-format/2"),
|
||||||
|
validator: Some(b"v2".to_vec()),
|
||||||
|
};
|
||||||
|
let encoded = encode_fetch_interface_response(&logical, &value, limits()).unwrap();
|
||||||
|
let error = client.complete(request.id, encoded).unwrap_err();
|
||||||
|
assert_eq!(error.kind, ClientErrorKind::UnsupportedDescriptorFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
observation.id,
|
||||||
|
encode_observe_response(
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
&ObjectObservation {
|
||||||
|
object: object(),
|
||||||
|
children: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let interface = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
interface.id,
|
||||||
|
encode_fetch_interface_response(
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
},
|
||||||
|
&FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let call = client
|
||||||
|
.prepare_call(
|
||||||
|
&session,
|
||||||
|
"/item",
|
||||||
|
"math",
|
||||||
|
"calculate",
|
||||||
|
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.mark_dispatched(call.id).unwrap();
|
||||||
|
|
||||||
|
let completion = client
|
||||||
|
.complete(
|
||||||
|
call.id,
|
||||||
|
response(
|
||||||
|
StatusCode::OK,
|
||||||
|
br#"{"result":"not an integer","unknown":true}"#,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
completion,
|
||||||
|
Completion::Call(record)
|
||||||
|
if matches!(
|
||||||
|
&record.outcome,
|
||||||
|
CallOutcome::Unknown {
|
||||||
|
reason: OutcomeUnknownReason::ResponseDecode,
|
||||||
|
failure: Some(failure),
|
||||||
|
} if failure.kind == ClientErrorKind::InvalidResponse
|
||||||
|
)
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/item").unwrap().state,
|
||||||
|
ObservationState::Stale
|
||||||
|
);
|
||||||
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-fs-server"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Request-time filesystem projection server for WIP over HTTP"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
http = "1"
|
||||||
|
rustix = { version = "1.1", features = ["fs"] }
|
||||||
|
wip-host = { path = "../wip-host" }
|
||||||
|
wip-http = { path = "../wip-http" }
|
||||||
|
wip-interface = { path = "../wip-interface" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# wip-fs-server
|
||||||
|
|
||||||
|
`wip-fs-server` projects one configured Linux filesystem directory onto WIP
|
||||||
|
Worldspace `/` at request time. It does not register the filesystem contents or
|
||||||
|
keep one object instance per entry. It uses `wip-host` for publication and typed
|
||||||
|
operation dispatch and uses the standard `wip-http` routes, JSON codecs,
|
||||||
|
envelopes, batching, and HTTP status mapping.
|
||||||
|
|
||||||
|
## Security model
|
||||||
|
|
||||||
|
- The effective root is opened once as a directory capability. Root path
|
||||||
|
components must be real directories (symlink components are rejected), and the
|
||||||
|
displayed effective root is read back from that same pinned descriptor. Every
|
||||||
|
request is resolved segment-by-segment with directory-relative, `O_NOFOLLOW`
|
||||||
|
handles.
|
||||||
|
- Symlinks are projected as links and are never followed. Their stored target is
|
||||||
|
available only through the `SymlinkInspect.read_link` application operation.
|
||||||
|
- Regular files, directories, symlinks, and unsupported entry types have distinct
|
||||||
|
public descriptions and capability sets.
|
||||||
|
- WIP names are Unicode. Linux names that are not valid UTF-8 are deliberately
|
||||||
|
not published; valid UTF-8 names map byte-for-byte and therefore cannot collide.
|
||||||
|
Unicode paths containing backend-invalid NUL bytes are likewise treated as
|
||||||
|
unpublished rather than as backend failures.
|
||||||
|
- No object `ref` is issued. This avoids claiming representation identity for
|
||||||
|
hard links or path-specific names. Regular files and symlinks receive an opaque
|
||||||
|
validator containing filesystem identity plus protected metadata; replacing a
|
||||||
|
path therefore does not preserve its validator.
|
||||||
|
- Protocol metadata and errors never contain the backend absolute path. Startup
|
||||||
|
prints only the explicitly configured effective root and security-sensitive
|
||||||
|
modes.
|
||||||
|
- The built-in HTTP listener is loopback-only. TLS termination, certificates,
|
||||||
|
authentication, an externally visible URL scheme, and proxy routing are
|
||||||
|
deployment concerns rather than separate WIP transport profiles.
|
||||||
|
|
||||||
|
The implementation currently targets Linux because it uses `O_PATH`,
|
||||||
|
directory-relative descriptor traversal, and `/proc/self/fd` to reopen the same
|
||||||
|
pinned backend object without resolving the untrusted Worldspace path twice.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
Run the loopback listener in read-only mode:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root /srv/public-files \
|
||||||
|
--listen 127.0.0.1:8080 \
|
||||||
|
--base-path /wip
|
||||||
|
```
|
||||||
|
|
||||||
|
Run with the write capability deliberately enabled:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root ./example-files \
|
||||||
|
--listen 127.0.0.1:8080 \
|
||||||
|
--base-path /wip \
|
||||||
|
--read-write
|
||||||
|
```
|
||||||
|
|
||||||
|
The server reports the effective root, `ReadOnly`/`ReadWrite` mode, endpoint,
|
||||||
|
and actual listen address. It does not enumerate the root.
|
||||||
|
|
||||||
|
## Standard interactions
|
||||||
|
|
||||||
|
The following examples use the built-in HTTP listener. The JSON follows the
|
||||||
|
standard WIP over HTTP binding; validators and operation `Bytes` are base64 body
|
||||||
|
fields, never `ETag` or `If-Match` headers.
|
||||||
|
|
||||||
|
Observe only the root Object:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/observe \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"path":"/","depth":0}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Observe the root and two levels of indexable children:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/observe \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"path":"/","depth":2}'
|
||||||
|
```
|
||||||
|
|
||||||
|
A regular-file observation returns the opaque read interface reference and an object
|
||||||
|
validator. Retrieve that descriptor with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_interface \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"interface":"<read-interface-from-observation>"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Then call a bounded range read:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{
|
||||||
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
|
"interface":{"reference":"<read-interface>"},
|
||||||
|
"operation":"read",
|
||||||
|
"arguments":{"offset":0,"length":4096}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
In `--read-write` mode a second regular-file interface declares `replace`.
|
||||||
|
Writes require the current object validator and return the post-write validator:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{
|
||||||
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
|
"interface":{"reference":"<write-interface>"},
|
||||||
|
"operation":"replace",
|
||||||
|
"arguments":{"contents":"dXBkYXRlZA=="}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`observe` and `fetch_interface` can also be combined through the standard
|
||||||
|
`POST /wip/v1/batch` route. `call_operation` is never batchable.
|
||||||
|
|
||||||
|
## Resource and failure behavior
|
||||||
|
|
||||||
|
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
||||||
|
nesting, batch items, file read/write bytes, tree depth/node count, pinned handles,
|
||||||
|
and active connections/requests. One absolute request deadline covers header and
|
||||||
|
body intake, dispatch, cooperative filesystem work, and response transmission;
|
||||||
|
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
||||||
|
accept connections directly, so the listener never moves more than the configured
|
||||||
|
concurrency into active userspace service. Advisory file-lock acquisition uses a
|
||||||
|
nonblocking loop and checks the same deadline/cancellation rather than allowing a
|
||||||
|
contended lock to stall a worker. Object observation recursively opens only the
|
||||||
|
requested depth. A successful response is complete through that depth; if the
|
||||||
|
configured projected-node budget would be exceeded, the interaction fails with
|
||||||
|
`ResourceLimitExceeded` instead of returning a partial observation. I/O failure
|
||||||
|
and cancellation remain errors.
|
||||||
|
|
||||||
|
Whole-file replacement compares the request validator against the identity and
|
||||||
|
state of the same pinned file handle used for the write. Failures before mutation
|
||||||
|
carry a `NotCommitted` guarantee and map to `Internal` or
|
||||||
|
`ResourceLimitExceeded`; a failure after truncation/write begins maps to
|
||||||
|
`OperationOutcomeUnknown`. The server and Clients do not automatically retry
|
||||||
|
side-effecting operations.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
//! Filesystem capability interfaces published by the projection.
|
||||||
|
|
||||||
|
use wip_interface as wip;
|
||||||
|
|
||||||
|
/// Bounded reads from a regular file.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait FileRead {
|
||||||
|
/// Reads bytes from the current regular file.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// At most the configured read limit, beginning at `offset`.
|
||||||
|
fn read(
|
||||||
|
&self,
|
||||||
|
/// Byte offset; omitted means zero.
|
||||||
|
offset: Option<u64>,
|
||||||
|
/// Requested byte count; omitted means the rest of the file.
|
||||||
|
length: Option<u64>,
|
||||||
|
) -> wip::OperationResult<wip::Bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inspection operations for a symbolic link itself.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait SymlinkInspect {
|
||||||
|
/// Reads the link payload without following it.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// The platform path bytes stored in the symbolic link.
|
||||||
|
fn read_link(&self) -> wip::OperationResult<wip::Bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicitly enabled mutation of a regular file.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait FileWrite {
|
||||||
|
/// Replaces the current regular file contents through its pinned handle.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// Unit after the new bytes have been written and synchronized.
|
||||||
|
fn replace(
|
||||||
|
&self,
|
||||||
|
/// Complete replacement contents.
|
||||||
|
contents: wip::Bytes,
|
||||||
|
) -> wip::OperationResult<()>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
//! Request-time filesystem projection served through the standard WIP over HTTP binding.
|
||||||
|
//!
|
||||||
|
//! This crate deliberately keeps the boundaries visible:
|
||||||
|
//!
|
||||||
|
//! - [`wip_protocol`] owns logical requests and responses;
|
||||||
|
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
||||||
|
//! - [`wip_http`] owns routes, JSON, envelopes, batching, and status mapping;
|
||||||
|
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
||||||
|
//!
|
||||||
|
//! The built-in HTTP listener is intentionally loopback-only. TLS termination,
|
||||||
|
//! certificates, authentication, and externally visible schemes are independent
|
||||||
|
//! deployment concerns rather than WIP transport profiles.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
mod interfaces;
|
||||||
|
mod projection;
|
||||||
|
mod server;
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub use interfaces::{FileRead, FileWrite, SymlinkInspect};
|
||||||
|
pub use server::{BoundServer, ServerBuildError, WipFsServer};
|
||||||
|
|
||||||
|
/// Filesystem capabilities published by regular files.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AccessMode {
|
||||||
|
/// Publish bounded reads only.
|
||||||
|
ReadOnly,
|
||||||
|
/// Also publish validator-protected whole-file replacement.
|
||||||
|
ReadWrite,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct ResourceLimits {
|
||||||
|
/// Standard JSON, body-size, nesting, and batch limits.
|
||||||
|
pub wire: wip_http::Limits,
|
||||||
|
/// Maximum bytes returned by one file read.
|
||||||
|
pub max_file_read_bytes: usize,
|
||||||
|
/// Maximum bytes accepted by one file replacement.
|
||||||
|
pub max_file_write_bytes: usize,
|
||||||
|
/// Maximum accepted `observe` depth.
|
||||||
|
pub max_observation_depth: u32,
|
||||||
|
/// Maximum accepted `observe` node count, including its root.
|
||||||
|
pub max_observation_nodes: u32,
|
||||||
|
/// Maximum simultaneously pinned projected filesystem handles.
|
||||||
|
pub max_open_handles: usize,
|
||||||
|
/// Maximum bytes accepted for one HTTP request head, including its terminator.
|
||||||
|
pub max_http_header_bytes: usize,
|
||||||
|
/// Maximum requests executing concurrently.
|
||||||
|
pub max_concurrent_requests: usize,
|
||||||
|
/// End-to-end deadline for HTTP intake, dispatch, and response transmission.
|
||||||
|
pub request_timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ResourceLimits {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
wire: wip_http::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
||||||
|
.expect("default wire limits are nonzero"),
|
||||||
|
max_file_read_bytes: 1024 * 1024,
|
||||||
|
max_file_write_bytes: 1024 * 1024,
|
||||||
|
max_observation_depth: 32,
|
||||||
|
max_observation_nodes: 1024,
|
||||||
|
max_open_handles: 2048,
|
||||||
|
max_http_header_bytes: 16 * 1024,
|
||||||
|
max_concurrent_requests: 32,
|
||||||
|
request_timeout: Duration::from_secs(30),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Complete listener and projection configuration.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
/// Filesystem directory projected as Worldspace `/`.
|
||||||
|
pub root: PathBuf,
|
||||||
|
/// Loopback socket used by the built-in cleartext listener.
|
||||||
|
pub listen: SocketAddr,
|
||||||
|
/// URL path prefix below which standard `v1/*` routes are mounted.
|
||||||
|
pub endpoint_base_path: String,
|
||||||
|
/// Read-only or explicit read-write publication mode.
|
||||||
|
pub access: AccessMode,
|
||||||
|
/// Request, operation, traversal, and concurrency bounds.
|
||||||
|
pub limits: ResourceLimits,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServerConfig {
|
||||||
|
/// Builds a secure-by-default configuration for `root`.
|
||||||
|
///
|
||||||
|
/// The listener defaults to an ephemeral loopback port and read-only access.
|
||||||
|
#[must_use]
|
||||||
|
pub fn for_root(root: impl Into<PathBuf>) -> Self {
|
||||||
|
Self {
|
||||||
|
root: root.into(),
|
||||||
|
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
||||||
|
endpoint_base_path: "/wip".into(),
|
||||||
|
access: AccessMode::ReadOnly,
|
||||||
|
limits: ResourceLimits::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
if !self.listen.ip().is_loopback() {
|
||||||
|
return Err(ConfigError::NonLoopbackCleartext);
|
||||||
|
}
|
||||||
|
if !valid_base_path(&self.endpoint_base_path) {
|
||||||
|
return Err(ConfigError::InvalidBasePath);
|
||||||
|
}
|
||||||
|
if self.limits.max_file_read_bytes == 0
|
||||||
|
|| self.limits.max_file_write_bytes == 0
|
||||||
|
|| self.limits.max_observation_nodes == 0
|
||||||
|
|| self.limits.max_open_handles == 0
|
||||||
|
|| self.limits.max_http_header_bytes == 0
|
||||||
|
|| self.limits.max_concurrent_requests == 0
|
||||||
|
|| self.limits.request_timeout.is_zero()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::ZeroLimit);
|
||||||
|
}
|
||||||
|
if self.limits.max_open_handles < self.limits.max_observation_nodes as usize {
|
||||||
|
return Err(ConfigError::InsufficientHandles);
|
||||||
|
}
|
||||||
|
if self.limits.wire.max_response_bytes() < 512 {
|
||||||
|
return Err(ConfigError::ResponseLimitTooSmall);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn endpoint(&self) -> Result<wip_http::Endpoint, ConfigError> {
|
||||||
|
let endpoint = format!("http://localhost{}", self.endpoint_base_path);
|
||||||
|
wip_http::Endpoint::parse(&endpoint).map_err(|_| ConfigError::InvalidBasePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalid server configuration.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
/// The cleartext built-in listener was exposed beyond loopback.
|
||||||
|
NonLoopbackCleartext,
|
||||||
|
/// The endpoint prefix is not an absolute canonical URL path.
|
||||||
|
InvalidBasePath,
|
||||||
|
/// A resource limit is zero.
|
||||||
|
ZeroLimit,
|
||||||
|
/// Tree nodes could exhaust the configured handle ceiling by construction.
|
||||||
|
InsufficientHandles,
|
||||||
|
/// The response limit cannot reliably carry a bounded protocol error envelope.
|
||||||
|
ResponseLimitTooSmall,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ConfigError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
formatter.write_str(match self {
|
||||||
|
Self::NonLoopbackCleartext => "the built-in cleartext listener must bind to loopback",
|
||||||
|
Self::InvalidBasePath => {
|
||||||
|
"endpoint base path must be absolute, canonical, and query-free"
|
||||||
|
}
|
||||||
|
Self::ZeroLimit => "all resource limits and the request timeout must be nonzero",
|
||||||
|
Self::InsufficientHandles => "max_open_handles must cover max_observation_nodes",
|
||||||
|
Self::ResponseLimitTooSmall => "max_response_bytes must be at least 512",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ConfigError {}
|
||||||
|
|
||||||
|
fn valid_base_path(path: &str) -> bool {
|
||||||
|
path.starts_with('/')
|
||||||
|
&& !path.contains('?')
|
||||||
|
&& !path.contains('#')
|
||||||
|
&& !path.contains("//")
|
||||||
|
&& !path
|
||||||
|
.split('/')
|
||||||
|
.any(|segment| segment == "." || segment == "..")
|
||||||
|
&& (path == "/" || !path.ends_with('/'))
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let mut root: Option<PathBuf> = None;
|
||||||
|
let mut listen: SocketAddr = "127.0.0.1:8080".parse()?;
|
||||||
|
let mut base_path = "/wip".to_owned();
|
||||||
|
let mut access = AccessMode::ReadOnly;
|
||||||
|
let mut arguments = std::env::args().skip(1);
|
||||||
|
while let Some(argument) = arguments.next() {
|
||||||
|
match argument.as_str() {
|
||||||
|
"--root" => root = Some(PathBuf::from(required_value(&mut arguments, "--root")?)),
|
||||||
|
"--listen" => listen = required_value(&mut arguments, "--listen")?.parse()?,
|
||||||
|
"--base-path" => base_path = required_value(&mut arguments, "--base-path")?,
|
||||||
|
"--read-write" => access = AccessMode::ReadWrite,
|
||||||
|
"--help" | "-h" => {
|
||||||
|
print_help();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
unknown => return Err(format!("unknown argument `{unknown}`; use --help").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let root = root.ok_or("--root is required")?;
|
||||||
|
let mut config = ServerConfig::for_root(root);
|
||||||
|
config.listen = listen;
|
||||||
|
config.endpoint_base_path = base_path;
|
||||||
|
config.access = access;
|
||||||
|
|
||||||
|
let server = WipFsServer::new(config)?;
|
||||||
|
let effective_root = server.effective_root().to_owned();
|
||||||
|
let endpoint = server.endpoint().clone();
|
||||||
|
let bound = server.bind()?;
|
||||||
|
eprintln!(
|
||||||
|
"wip-fs-server root={} access={access:?} endpoint={} listen={}",
|
||||||
|
effective_root.display(),
|
||||||
|
endpoint,
|
||||||
|
bound.local_addr()
|
||||||
|
);
|
||||||
|
bound.serve()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_value(
|
||||||
|
arguments: &mut impl Iterator<Item = String>,
|
||||||
|
option: &str,
|
||||||
|
) -> Result<String, Box<dyn Error>> {
|
||||||
|
arguments
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| format!("{option} requires a value").into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_help() {
|
||||||
|
println!(
|
||||||
|
"Usage: wip-fs-server --root PATH [--listen 127.0.0.1:8080] \\\n [--base-path /wip] [--read-write]\n\n\
|
||||||
|
The built-in HTTP listener is loopback-only. TLS termination, authentication, \
|
||||||
|
and external routing are deployment concerns."
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,722 @@
|
|||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use http::{Request, Response, StatusCode};
|
||||||
|
use wip_host::{ExecutionContext, ObjectProvider};
|
||||||
|
use wip_http::{
|
||||||
|
BatchRequestKind, BatchResponse, BatchResponseItem, BatchSuccess, CodecError, EncodeHttpError,
|
||||||
|
Endpoint, RequestMetadataError, ResourceLimitKind, Route, decode_batch_request,
|
||||||
|
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
|
||||||
|
encode_batch_error_response, encode_batch_resource_limit_error_response, encode_batch_response,
|
||||||
|
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
|
||||||
|
encode_protocol_error_response, encode_resource_limit_error_response, validate_http_request,
|
||||||
|
};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
|
use crate::projection::Projection;
|
||||||
|
use crate::{ConfigError, ServerConfig};
|
||||||
|
|
||||||
|
/// Filesystem projection and framework-neutral standard WIP request adapter.
|
||||||
|
pub struct WipFsServer {
|
||||||
|
config: ServerConfig,
|
||||||
|
endpoint: Endpoint,
|
||||||
|
effective_root: std::path::PathBuf,
|
||||||
|
projection: Arc<Projection>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WipFsServer {
|
||||||
|
/// Validates configuration and opens the configured directory capability.
|
||||||
|
pub fn new(config: ServerConfig) -> Result<Self, ServerBuildError> {
|
||||||
|
config.validate()?;
|
||||||
|
let endpoint = config.endpoint()?;
|
||||||
|
let projection = Projection::open(&config.root, config.access, config.limits)?;
|
||||||
|
let effective_root = projection.effective_root()?;
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
endpoint,
|
||||||
|
effective_root,
|
||||||
|
projection: Arc::new(projection),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical effective filesystem root opened by the server.
|
||||||
|
#[must_use]
|
||||||
|
pub fn effective_root(&self) -> &std::path::Path {
|
||||||
|
&self.effective_root
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the configured transport endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub fn endpoint(&self) -> &Endpoint {
|
||||||
|
&self.endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles one already-buffered HTTP request with the standard `wip-http` codecs.
|
||||||
|
///
|
||||||
|
/// Listener integrations must enforce the same body limit while collecting bytes.
|
||||||
|
#[must_use]
|
||||||
|
pub fn handle_http(&self, request: Request<Vec<u8>>) -> Response<Vec<u8>> {
|
||||||
|
self.handle_http_with_deadline(request, Instant::now() + self.config.limits.request_timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_http_with_deadline(
|
||||||
|
&self,
|
||||||
|
request: Request<Vec<u8>>,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let Some(route) = self.route(request.uri().path()) else {
|
||||||
|
return empty_response(StatusCode::NOT_FOUND);
|
||||||
|
};
|
||||||
|
if let Err(error) = validate_http_request(&self.endpoint, route, &request) {
|
||||||
|
return self.metadata_error(route, error);
|
||||||
|
}
|
||||||
|
let context = ExecutionContext::new()
|
||||||
|
.with_deadline(deadline)
|
||||||
|
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
||||||
|
match route {
|
||||||
|
Route::Observe => self.observe(request.body(), &context),
|
||||||
|
Route::FetchInterface => self.fetch_interface(request.body()),
|
||||||
|
Route::CallOperation => self.call_operation(request.body(), &context),
|
||||||
|
Route::Batch => self.batch(request.body(), &context),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Binds the built-in bounded loopback HTTP listener.
|
||||||
|
///
|
||||||
|
/// The built-in listener is cleartext and loopback-only. Externally visible
|
||||||
|
/// schemes, TLS termination, authentication, and proxy routing are deployment
|
||||||
|
/// concerns rather than WIP transport profiles.
|
||||||
|
pub fn bind(self) -> Result<BoundServer, ServerBuildError> {
|
||||||
|
let listener = TcpListener::bind(self.config.listen)
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
listener
|
||||||
|
.set_nonblocking(true)
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
let local_addr = listener
|
||||||
|
.local_addr()
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
Ok(BoundServer {
|
||||||
|
local_addr,
|
||||||
|
service: Arc::new(self),
|
||||||
|
listener: Arc::new(listener),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(&self, path: &str) -> Option<Route> {
|
||||||
|
[
|
||||||
|
Route::Observe,
|
||||||
|
Route::FetchInterface,
|
||||||
|
Route::CallOperation,
|
||||||
|
Route::Batch,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|route| self.endpoint.route(*route).path() == path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
|
let request = match decode_observe_request(body, self.config.limits.wire) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return self.codec_error(ProtocolInteraction::Observe, error),
|
||||||
|
};
|
||||||
|
match self.projection.observe(context, &request) {
|
||||||
|
Ok(tree) => encode_observe_response(&request, &tree, self.config.limits.wire)
|
||||||
|
.unwrap_or_else(|error| {
|
||||||
|
self.read_encode_error(ProtocolInteraction::Observe, error)
|
||||||
|
}),
|
||||||
|
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch_interface(&self, body: &[u8]) -> Response<Vec<u8>> {
|
||||||
|
let request = match decode_fetch_interface_request(body, self.config.limits.wire) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return self.codec_error(ProtocolInteraction::FetchInterface, error),
|
||||||
|
};
|
||||||
|
match self.projection.fetch_interface(&request) {
|
||||||
|
Ok(interface) => {
|
||||||
|
encode_fetch_interface_response(&request, &interface, self.config.limits.wire)
|
||||||
|
.unwrap_or_else(|error| {
|
||||||
|
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call_operation(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
|
let metadata = match decode_call_operation_metadata(body, self.config.limits.wire) {
|
||||||
|
Ok(metadata) => metadata,
|
||||||
|
Err(error) => return self.codec_error(ProtocolInteraction::CallOperation, error),
|
||||||
|
};
|
||||||
|
let may_commit = metadata.operation == "replace";
|
||||||
|
let decoded = std::sync::Mutex::new(None);
|
||||||
|
let execution = self.projection.call_operation_with_context_and_decoder(
|
||||||
|
context,
|
||||||
|
metadata.target.clone(),
|
||||||
|
metadata.interface.clone(),
|
||||||
|
metadata.operation.clone(),
|
||||||
|
|descriptor| {
|
||||||
|
let request = metadata.decode_request(body, descriptor, self.config.limits.wire)?;
|
||||||
|
let arguments = request.arguments.clone();
|
||||||
|
*decoded.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||||
|
Some((request, descriptor.clone()));
|
||||||
|
Ok::<_, CodecError>(arguments)
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match execution.map_err(|error| error.protocol_error()) {
|
||||||
|
Ok(result) => {
|
||||||
|
let Some((request, descriptor)) = decoded
|
||||||
|
.into_inner()
|
||||||
|
.unwrap_or_else(|error| error.into_inner())
|
||||||
|
else {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: if may_commit {
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown
|
||||||
|
} else {
|
||||||
|
ProtocolErrorCode::Internal
|
||||||
|
},
|
||||||
|
message: "operation completed without response metadata".into(),
|
||||||
|
};
|
||||||
|
return self.protocol_error(ProtocolInteraction::CallOperation, &error, None);
|
||||||
|
};
|
||||||
|
encode_call_operation_response(
|
||||||
|
&request,
|
||||||
|
&descriptor,
|
||||||
|
&result,
|
||||||
|
self.config.limits.wire,
|
||||||
|
)
|
||||||
|
.unwrap_or_else(|encode_error| {
|
||||||
|
if !may_commit {
|
||||||
|
return self
|
||||||
|
.read_encode_error(ProtocolInteraction::CallOperation, encode_error);
|
||||||
|
}
|
||||||
|
// Replacement may already be committed, so a response
|
||||||
|
// encoding failure cannot carry a non-commit guarantee.
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
message: "operation completed but its response could not be encoded".into(),
|
||||||
|
};
|
||||||
|
self.protocol_error(ProtocolInteraction::CallOperation, &error, None)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
|
let request = match decode_batch_request(body, self.config.limits.wire) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return self.batch_codec_error(error),
|
||||||
|
};
|
||||||
|
let responses = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(|item| {
|
||||||
|
let outcome = match &item.request {
|
||||||
|
BatchRequestKind::Observe(request) => self
|
||||||
|
.projection
|
||||||
|
.observe(context, request)
|
||||||
|
.map(BatchSuccess::Observe),
|
||||||
|
BatchRequestKind::FetchInterface(request) => self
|
||||||
|
.projection
|
||||||
|
.fetch_interface(request)
|
||||||
|
.map(BatchSuccess::FetchInterface),
|
||||||
|
BatchRequestKind::Invalid { error, .. } => Err(error.clone()),
|
||||||
|
};
|
||||||
|
BatchResponseItem {
|
||||||
|
id: item.id.clone(),
|
||||||
|
outcome,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let response = BatchResponse { responses };
|
||||||
|
encode_batch_response(&request, &response, self.config.limits.wire).unwrap_or_else(
|
||||||
|
|error| match error {
|
||||||
|
EncodeHttpError::Codec(codec) => self.batch_codec_error(codec),
|
||||||
|
EncodeHttpError::Http(_) => self.batch_top_error(&internal_error(), None),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn metadata_error(&self, route: Route, error: RequestMetadataError) -> Response<Vec<u8>> {
|
||||||
|
match error {
|
||||||
|
RequestMetadataError::InvalidRequest(_) => self.protocol_error(
|
||||||
|
interaction(route),
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "invalid HTTP request metadata".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
RequestMetadataError::UnsupportedMediaType => {
|
||||||
|
empty_response(StatusCode::UNSUPPORTED_MEDIA_TYPE)
|
||||||
|
}
|
||||||
|
RequestMetadataError::NotAcceptable => empty_response(StatusCode::NOT_ACCEPTABLE),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codec_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: CodecError,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
if let Some(kind) = error.resource_limit_kind() {
|
||||||
|
self.protocol_error(interaction, &resource_error(), Some(kind))
|
||||||
|
} else {
|
||||||
|
self.protocol_error(
|
||||||
|
interaction,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "malformed WIP request".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch_codec_error(&self, error: CodecError) -> Response<Vec<u8>> {
|
||||||
|
if let Some(kind) = error.resource_limit_kind() {
|
||||||
|
self.batch_top_error(&resource_error(), Some(kind))
|
||||||
|
} else {
|
||||||
|
self.batch_top_error(
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "malformed WIP batch request".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_encode_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: EncodeHttpError,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
match error {
|
||||||
|
EncodeHttpError::Codec(codec) if codec.resource_limit_kind().is_some() => {
|
||||||
|
self.protocol_error(interaction, &resource_error(), codec.resource_limit_kind())
|
||||||
|
}
|
||||||
|
_ => self.protocol_error(interaction, &internal_error(), None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn protocol_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
resource_kind: Option<ResourceLimitKind>,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let encoded = match resource_kind {
|
||||||
|
Some(kind) => encode_resource_limit_error_response(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
kind,
|
||||||
|
self.config.limits.wire,
|
||||||
|
),
|
||||||
|
None => encode_protocol_error_response(interaction, error, self.config.limits.wire),
|
||||||
|
};
|
||||||
|
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch_top_error(
|
||||||
|
&self,
|
||||||
|
error: &ProtocolError,
|
||||||
|
resource_kind: Option<ResourceLimitKind>,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let encoded = match resource_kind {
|
||||||
|
Some(kind) => {
|
||||||
|
encode_batch_resource_limit_error_response(error, kind, self.config.limits.wire)
|
||||||
|
}
|
||||||
|
None => encode_batch_error_response(error, self.config.limits.wire),
|
||||||
|
};
|
||||||
|
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bound real HTTP listener for a [`WipFsServer`].
|
||||||
|
pub struct BoundServer {
|
||||||
|
local_addr: SocketAddr,
|
||||||
|
service: Arc<WipFsServer>,
|
||||||
|
listener: Arc<TcpListener>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundServer {
|
||||||
|
/// Returns the actual bound loopback address, including an assigned port.
|
||||||
|
#[must_use]
|
||||||
|
pub fn local_addr(&self) -> SocketAddr {
|
||||||
|
self.local_addr
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves requests with a fixed worker count until `shutdown` becomes true.
|
||||||
|
///
|
||||||
|
/// Workers accept connections directly, so at most
|
||||||
|
/// `max_concurrent_requests` sockets are active in userspace. Each connection
|
||||||
|
/// is closed after one request and shares one absolute deadline across HTTP
|
||||||
|
/// intake, dispatch, and response transmission.
|
||||||
|
pub fn serve_until(&self, shutdown: Arc<AtomicBool>) -> Result<(), std::io::Error> {
|
||||||
|
let mut workers = Vec::with_capacity(self.service.config.limits.max_concurrent_requests);
|
||||||
|
for _ in 0..self.service.config.limits.max_concurrent_requests {
|
||||||
|
let listener = Arc::clone(&self.listener);
|
||||||
|
let service = Arc::clone(&self.service);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
workers.push(thread::spawn(move || {
|
||||||
|
while !shutdown.load(Ordering::Acquire) {
|
||||||
|
match listener.accept() {
|
||||||
|
Ok((stream, _)) => serve_connection(&service, stream),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||||
|
thread::sleep(Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
for worker in workers {
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.map_err(|_| std::io::Error::other("HTTP worker panicked"))??;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves until the process is terminated.
|
||||||
|
pub fn serve(&self) -> Result<(), std::io::Error> {
|
||||||
|
self.serve_until(Arc::new(AtomicBool::new(false)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct ParsedRequestHead {
|
||||||
|
method: http::Method,
|
||||||
|
target: String,
|
||||||
|
headers: Vec<(http::header::HeaderName, http::HeaderValue)>,
|
||||||
|
content_length: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum IntakeError {
|
||||||
|
Timeout,
|
||||||
|
HeaderTooLarge,
|
||||||
|
PayloadTooLarge { target: String },
|
||||||
|
BadRequest,
|
||||||
|
Socket,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve_connection(service: &WipFsServer, mut stream: TcpStream) {
|
||||||
|
let _ = stream.set_nonblocking(false);
|
||||||
|
let started = Instant::now();
|
||||||
|
let deadline = started
|
||||||
|
.checked_add(service.config.limits.request_timeout)
|
||||||
|
.unwrap_or(started);
|
||||||
|
let response = match read_http_request(
|
||||||
|
&mut stream,
|
||||||
|
service.config.limits.max_http_header_bytes,
|
||||||
|
service.config.limits.wire.max_request_bytes(),
|
||||||
|
deadline,
|
||||||
|
) {
|
||||||
|
Ok(request) => Some(service.handle_http_with_deadline(request, deadline)),
|
||||||
|
Err(IntakeError::HeaderTooLarge) => {
|
||||||
|
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
||||||
|
}
|
||||||
|
Err(IntakeError::PayloadTooLarge { target }) => {
|
||||||
|
Some(payload_too_large_response(service, &target))
|
||||||
|
}
|
||||||
|
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
||||||
|
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
||||||
|
};
|
||||||
|
if let Some(response) = response {
|
||||||
|
let _ = write_http_response(&mut stream, &response, deadline);
|
||||||
|
}
|
||||||
|
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_http_request(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
maximum_header: usize,
|
||||||
|
maximum_body: usize,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<Request<Vec<u8>>, IntakeError> {
|
||||||
|
let mut received = Vec::with_capacity(maximum_header.min(8 * 1024));
|
||||||
|
let header_end = loop {
|
||||||
|
if let Some(position) = received.windows(4).position(|window| window == b"\r\n\r\n") {
|
||||||
|
let end = position + 4;
|
||||||
|
if end > maximum_header {
|
||||||
|
return Err(IntakeError::HeaderTooLarge);
|
||||||
|
}
|
||||||
|
break end;
|
||||||
|
}
|
||||||
|
if received.len() >= maximum_header {
|
||||||
|
return Err(IntakeError::HeaderTooLarge);
|
||||||
|
}
|
||||||
|
let mut chunk = [0_u8; 4 * 1024];
|
||||||
|
let available = (maximum_header - received.len()).min(chunk.len());
|
||||||
|
let count = read_with_deadline(stream, &mut chunk[..available], deadline)?;
|
||||||
|
if count == 0 {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
received.extend_from_slice(&chunk[..count]);
|
||||||
|
};
|
||||||
|
|
||||||
|
let parsed = parse_request_head(&received[..header_end])?;
|
||||||
|
if parsed.content_length > maximum_body {
|
||||||
|
return Err(IntakeError::PayloadTooLarge {
|
||||||
|
target: parsed.target,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut body = Vec::with_capacity(parsed.content_length);
|
||||||
|
let buffered = &received[header_end..];
|
||||||
|
body.extend_from_slice(&buffered[..buffered.len().min(parsed.content_length)]);
|
||||||
|
while body.len() < parsed.content_length {
|
||||||
|
let mut chunk = [0_u8; 8 * 1024];
|
||||||
|
let wanted = (parsed.content_length - body.len()).min(chunk.len());
|
||||||
|
let count = read_with_deadline(stream, &mut chunk[..wanted], deadline)?;
|
||||||
|
if count == 0 {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk[..count]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut builder = Request::builder().method(parsed.method).uri(parsed.target);
|
||||||
|
for (name, value) in parsed.headers {
|
||||||
|
builder = builder.header(name, value);
|
||||||
|
}
|
||||||
|
builder.body(body).map_err(|_| IntakeError::BadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_request_head(bytes: &[u8]) -> Result<ParsedRequestHead, IntakeError> {
|
||||||
|
let text = std::str::from_utf8(bytes).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let mut lines = text
|
||||||
|
.strip_suffix("\r\n\r\n")
|
||||||
|
.ok_or(IntakeError::BadRequest)?
|
||||||
|
.split("\r\n");
|
||||||
|
let mut request_line = lines
|
||||||
|
.next()
|
||||||
|
.ok_or(IntakeError::BadRequest)?
|
||||||
|
.split_ascii_whitespace();
|
||||||
|
let method = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
let target = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
let version = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
if request_line.next().is_some()
|
||||||
|
|| !matches!(version, "HTTP/1.0" | "HTTP/1.1")
|
||||||
|
|| !target.starts_with('/')
|
||||||
|
{
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
let method =
|
||||||
|
http::Method::from_bytes(method.as_bytes()).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let _: http::Uri = target.parse().map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
let mut content_length = None;
|
||||||
|
for line in lines {
|
||||||
|
if line.is_empty() || line.starts_with([' ', '\t']) {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
let (name, value) = line.split_once(':').ok_or(IntakeError::BadRequest)?;
|
||||||
|
let name = http::header::HeaderName::from_bytes(name.as_bytes())
|
||||||
|
.map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let value =
|
||||||
|
http::HeaderValue::from_str(value.trim()).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
if name == http::header::CONTENT_LENGTH {
|
||||||
|
if content_length.is_some() {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
content_length = Some(
|
||||||
|
value
|
||||||
|
.to_str()
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.parse::<usize>().ok())
|
||||||
|
.ok_or(IntakeError::BadRequest)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if name == http::header::TRANSFER_ENCODING {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
headers.push((name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ParsedRequestHead {
|
||||||
|
method,
|
||||||
|
target: target.to_owned(),
|
||||||
|
headers,
|
||||||
|
content_length: content_length.unwrap_or(0),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_with_deadline(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
buffer: &mut [u8],
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<usize, IntakeError> {
|
||||||
|
let remaining = deadline
|
||||||
|
.checked_duration_since(Instant::now())
|
||||||
|
.ok_or(IntakeError::Timeout)?;
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(remaining.max(Duration::from_millis(1))))
|
||||||
|
.map_err(|_| IntakeError::Socket)?;
|
||||||
|
stream.read(buffer).map_err(|error| match error.kind() {
|
||||||
|
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => IntakeError::Timeout,
|
||||||
|
_ => IntakeError::Socket,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload_too_large_response(service: &WipFsServer, target: &str) -> Response<Vec<u8>> {
|
||||||
|
let route = service.route(target.split('?').next().unwrap_or_default());
|
||||||
|
route.map_or_else(
|
||||||
|
|| empty_response(StatusCode::PAYLOAD_TOO_LARGE),
|
||||||
|
|route| {
|
||||||
|
if route == Route::Batch {
|
||||||
|
service.batch_top_error(
|
||||||
|
&resource_error(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
service.protocol_error(
|
||||||
|
interaction(route),
|
||||||
|
&resource_error(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_http_response(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
response: &Response<Vec<u8>>,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<(), std::io::Error> {
|
||||||
|
let mut encoded = Vec::new();
|
||||||
|
write!(
|
||||||
|
encoded,
|
||||||
|
"HTTP/1.1 {} {}\r\n",
|
||||||
|
response.status().as_u16(),
|
||||||
|
response.status().canonical_reason().unwrap_or("")
|
||||||
|
)?;
|
||||||
|
for (name, value) in response.headers() {
|
||||||
|
if name == http::header::CONTENT_LENGTH
|
||||||
|
|| name == http::header::CONNECTION
|
||||||
|
|| name == http::header::TRANSFER_ENCODING
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
encoded.extend_from_slice(name.as_str().as_bytes());
|
||||||
|
encoded.extend_from_slice(b": ");
|
||||||
|
encoded.extend_from_slice(value.as_bytes());
|
||||||
|
encoded.extend_from_slice(b"\r\n");
|
||||||
|
}
|
||||||
|
write!(
|
||||||
|
encoded,
|
||||||
|
"Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||||
|
response.body().len()
|
||||||
|
)?;
|
||||||
|
encoded.extend_from_slice(response.body());
|
||||||
|
write_all_with_deadline(stream, &encoded, deadline)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_all_with_deadline(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
mut bytes: &[u8],
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<(), std::io::Error> {
|
||||||
|
while !bytes.is_empty() {
|
||||||
|
let remaining = deadline
|
||||||
|
.checked_duration_since(Instant::now())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
std::io::Error::new(std::io::ErrorKind::TimedOut, "request timed out")
|
||||||
|
})?;
|
||||||
|
stream.set_write_timeout(Some(remaining.max(Duration::from_millis(1))))?;
|
||||||
|
match stream.write(bytes) {
|
||||||
|
Ok(0) => {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::WriteZero,
|
||||||
|
"socket closed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(count) => bytes = &bytes[count..],
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stream.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interaction(route: Route) -> ProtocolInteraction {
|
||||||
|
match route {
|
||||||
|
Route::Observe => ProtocolInteraction::Observe,
|
||||||
|
Route::FetchInterface => ProtocolInteraction::FetchInterface,
|
||||||
|
Route::CallOperation => ProtocolInteraction::CallOperation,
|
||||||
|
Route::Batch => ProtocolInteraction::Observe,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resource_error() -> ProtocolError {
|
||||||
|
ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "configured resource limit exceeded".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal_error() -> ProtocolError {
|
||||||
|
ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "filesystem server failed".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.body(Vec::new())
|
||||||
|
.expect("static status builds an HTTP response")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure while validating, opening, or binding the server.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ServerBuildError {
|
||||||
|
/// Configuration is unsafe or unbounded.
|
||||||
|
Config(ConfigError),
|
||||||
|
/// The root capability could not be opened.
|
||||||
|
Io(std::io::Error),
|
||||||
|
/// The listener could not be bound.
|
||||||
|
Listener(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ServerBuildError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Config(error) => write!(formatter, "invalid server configuration: {error}"),
|
||||||
|
Self::Io(error) => write!(formatter, "filesystem root could not be opened: {error}"),
|
||||||
|
Self::Listener(error) => write!(formatter, "HTTP listener could not be bound: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ServerBuildError {
|
||||||
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::Config(error) => Some(error),
|
||||||
|
Self::Io(error) => Some(error),
|
||||||
|
Self::Listener(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ConfigError> for ServerBuildError {
|
||||||
|
fn from(value: ConfigError) -> Self {
|
||||||
|
Self::Config(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for ServerBuildError {
|
||||||
|
fn from(value: std::io::Error) -> Self {
|
||||||
|
Self::Io(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpStream};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
|
use wip_http::{
|
||||||
|
BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse, BatchSuccess, DecodedResponse,
|
||||||
|
Endpoint, JSON_CONTENT_TYPE, Limits, Route, decode_batch_request, decode_batch_response,
|
||||||
|
decode_call_operation_response, decode_fetch_interface_response, decode_observe_response,
|
||||||
|
encode_batch_request, encode_call_operation_request, encode_fetch_interface_request,
|
||||||
|
encode_observe_request,
|
||||||
|
};
|
||||||
|
use wip_protocol::{
|
||||||
|
CallOperationRequest, FetchInterfaceRequest, InterfaceTarget, ObserveRequest,
|
||||||
|
ProtocolErrorCode, Target, Value,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_listener_serves_three_core_interactions_batch_and_write() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
|
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
||||||
|
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.access = AccessMode::ReadWrite;
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
|
||||||
|
.expect("client endpoint");
|
||||||
|
|
||||||
|
let file_request = ObserveRequest {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
depth: 0,
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_observe_request(&endpoint, &file_request, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
let file = success(
|
||||||
|
decode_observe_response(&file_request, &response, limits).expect("decode observation"),
|
||||||
|
)
|
||||||
|
.object;
|
||||||
|
assert_eq!(file.name, "hello.txt");
|
||||||
|
assert_eq!(file.interfaces.len(), 2);
|
||||||
|
assert!(file.validator.is_some());
|
||||||
|
|
||||||
|
let tree_request = ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 1,
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_observe_request(&endpoint, &tree_request, limits).expect("encode tree"),
|
||||||
|
);
|
||||||
|
let tree =
|
||||||
|
success(decode_observe_response(&tree_request, &response, limits).expect("decode tree"));
|
||||||
|
assert_eq!(
|
||||||
|
tree.children
|
||||||
|
.as_ref()
|
||||||
|
.expect("root children observed")
|
||||||
|
.len(),
|
||||||
|
2
|
||||||
|
);
|
||||||
|
|
||||||
|
let read_interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[0].clone(),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_interface_request(&endpoint, &read_interface_request, limits)
|
||||||
|
.expect("encode interface fetch"),
|
||||||
|
);
|
||||||
|
let read_interface = success(
|
||||||
|
decode_fetch_interface_response(&read_interface_request, &response, limits)
|
||||||
|
.expect("decode interface"),
|
||||||
|
);
|
||||||
|
assert_eq!(read_interface.descriptor.operations[0].name, "read");
|
||||||
|
|
||||||
|
let read_request = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
validator: file.validator.clone(),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[0].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "read".into(),
|
||||||
|
arguments: BTreeMap::from([
|
||||||
|
("offset".into(), Value::Integer(6)),
|
||||||
|
("length".into(), Value::Integer(5)),
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_call_operation_request(&endpoint, &read_request, &read_interface.descriptor, limits)
|
||||||
|
.expect("encode read call"),
|
||||||
|
);
|
||||||
|
let read = success(
|
||||||
|
decode_call_operation_response(
|
||||||
|
&read_request,
|
||||||
|
&read_interface.descriptor,
|
||||||
|
&response,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("decode read call"),
|
||||||
|
);
|
||||||
|
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
||||||
|
|
||||||
|
let batch_request = BatchRequest {
|
||||||
|
requests: vec![
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "root".into(),
|
||||||
|
request: BatchRequestKind::Observe(ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 0,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "tree".into(),
|
||||||
|
request: BatchRequestKind::Observe(ObserveRequest {
|
||||||
|
path: "/nested".into(),
|
||||||
|
depth: 1,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(read_interface_request.clone()),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_batch_request(&endpoint, &batch_request, limits).expect("encode batch"),
|
||||||
|
);
|
||||||
|
let batch =
|
||||||
|
success(decode_batch_response(&batch_request, &response, limits).expect("decode batch"));
|
||||||
|
assert_batch_successes(&batch);
|
||||||
|
|
||||||
|
let write_interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[1].clone(),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_interface_request(&endpoint, &write_interface_request, limits)
|
||||||
|
.expect("encode write interface fetch"),
|
||||||
|
);
|
||||||
|
let write_interface = success(
|
||||||
|
decode_fetch_interface_response(&write_interface_request, &response, limits)
|
||||||
|
.expect("decode write interface"),
|
||||||
|
);
|
||||||
|
let write_request = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
validator: file.validator,
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[1].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "replace".into(),
|
||||||
|
arguments: BTreeMap::from([("contents".into(), Value::Bytes(b"updated".to_vec()))]),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_call_operation_request(
|
||||||
|
&endpoint,
|
||||||
|
&write_request,
|
||||||
|
&write_interface.descriptor,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("encode write call"),
|
||||||
|
);
|
||||||
|
let write = success(
|
||||||
|
decode_call_operation_response(
|
||||||
|
&write_request,
|
||||||
|
&write_interface.descriptor,
|
||||||
|
&response,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("decode write call"),
|
||||||
|
);
|
||||||
|
assert!(write.validator.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("read updated file"),
|
||||||
|
b"updated"
|
||||||
|
);
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.max_concurrent_requests = 1;
|
||||||
|
config.limits.request_timeout = Duration::from_millis(200);
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut stalled = TcpStream::connect(address).expect("connect stalled client");
|
||||||
|
stalled
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.expect("set stalled read timeout");
|
||||||
|
write!(
|
||||||
|
stalled,
|
||||||
|
"POST /wip/v1/observe HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nAccept: application/json\r\nContent-Length: 100\r\n\r\n{{"
|
||||||
|
)
|
||||||
|
.expect("write partial request");
|
||||||
|
stalled.flush().expect("flush partial request");
|
||||||
|
thread::sleep(Duration::from_millis(25));
|
||||||
|
|
||||||
|
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
|
||||||
|
.expect("client endpoint");
|
||||||
|
let observe = ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 0,
|
||||||
|
};
|
||||||
|
let started = Instant::now();
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_observe_request(&endpoint, &observe, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
let _root =
|
||||||
|
success(decode_observe_response(&observe, &response, limits).expect("decode observation"));
|
||||||
|
assert!(
|
||||||
|
started.elapsed() < Duration::from_secs(1),
|
||||||
|
"the valid request remained starved after the intake deadline"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut byte = [0_u8; 1];
|
||||||
|
match stalled.read(&mut byte) {
|
||||||
|
Ok(0) => {}
|
||||||
|
Err(error)
|
||||||
|
if matches!(
|
||||||
|
error.kind(),
|
||||||
|
std::io::ErrorKind::ConnectionReset
|
||||||
|
| std::io::ErrorKind::ConnectionAborted
|
||||||
|
| std::io::ErrorKind::BrokenPipe
|
||||||
|
) => {}
|
||||||
|
outcome => panic!("stalled connection was not closed after its deadline: {outcome:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_keeps_known_malformed_arguments_item_local() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
let body = br#"{"requests":[{"id":"ok","method":"observe","arguments":{"path":"/","depth":0}},{"id":"bad","method":"observe","arguments":{"path":"/","depth":"bad"}}]}"#;
|
||||||
|
let logical = decode_batch_request(body, limits).expect("decode item-local invalid request");
|
||||||
|
assert!(matches!(
|
||||||
|
logical.requests[1].request,
|
||||||
|
BatchRequestKind::Invalid { .. }
|
||||||
|
));
|
||||||
|
let request = http::Request::builder()
|
||||||
|
.method(http::Method::POST)
|
||||||
|
.uri(endpoint.route(Route::Batch).as_str())
|
||||||
|
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(http::header::ACCEPT, "application/json")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.expect("build request");
|
||||||
|
let response = server.handle_http(request);
|
||||||
|
let batch = success(
|
||||||
|
decode_batch_response(&logical, &response, limits).expect("decode mixed batch response"),
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[0].outcome,
|
||||||
|
Ok(BatchSuccess::Observe(_))
|
||||||
|
));
|
||||||
|
assert!(batch.responses[1].outcome.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn call_argument_decoding_does_not_mask_missing_target() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
||||||
|
let request = http::Request::builder()
|
||||||
|
.method(http::Method::POST)
|
||||||
|
.uri(endpoint.route(Route::CallOperation).as_str())
|
||||||
|
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(http::header::ACCEPT, "application/json")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.expect("build request");
|
||||||
|
let response = server.handle_http(request);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(response.body())
|
||||||
|
.expect("UTF-8 error")
|
||||||
|
.contains("\"not_found\"")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn backend_invalid_unicode_path_is_not_found_not_internal() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
let request = ObserveRequest {
|
||||||
|
path: "/bad\0name".into(),
|
||||||
|
depth: 0,
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_observe_request(&endpoint, &request, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
match decode_observe_response(&request, &response, limits).expect("decode missing response") {
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => {
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::NotFound);
|
||||||
|
}
|
||||||
|
DecodedResponse::Success(_) => panic!("backend-invalid path must not resolve"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn read_response_size_failure_preserves_non_commit_guarantee() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(4_096, 1_024, 64, 64).expect("wire limits");
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
|
||||||
|
let observe_request = ObserveRequest {
|
||||||
|
path: "/large".into(),
|
||||||
|
depth: 0,
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_observe_request(&endpoint, &observe_request, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
let file = success(
|
||||||
|
decode_observe_response(&observe_request, &response, limits).expect("decode observation"),
|
||||||
|
)
|
||||||
|
.object;
|
||||||
|
let interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[0].clone(),
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_fetch_interface_request(&endpoint, &interface_request, limits)
|
||||||
|
.expect("encode interface fetch"),
|
||||||
|
);
|
||||||
|
let interface = success(
|
||||||
|
decode_fetch_interface_response(&interface_request, &response, limits)
|
||||||
|
.expect("decode interface"),
|
||||||
|
);
|
||||||
|
let call = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/large".into(),
|
||||||
|
validator: file.validator,
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[0].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "read".into(),
|
||||||
|
arguments: BTreeMap::from([("length".into(), Value::Integer(1_500))]),
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
||||||
|
.expect("encode read call"),
|
||||||
|
);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
match decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
||||||
|
.expect("decode resource failure")
|
||||||
|
{
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => {
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::ResourceLimitExceeded);
|
||||||
|
}
|
||||||
|
DecodedResponse::Success(_) => panic!("oversized read response must fail"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_batch_successes(batch: &BatchResponse) {
|
||||||
|
assert_eq!(batch.responses.len(), 3);
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[0].outcome,
|
||||||
|
Ok(BatchSuccess::Observe(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[1].outcome,
|
||||||
|
Ok(BatchSuccess::Observe(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[2].outcome,
|
||||||
|
Ok(BatchSuccess::FetchInterface(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn success<T>(response: DecodedResponse<T>) -> T {
|
||||||
|
match response {
|
||||||
|
DecodedResponse::Success(value) => value,
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => panic!("protocol failure: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
||||||
|
let mut stream = TcpStream::connect(address).expect("connect listener");
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.expect("set read timeout");
|
||||||
|
let path = request
|
||||||
|
.uri()
|
||||||
|
.path_and_query()
|
||||||
|
.map_or("/", |value| value.as_str());
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"{} {} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n",
|
||||||
|
request.method(),
|
||||||
|
path
|
||||||
|
)
|
||||||
|
.expect("write request line");
|
||||||
|
for (name, value) in request.headers() {
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"{}: {}\r\n",
|
||||||
|
name,
|
||||||
|
value.to_str().expect("ASCII request header")
|
||||||
|
)
|
||||||
|
.expect("write header");
|
||||||
|
}
|
||||||
|
write!(stream, "Content-Length: {}\r\n\r\n", request.body().len())
|
||||||
|
.expect("write content length");
|
||||||
|
stream.write_all(request.body()).expect("write body");
|
||||||
|
stream.flush().expect("flush request");
|
||||||
|
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
stream.read_to_end(&mut raw).expect("read response");
|
||||||
|
let split = raw
|
||||||
|
.windows(4)
|
||||||
|
.position(|window| window == b"\r\n\r\n")
|
||||||
|
.expect("HTTP response header");
|
||||||
|
let head = std::str::from_utf8(&raw[..split]).expect("UTF-8 response head");
|
||||||
|
let mut lines = head.split("\r\n");
|
||||||
|
let status = lines
|
||||||
|
.next()
|
||||||
|
.and_then(|line| line.split_whitespace().nth(1))
|
||||||
|
.and_then(|status| status.parse::<u16>().ok())
|
||||||
|
.expect("response status");
|
||||||
|
let mut builder = http::Response::builder().status(status);
|
||||||
|
for line in lines {
|
||||||
|
let (name, value) = line.split_once(':').expect("response header");
|
||||||
|
builder = builder.header(name, value.trim());
|
||||||
|
}
|
||||||
|
builder
|
||||||
|
.body(raw[split + 4..].to_vec())
|
||||||
|
.expect("build response")
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-http"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Framework-independent standard WIP over HTTP v1 binding"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
|
http = "1"
|
||||||
|
serde = "1"
|
||||||
|
serde_json = "1"
|
||||||
|
url = "2"
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
@@ -0,0 +1,570 @@
|
|||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||||
|
use http::{Method, Request, Response, StatusCode};
|
||||||
|
use serde_json::{Map, Value as Json};
|
||||||
|
use wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, ObserveRequest,
|
||||||
|
ObserveResponse, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::response::{self, DecodedResponse};
|
||||||
|
use crate::{
|
||||||
|
BodyKind, ClientResponseError, CodecError, EncodeHttpError, Endpoint, InvalidResponseKind,
|
||||||
|
JSON_CONTENT_TYPE, Limits, ResourceLimitKind, Route, is_json_content_type, json,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A retrieval method accepted by the standard v1 batch endpoint.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum BatchMethod {
|
||||||
|
/// Observe one object and its indexable descendants.
|
||||||
|
Observe,
|
||||||
|
/// Fetch one interface descriptor.
|
||||||
|
FetchInterface,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BatchMethod {
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Observe => "observe",
|
||||||
|
Self::FetchInterface => "fetch_interface",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interaction(self) -> ProtocolInteraction {
|
||||||
|
match self {
|
||||||
|
Self::Observe => ProtocolInteraction::Observe,
|
||||||
|
Self::FetchInterface => ProtocolInteraction::FetchInterface,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One retrieval interaction accepted by the standard v1 batch endpoint.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum BatchRequestKind {
|
||||||
|
/// Observe one object and its indexable descendants.
|
||||||
|
Observe(ObserveRequest),
|
||||||
|
/// Fetch one interface descriptor.
|
||||||
|
FetchInterface(FetchInterfaceRequest),
|
||||||
|
/// A known method whose `arguments` are not a valid logical request.
|
||||||
|
Invalid {
|
||||||
|
/// Method that was successfully identified from the item envelope.
|
||||||
|
method: BatchMethod,
|
||||||
|
/// Item-local `invalid_request` to return without rejecting other items.
|
||||||
|
error: ProtocolError,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BatchRequestKind {
|
||||||
|
fn interaction(&self) -> ProtocolInteraction {
|
||||||
|
match self {
|
||||||
|
Self::Observe(_) => ProtocolInteraction::Observe,
|
||||||
|
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
|
||||||
|
Self::Invalid { method, .. } => method.interaction(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One uniquely identified batch subrequest.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct BatchRequestItem {
|
||||||
|
/// Identifier used only to correlate the corresponding subresponse.
|
||||||
|
pub id: String,
|
||||||
|
/// Retrieval interaction and arguments.
|
||||||
|
pub request: BatchRequestKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A standard v1 batch request.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct BatchRequest {
|
||||||
|
/// Independent subrequests. Identifiers must be unique.
|
||||||
|
pub requests: Vec<BatchRequestItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Successful result of one batch item.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum BatchSuccess {
|
||||||
|
/// Successful `observe` result.
|
||||||
|
Observe(ObserveResponse),
|
||||||
|
/// Successful `fetch_interface` result.
|
||||||
|
FetchInterface(FetchInterfaceResponse),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One batch subresponse, correlated by `id` rather than array position.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct BatchResponseItem {
|
||||||
|
/// Identifier copied from its subrequest.
|
||||||
|
pub id: String,
|
||||||
|
/// Direct interaction result or canonical item-local protocol failure.
|
||||||
|
pub outcome: Result<BatchSuccess, ProtocolError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A valid standard v1 batch response.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct BatchResponse {
|
||||||
|
/// Exactly one response for each requested identifier, in any order.
|
||||||
|
pub responses: Vec<BatchResponseItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Result<(), CodecError> {
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut count = 0;
|
||||||
|
for id in ids {
|
||||||
|
count += 1;
|
||||||
|
if !seen.insert(id) {
|
||||||
|
return Err(CodecError::DuplicateBatchId { id: id.into() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count > maximum {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: count,
|
||||||
|
maximum,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
|
||||||
|
let (method, arguments) = match &item.request {
|
||||||
|
BatchRequestKind::Observe(value) => ("observe", json::observe_request_to_json(value)),
|
||||||
|
BatchRequestKind::FetchInterface(value) => (
|
||||||
|
"fetch_interface",
|
||||||
|
json::fetch_interface_request_to_json(value),
|
||||||
|
),
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "requests".into(),
|
||||||
|
reason: "item-local invalid requests cannot be encoded as client requests".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(serde_json::json!({"id": item.id, "method": method, "arguments": arguments}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, CodecError> {
|
||||||
|
validate_ids(
|
||||||
|
request.requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
for item in &request.requests {
|
||||||
|
match &item.request {
|
||||||
|
BatchRequestKind::Observe(value) => value.validate()?,
|
||||||
|
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let requests = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(request_item_to_json)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
Ok(serde_json::json!({"requests": requests}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||||
|
let fields = exact_object(value, "batch", &["requests"])?;
|
||||||
|
let values = array(required(fields, "requests")?, "requests")?;
|
||||||
|
if values.len() > limits.max_batch_items {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: values.len(),
|
||||||
|
maximum: limits.max_batch_items,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut requests = Vec::with_capacity(values.len());
|
||||||
|
for (index, value) in values.iter().enumerate() {
|
||||||
|
let field = format!("requests[{index}]");
|
||||||
|
let fields = exact_object(value, &field, &["id", "method", "arguments"])?;
|
||||||
|
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||||
|
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
|
||||||
|
let arguments = required(fields, "arguments")?;
|
||||||
|
let method = match method_name.as_str() {
|
||||||
|
"observe" => BatchMethod::Observe,
|
||||||
|
"fetch_interface" => BatchMethod::FetchInterface,
|
||||||
|
_ => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: format!("{field}.method"),
|
||||||
|
reason: "batch supports only observe and fetch_interface".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let decoded = match method {
|
||||||
|
BatchMethod::Observe => {
|
||||||
|
json::observe_request_from_json(arguments).map(BatchRequestKind::Observe)
|
||||||
|
}
|
||||||
|
BatchMethod::FetchInterface => json::fetch_interface_request_from_json(arguments)
|
||||||
|
.map(BatchRequestKind::FetchInterface),
|
||||||
|
};
|
||||||
|
let request = decoded.unwrap_or_else(|error| BatchRequestKind::Invalid {
|
||||||
|
method,
|
||||||
|
error: ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: format!("invalid {} arguments: {error}", method.name()),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
requests.push(BatchRequestItem { id, request });
|
||||||
|
}
|
||||||
|
validate_ids(
|
||||||
|
requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
Ok(BatchRequest { requests })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a batch request using `POST v1/batch`.
|
||||||
|
pub fn encode_batch_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &BatchRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(&request_to_json(value, limits)?, BodyKind::Request, limits)?;
|
||||||
|
Ok(Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri(endpoint.route(Route::Batch).as_str())
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(ACCEPT, "application/json")
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and validates a batch request body.
|
||||||
|
pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
request_from_json(&value, limits)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn success_to_json(success: &BatchSuccess) -> Json {
|
||||||
|
match success {
|
||||||
|
BatchSuccess::Observe(value) => json::observe_response_to_json(value),
|
||||||
|
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response_to_json(
|
||||||
|
request: &BatchRequest,
|
||||||
|
response: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Json, CodecError> {
|
||||||
|
correlate(request, response, limits)?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"responses": response.responses.iter().map(|item| {
|
||||||
|
let mut fields = Map::new();
|
||||||
|
fields.insert("id".into(), Json::String(item.id.clone()));
|
||||||
|
match &item.outcome {
|
||||||
|
Ok(success) => { fields.insert("result".into(), success_to_json(success)); }
|
||||||
|
Err(error) => { fields.insert("error".into(), response::item_error_to_json(error)); }
|
||||||
|
}
|
||||||
|
Json::Object(fields)
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn correlate(
|
||||||
|
request: &BatchRequest,
|
||||||
|
response: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<(), CodecError> {
|
||||||
|
validate_ids(
|
||||||
|
request.requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
validate_ids(
|
||||||
|
response.responses.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(|item| (item.id.as_str(), &item.request))
|
||||||
|
.collect();
|
||||||
|
for item in &response.responses {
|
||||||
|
let Some(kind) = requested.get(item.id.as_str()) else {
|
||||||
|
return Err(CodecError::UnexpectedBatchId {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
match (&item.outcome, *kind) {
|
||||||
|
(Ok(BatchSuccess::Observe(value)), BatchRequestKind::Observe(request)) => {
|
||||||
|
request.validate_response(value)?;
|
||||||
|
}
|
||||||
|
(
|
||||||
|
Ok(BatchSuccess::FetchInterface(value)),
|
||||||
|
BatchRequestKind::FetchInterface(request),
|
||||||
|
) => {
|
||||||
|
value.validate_for(request)?;
|
||||||
|
}
|
||||||
|
(
|
||||||
|
Err(error),
|
||||||
|
BatchRequestKind::Invalid {
|
||||||
|
error: expected, ..
|
||||||
|
},
|
||||||
|
) if error == expected => {}
|
||||||
|
(Err(error), kind)
|
||||||
|
if !matches!(kind, BatchRequestKind::Invalid { .. })
|
||||||
|
&& error.code.is_allowed_for(kind.interaction()) => {}
|
||||||
|
_ => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for item in &request.requests {
|
||||||
|
if !response.responses.iter().any(|other| other.id == item.id) {
|
||||||
|
return Err(CodecError::MissingBatchId {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a valid batch response. Item failures remain inside HTTP 200.
|
||||||
|
pub fn encode_batch_response(
|
||||||
|
request: &BatchRequest,
|
||||||
|
value: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(
|
||||||
|
&response_to_json(request, value, limits)?,
|
||||||
|
BodyKind::Response,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a top-level batch-envelope failure.
|
||||||
|
///
|
||||||
|
/// Item-local failures belong in [`BatchResponseItem`]. Only failures that can
|
||||||
|
/// reject the batch envelope before item execution are accepted here. A
|
||||||
|
/// resource-limit failure defaults to the logical-limit status; use
|
||||||
|
/// [`encode_batch_resource_limit_error_response`] when the concrete class is
|
||||||
|
/// known.
|
||||||
|
pub fn encode_batch_error_response(
|
||||||
|
error: &ProtocolError,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if !matches!(
|
||||||
|
error.code,
|
||||||
|
ProtocolErrorCode::InvalidRequest
|
||||||
|
| ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
| ProtocolErrorCode::Internal
|
||||||
|
) {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "code is not valid for a top-level batch failure".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(response::status_for_error(error.code))
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a class-specific top-level batch `resource_limit_exceeded` failure.
|
||||||
|
pub fn encode_batch_resource_limit_error_response(
|
||||||
|
error: &ProtocolError,
|
||||||
|
kind: ResourceLimitKind,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if error.code != ProtocolErrorCode::ResourceLimitExceeded {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(response::status_for_resource_limit(kind))
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response_from_json(
|
||||||
|
value: &Json,
|
||||||
|
request: &BatchRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<BatchResponse, CodecError> {
|
||||||
|
let fields = exact_object(value, "batch", &["responses"])?;
|
||||||
|
let values = array(required(fields, "responses")?, "responses")?;
|
||||||
|
if values.len() > limits.max_batch_items {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: values.len(),
|
||||||
|
maximum: limits.max_batch_items,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(|item| (item.id.as_str(), &item.request))
|
||||||
|
.collect();
|
||||||
|
let mut responses = Vec::with_capacity(values.len());
|
||||||
|
for (index, value) in values.iter().enumerate() {
|
||||||
|
let field = format!("responses[{index}]");
|
||||||
|
let fields = object(value, &field)?;
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !["id", "result", "error"].contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{field}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||||
|
let Some(kind) = requested.get(id.as_str()) else {
|
||||||
|
return Err(CodecError::UnexpectedBatchId { id });
|
||||||
|
};
|
||||||
|
let outcome = match (fields.get("result"), fields.get("error")) {
|
||||||
|
(Some(_), Some(_)) | (None, None) => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field,
|
||||||
|
reason: "batch item must contain exactly one of result or error".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(None, Some(error)) => {
|
||||||
|
let error = response::item_error_from_json(error)?;
|
||||||
|
match kind {
|
||||||
|
BatchRequestKind::Invalid {
|
||||||
|
error: expected, ..
|
||||||
|
} if error == *expected => {}
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch { id });
|
||||||
|
}
|
||||||
|
kind if error.code.is_allowed_for(kind.interaction()) => {}
|
||||||
|
_ => return Err(CodecError::BatchInteractionMismatch { id }),
|
||||||
|
}
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
(Some(result), None) => Ok(match kind {
|
||||||
|
BatchRequestKind::Observe(request) => {
|
||||||
|
let value = json::observe_response_from_json(result)?;
|
||||||
|
request.validate_response(&value)?;
|
||||||
|
BatchSuccess::Observe(value)
|
||||||
|
}
|
||||||
|
BatchRequestKind::FetchInterface(request) => {
|
||||||
|
let value = json::fetch_interface_response_from_json(result)?;
|
||||||
|
value.validate_for(request)?;
|
||||||
|
BatchSuccess::FetchInterface(value)
|
||||||
|
}
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch { id });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
responses.push(BatchResponseItem { id, outcome });
|
||||||
|
}
|
||||||
|
let response = BatchResponse { responses };
|
||||||
|
correlate(request, &response, limits)?;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a batch response, including item-local failures within HTTP 200.
|
||||||
|
pub fn decode_batch_response<B: AsRef<[u8]>>(
|
||||||
|
request: &BatchRequest,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<BatchResponse>, ClientResponseError> {
|
||||||
|
let valid_content_type = value
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if !valid_content_type {
|
||||||
|
if value.status().is_success() {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidBatch,
|
||||||
|
"missing or non-UTF-8 application/json Content-Type",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return Err(response::transport_failure(value.status()));
|
||||||
|
}
|
||||||
|
let decoded = response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
limits,
|
||||||
|
|json| response_from_json(json, request, limits),
|
||||||
|
)
|
||||||
|
.map_err(|error| match error {
|
||||||
|
ClientResponseError::InvalidResponse { detail, .. } => {
|
||||||
|
ClientResponseError::invalid(InvalidResponseKind::InvalidBatch, detail)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
})?;
|
||||||
|
if let DecodedResponse::ProtocolFailure { error, .. } = &decoded
|
||||||
|
&& !matches!(
|
||||||
|
error.code,
|
||||||
|
ProtocolErrorCode::InvalidRequest
|
||||||
|
| ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
| ProtocolErrorCode::Internal
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidBatch,
|
||||||
|
"protocol code is not valid for a top-level batch failure",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let DecodedResponse::Success(success) = &decoded {
|
||||||
|
for item in &success.responses {
|
||||||
|
if let Ok(BatchSuccess::FetchInterface(interface)) = &item.outcome
|
||||||
|
&& interface.descriptor.format != INTERFACE_FORMAT_V1
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||||
|
format: interface.descriptor.format.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object<'a>(value: &'a Json, field: &str) -> Result<&'a Map<String, Json>, CodecError> {
|
||||||
|
value.as_object().ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected object".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exact_object<'a>(
|
||||||
|
value: &'a Json,
|
||||||
|
field: &str,
|
||||||
|
allowed: &[&str],
|
||||||
|
) -> Result<&'a Map<String, Json>, CodecError> {
|
||||||
|
let fields = object(value, field)?;
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !allowed.contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{field}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a Json, CodecError> {
|
||||||
|
fields
|
||||||
|
.get(name)
|
||||||
|
.ok_or_else(|| CodecError::MissingField { field: name.into() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn string(value: &Json, field: &str) -> Result<String, CodecError> {
|
||||||
|
value
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected string".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn array<'a>(value: &'a Json, field: &str) -> Result<&'a [Json], CodecError> {
|
||||||
|
value
|
||||||
|
.as_array()
|
||||||
|
.map(Vec::as_slice)
|
||||||
|
.ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected array".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,604 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||||
|
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
||||||
|
use wip_protocol::{
|
||||||
|
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
||||||
|
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, ObserveRequest, ObserveResponse,
|
||||||
|
ProtocolError, ProtocolInteraction, Target,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::response::{self, DecodedResponse};
|
||||||
|
use crate::{
|
||||||
|
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||||
|
Limits, ResourceLimitKind, Route, json,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
route: Route,
|
||||||
|
body: Vec<u8>,
|
||||||
|
) -> Result<Request<Vec<u8>>, http::Error> {
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri(endpoint.route(route).as_str())
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(ACCEPT, "application/json")
|
||||||
|
.body(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: StatusCode, body: Vec<u8>) -> Result<Response<Vec<u8>>, http::Error> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
||||||
|
let valid = response
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if valid {
|
||||||
|
Ok(())
|
||||||
|
} else if response.status().is_success() {
|
||||||
|
Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
"missing or non-UTF-8 application/json Content-Type",
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Err(response::transport_failure(response.status()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_utf8_charset(value: &str) -> bool {
|
||||||
|
let value = value.trim();
|
||||||
|
value.eq_ignore_ascii_case("utf-8")
|
||||||
|
|| value
|
||||||
|
.strip_prefix('"')
|
||||||
|
.and_then(|value| value.strip_suffix('"'))
|
||||||
|
.is_some_and(|value| value.eq_ignore_ascii_case("utf-8"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns whether a Content-Type value denotes UTF-8 `application/json`.
|
||||||
|
///
|
||||||
|
/// The charset parameter is optional because JSON exchanged by this binding is
|
||||||
|
/// always UTF-8; when present, its value must be `utf-8`. Other parameters are
|
||||||
|
/// rejected so intermediaries cannot silently select another representation.
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_json_content_type(value: &str) -> bool {
|
||||||
|
let mut parts = value.split(';');
|
||||||
|
if !parts
|
||||||
|
.next()
|
||||||
|
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut saw_charset = false;
|
||||||
|
for parameter in parts {
|
||||||
|
let Some((name, value)) = parameter.trim().split_once('=') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if !name.trim().eq_ignore_ascii_case("charset") || !is_utf8_charset(value) || saw_charset {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
saw_charset = true;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accepts_json(headers: &HeaderMap) -> bool {
|
||||||
|
let mut present = false;
|
||||||
|
let mut best_match: Option<((u8, u8), f32)> = None;
|
||||||
|
for value in headers.get_all(ACCEPT) {
|
||||||
|
present = true;
|
||||||
|
let Ok(value) = value.to_str() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for range in value.split(',') {
|
||||||
|
let mut parts = range.split(';');
|
||||||
|
let media_range = parts.next().unwrap_or_default().trim();
|
||||||
|
let mut quality = 1.0_f32;
|
||||||
|
let mut saw_quality = false;
|
||||||
|
let mut saw_charset = false;
|
||||||
|
let mut media_parameter_count = 0;
|
||||||
|
let mut valid = true;
|
||||||
|
for parameter in parts {
|
||||||
|
let parameter = parameter.trim();
|
||||||
|
let (name, value) = parameter
|
||||||
|
.split_once('=')
|
||||||
|
.map_or((parameter, None), |(name, value)| {
|
||||||
|
(name.trim(), Some(value))
|
||||||
|
});
|
||||||
|
if name.is_empty() {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if saw_quality {
|
||||||
|
// Parameters after q are Accept extensions and do not
|
||||||
|
// constrain the selected representation.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if name.eq_ignore_ascii_case("q") {
|
||||||
|
let Some(value) = value else {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
saw_quality = true;
|
||||||
|
match value.trim().parse::<f32>() {
|
||||||
|
Ok(value) if (0.0..=1.0).contains(&value) => quality = value,
|
||||||
|
_ => {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let Some(value) = value else {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
if !name.eq_ignore_ascii_case("charset")
|
||||||
|
|| !is_utf8_charset(value)
|
||||||
|
|| saw_charset
|
||||||
|
{
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
saw_charset = true;
|
||||||
|
media_parameter_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let media_specificity = if media_range.eq_ignore_ascii_case("application/json") {
|
||||||
|
Some(2)
|
||||||
|
} else if media_range.eq_ignore_ascii_case("application/*") {
|
||||||
|
Some(1)
|
||||||
|
} else if media_range == "*/*" {
|
||||||
|
Some(0)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if valid && let Some(media_specificity) = media_specificity {
|
||||||
|
let specificity = (media_specificity, media_parameter_count);
|
||||||
|
match best_match {
|
||||||
|
Some((best_specificity, _)) if best_specificity > specificity => {}
|
||||||
|
Some((best_specificity, best_quality)) if best_specificity == specificity => {
|
||||||
|
best_match = Some((specificity, best_quality.max(quality)));
|
||||||
|
}
|
||||||
|
_ => best_match = Some((specificity, quality)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if present {
|
||||||
|
best_match.is_some_and(|(_, quality)| quality > 0.0)
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure while validating inbound HTTP request metadata.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum RequestMetadataError {
|
||||||
|
/// The method or route does not match the selected WIP interaction.
|
||||||
|
InvalidRequest(CodecError),
|
||||||
|
/// The request body does not use UTF-8 `application/json`.
|
||||||
|
UnsupportedMediaType,
|
||||||
|
/// The request's `Accept` metadata excludes `application/json`.
|
||||||
|
NotAcceptable,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestMetadataError {
|
||||||
|
/// Returns the HTTP status for this metadata failure.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||||
|
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for RequestMetadataError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(error) => error.fmt(formatter),
|
||||||
|
Self::UnsupportedMediaType => {
|
||||||
|
formatter.write_str("expected UTF-8 application/json Content-Type")
|
||||||
|
}
|
||||||
|
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for RequestMetadataError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(error) => Some(error),
|
||||||
|
Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||||
|
///
|
||||||
|
/// Both absolute-form and origin-form request URIs are accepted, but the path
|
||||||
|
/// must exactly equal the selected endpoint route and a query is forbidden.
|
||||||
|
/// Unsupported content negotiation is reported as a Transport Binding metadata
|
||||||
|
/// failure rather than a Core `invalid_request`.
|
||||||
|
pub fn validate_http_request<B>(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
route: Route,
|
||||||
|
value: &Request<B>,
|
||||||
|
) -> Result<(), RequestMetadataError> {
|
||||||
|
if value.method() != Method::POST {
|
||||||
|
return Err(RequestMetadataError::InvalidRequest(
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: "method".into(),
|
||||||
|
reason: "standard WIP routes require POST".into(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let expected = endpoint.route(route);
|
||||||
|
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||||
|
return Err(RequestMetadataError::InvalidRequest(
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: "route".into(),
|
||||||
|
reason: "request URI does not match the selected standard route".into(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let valid_content_type = value
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if !valid_content_type {
|
||||||
|
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||||
|
}
|
||||||
|
if !accepts_json(value.headers()) {
|
||||||
|
return Err(RequestMetadataError::NotAcceptable);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes an `observe` HTTP request.
|
||||||
|
pub fn encode_observe_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &ObserveRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
value.validate().map_err(CodecError::from)?;
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::observe_request_to_json(value),
|
||||||
|
BodyKind::Request,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(request(endpoint, Route::Observe, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes an `observe` request body.
|
||||||
|
pub fn decode_observe_request(body: &[u8], limits: Limits) -> Result<ObserveRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
json::observe_request_from_json(&value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a `fetch_interface` HTTP request.
|
||||||
|
pub fn encode_fetch_interface_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &FetchInterfaceRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::fetch_interface_request_to_json(value),
|
||||||
|
BodyKind::Request,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(request(endpoint, Route::FetchInterface, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a `fetch_interface` request body.
|
||||||
|
pub fn decode_fetch_interface_request(
|
||||||
|
body: &[u8],
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<FetchInterfaceRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
json::fetch_interface_request_from_json(&value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Descriptor-independent fields needed to resolve a `call_operation` request.
|
||||||
|
///
|
||||||
|
/// A Host decodes this metadata first, fixes the current interface descriptor,
|
||||||
|
/// then passes the same body and descriptor to [`decode_call_operation_request`].
|
||||||
|
/// This preserves canonical path/interface/operation lookup and error precedence
|
||||||
|
/// without treating unvalidated argument JSON as a logical [`wip_protocol::Value`].
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CallOperationMetadata {
|
||||||
|
/// Path and optional object-state precondition.
|
||||||
|
pub target: Target,
|
||||||
|
/// Interface reference and optional interface precondition.
|
||||||
|
pub interface: InterfaceTarget,
|
||||||
|
/// Operation name used to select a declaration.
|
||||||
|
pub operation: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CallOperationMetadata {
|
||||||
|
/// Decodes the descriptor-bound request and verifies that routing metadata
|
||||||
|
/// still matches the values used to resolve `descriptor`.
|
||||||
|
pub fn decode_request(
|
||||||
|
&self,
|
||||||
|
body: &[u8],
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationRequest, CodecError> {
|
||||||
|
let request = decode_call_operation_request(body, descriptor, limits)?;
|
||||||
|
if request.target != self.target
|
||||||
|
|| request.interface != self.interface
|
||||||
|
|| request.operation != self.operation
|
||||||
|
{
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "request".into(),
|
||||||
|
reason: "call metadata changed after descriptor resolution".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes descriptor-independent `call_operation` routing metadata.
|
||||||
|
pub fn decode_call_operation_metadata(
|
||||||
|
body: &[u8],
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationMetadata, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
let (target, interface, operation) = json::call_request_metadata_from_json(&value)?;
|
||||||
|
Ok(CallOperationMetadata {
|
||||||
|
target,
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a descriptor-bound `call_operation` HTTP request.
|
||||||
|
pub fn encode_call_operation_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let value = json::call_request_to_json(value, descriptor)?;
|
||||||
|
let body = json::serialize(&value, BodyKind::Request, limits)?;
|
||||||
|
Ok(request(endpoint, Route::CallOperation, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a descriptor-bound `call_operation` request body.
|
||||||
|
pub fn decode_call_operation_request(
|
||||||
|
body: &[u8],
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
json::call_request_from_json(&value, descriptor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `observe` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_observe_response(
|
||||||
|
request_value: &ObserveRequest,
|
||||||
|
value: &ObserveResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
request_value
|
||||||
|
.validate_response(value)
|
||||||
|
.map_err(CodecError::from)?;
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::observe_response_to_json(value),
|
||||||
|
BodyKind::Response,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(response(StatusCode::OK, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and classifies an `observe` client response.
|
||||||
|
pub fn decode_observe_response<B: AsRef<[u8]>>(
|
||||||
|
request_value: &ObserveRequest,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<ObserveResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
limits,
|
||||||
|
|json| {
|
||||||
|
let observation = json::observe_response_from_json(json)?;
|
||||||
|
request_value.validate_response(&observation)?;
|
||||||
|
Ok(observation)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `fetch_interface` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_fetch_interface_response(
|
||||||
|
request_value: &FetchInterfaceRequest,
|
||||||
|
value: &FetchInterfaceResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
value
|
||||||
|
.validate_for(request_value)
|
||||||
|
.map_err(CodecError::from)?;
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::fetch_interface_response_to_json(value),
|
||||||
|
BodyKind::Response,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(response(StatusCode::OK, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and classifies a `fetch_interface` client response.
|
||||||
|
pub fn decode_fetch_interface_response<B: AsRef<[u8]>>(
|
||||||
|
request_value: &FetchInterfaceRequest,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<FetchInterfaceResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
let decoded = response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::FetchInterface,
|
||||||
|
limits,
|
||||||
|
|json| {
|
||||||
|
let interface = json::fetch_interface_response_from_json(json)?;
|
||||||
|
interface.validate_for(request_value)?;
|
||||||
|
Ok(interface)
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
if let DecodedResponse::Success(success) = &decoded
|
||||||
|
&& success.descriptor.format != INTERFACE_FORMAT_V1
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||||
|
format: success.descriptor.format.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `call_operation` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_call_operation_response(
|
||||||
|
request_value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
value: &CallOperationResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let json = json::call_response_to_json(value, descriptor, &request_value.operation)?;
|
||||||
|
let body = json::serialize(&json, BodyKind::Response, limits)?;
|
||||||
|
Ok(response(StatusCode::OK, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and classifies a descriptor-bound `call_operation` client response.
|
||||||
|
pub fn decode_call_operation_response<B: AsRef<[u8]>>(
|
||||||
|
request_value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<CallOperationResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::CallOperation,
|
||||||
|
limits,
|
||||||
|
|json| json::call_response_from_json(json, descriptor, &request_value.operation),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_protocol_error(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
) -> Result<(), CodecError> {
|
||||||
|
if !error.code.is_allowed_for(interaction) {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: format!(
|
||||||
|
"code `{}` is not allowed for {interaction:?}",
|
||||||
|
response::error_code_name(error.code)
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_protocol_error_with_status(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
status: StatusCode,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
validate_protocol_error(interaction, error)?;
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(response(status, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a canonical Host error envelope using its standard HTTP status.
|
||||||
|
///
|
||||||
|
/// The code must be allowed for `interaction`. This API accepts only
|
||||||
|
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
||||||
|
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
||||||
|
/// error envelopes. Resource-limit errors use the logical-limit status; callers
|
||||||
|
/// that know the concrete limit class should use
|
||||||
|
/// [`encode_resource_limit_error_response`].
|
||||||
|
pub fn encode_protocol_error_response(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
encode_protocol_error_with_status(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
response::status_for_error(error.code),
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a `resource_limit_exceeded` envelope with its class-specific status.
|
||||||
|
pub fn encode_resource_limit_error_response(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
kind: ResourceLimitKind,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if error.code != wip_protocol::ProtocolErrorCode::ResourceLimitExceeded {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
encode_protocol_error_with_status(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
response::status_for_resource_limit(kind),
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure while building an outbound framework-neutral HTTP message.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EncodeHttpError {
|
||||||
|
/// JSON or protocol encoding failed.
|
||||||
|
Codec(CodecError),
|
||||||
|
/// The framework-neutral HTTP message builder rejected the URI or headers.
|
||||||
|
Http(http::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for EncodeHttpError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Codec(error) => error.fmt(formatter),
|
||||||
|
Self::Http(error) => error.fmt(formatter),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for EncodeHttpError {
|
||||||
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::Codec(error) => Some(error),
|
||||||
|
Self::Http(error) => Some(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CodecError> for EncodeHttpError {
|
||||||
|
fn from(value: CodecError) -> Self {
|
||||||
|
Self::Codec(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<http::Error> for EncodeHttpError {
|
||||||
|
fn from(value: http::Error) -> Self {
|
||||||
|
Self::Http(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// The media type emitted for every WIP request and every response with a body.
|
||||||
|
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
||||||
|
|
||||||
|
/// A fixed standard WIP over HTTP v1 route.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Route {
|
||||||
|
/// Observe one object and its indexable descendants.
|
||||||
|
Observe,
|
||||||
|
/// Fetch an interface descriptor.
|
||||||
|
FetchInterface,
|
||||||
|
/// Call one operation.
|
||||||
|
CallOperation,
|
||||||
|
/// Package independent retrieval interactions.
|
||||||
|
Batch,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Route {
|
||||||
|
/// Returns the RFC 3986 relative reference used below an endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn relative_reference(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Observe => "v1/observe",
|
||||||
|
Self::FetchInterface => "v1/fetch_interface",
|
||||||
|
Self::CallOperation => "v1/call_operation",
|
||||||
|
Self::Batch => "v1/batch",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A canonical absolute hierarchical base URL whose path always ends in `/`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Endpoint(Url);
|
||||||
|
|
||||||
|
impl Endpoint {
|
||||||
|
/// Parses and canonicalizes an endpoint.
|
||||||
|
///
|
||||||
|
/// The input must be an absolute hierarchical URL with a host and without a
|
||||||
|
/// query or fragment. Its path is an endpoint prefix, not a Worldspace path.
|
||||||
|
/// A trailing slash is appended when absent so RFC 3986 relative-reference
|
||||||
|
/// resolution preserves the final prefix segment. The supplied scheme is
|
||||||
|
/// preserved; scheme and transport security are deployment concerns.
|
||||||
|
pub fn parse(input: &str) -> Result<Self, EndpointError> {
|
||||||
|
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
|
||||||
|
if url.cannot_be_a_base() || url.host_str().is_none() {
|
||||||
|
return Err(EndpointError::NotAbsoluteBase);
|
||||||
|
}
|
||||||
|
if url.query().is_some() {
|
||||||
|
return Err(EndpointError::HasQuery);
|
||||||
|
}
|
||||||
|
if url.fragment().is_some() {
|
||||||
|
return Err(EndpointError::HasFragment);
|
||||||
|
}
|
||||||
|
if !url.path().ends_with('/') {
|
||||||
|
let path = format!("{}/", url.path());
|
||||||
|
url.set_path(&path);
|
||||||
|
}
|
||||||
|
Ok(Self(url))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical base URL.
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_url(&self) -> &Url {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves one fixed v1 route below this endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub fn route(&self, route: Route) -> Url {
|
||||||
|
self.0
|
||||||
|
.join(route.relative_reference())
|
||||||
|
.expect("fixed relative WIP routes are valid URL references")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recognizes an exact standard route below this endpoint.
|
||||||
|
///
|
||||||
|
/// Query strings, fragments, additional path segments, and Worldspace paths
|
||||||
|
/// are not route components and therefore never match.
|
||||||
|
#[must_use]
|
||||||
|
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
||||||
|
const ROUTES: [Route; 4] = [
|
||||||
|
Route::Observe,
|
||||||
|
Route::FetchInterface,
|
||||||
|
Route::CallOperation,
|
||||||
|
Route::Batch,
|
||||||
|
];
|
||||||
|
if candidate.query().is_some() || candidate.fragment().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
ROUTES
|
||||||
|
.into_iter()
|
||||||
|
.find(|route| self.route(*route) == *candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Endpoint {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
self.0.fmt(formatter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&str> for Endpoint {
|
||||||
|
type Error = EndpointError;
|
||||||
|
|
||||||
|
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||||
|
Self::parse(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why an endpoint is not a valid standard WIP over HTTP base.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EndpointError {
|
||||||
|
/// URL parsing failed.
|
||||||
|
InvalidUrl(url::ParseError),
|
||||||
|
/// The URL is not a hierarchical absolute URL with an authority.
|
||||||
|
NotAbsoluteBase,
|
||||||
|
/// A query component was supplied.
|
||||||
|
HasQuery,
|
||||||
|
/// A fragment component was supplied.
|
||||||
|
HasFragment,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for EndpointError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
|
||||||
|
Self::NotAbsoluteBase => {
|
||||||
|
formatter.write_str("WIP endpoint must be an absolute base URL")
|
||||||
|
}
|
||||||
|
Self::HasQuery => formatter.write_str("WIP endpoint must not contain a query"),
|
||||||
|
Self::HasFragment => formatter.write_str("WIP endpoint must not contain a fragment"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for EndpointError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidUrl(error) => Some(error),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
/// Caller-selected hard limits applied before or while decoding JSON.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Limits {
|
||||||
|
/// Largest accepted request body in bytes.
|
||||||
|
pub(crate) max_request_bytes: usize,
|
||||||
|
/// Largest accepted response body in bytes.
|
||||||
|
pub(crate) max_response_bytes: usize,
|
||||||
|
/// Largest accepted JSON container nesting depth.
|
||||||
|
pub(crate) max_nesting: usize,
|
||||||
|
/// Largest accepted number of batch items.
|
||||||
|
pub(crate) max_batch_items: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Limits {
|
||||||
|
/// Creates a nonzero limit set.
|
||||||
|
pub fn new(
|
||||||
|
max_request_bytes: usize,
|
||||||
|
max_response_bytes: usize,
|
||||||
|
max_nesting: usize,
|
||||||
|
max_batch_items: usize,
|
||||||
|
) -> Result<Self, LimitConfigurationError> {
|
||||||
|
if max_request_bytes == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroRequestBytes);
|
||||||
|
}
|
||||||
|
if max_response_bytes == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroResponseBytes);
|
||||||
|
}
|
||||||
|
if max_nesting == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroNesting);
|
||||||
|
}
|
||||||
|
if max_batch_items == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroBatchItems);
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
max_request_bytes,
|
||||||
|
max_response_bytes,
|
||||||
|
max_nesting,
|
||||||
|
max_batch_items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the request body byte limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_request_bytes(self) -> usize {
|
||||||
|
self.max_request_bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the response body byte limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_response_bytes(self) -> usize {
|
||||||
|
self.max_response_bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the JSON container nesting limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_nesting(self) -> usize {
|
||||||
|
self.max_nesting
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the batch item count limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_batch_items(self) -> usize {
|
||||||
|
self.max_batch_items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a [`Limits`] configuration is not bounded.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LimitConfigurationError {
|
||||||
|
/// Request-byte limit was zero.
|
||||||
|
ZeroRequestBytes,
|
||||||
|
/// Response-byte limit was zero.
|
||||||
|
ZeroResponseBytes,
|
||||||
|
/// Nesting limit was zero.
|
||||||
|
ZeroNesting,
|
||||||
|
/// Batch-item limit was zero.
|
||||||
|
ZeroBatchItems,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for LimitConfigurationError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter.write_str(match self {
|
||||||
|
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
||||||
|
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
||||||
|
Self::ZeroNesting => "nesting limit must be nonzero",
|
||||||
|
Self::ZeroBatchItems => "batch item limit must be nonzero",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for LimitConfigurationError {}
|
||||||
|
|
||||||
|
/// Whether a body is being decoded as a request or response.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum BodyKind {
|
||||||
|
/// An inbound server request.
|
||||||
|
Request,
|
||||||
|
/// An inbound client response.
|
||||||
|
Response,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The class of a resource limit exceeded by a wire representation.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ResourceLimitKind {
|
||||||
|
/// A request or response representation exceeded its byte-size limit.
|
||||||
|
RepresentationBytes,
|
||||||
|
/// A logical limit such as nesting depth, batch count, or collection size was exceeded.
|
||||||
|
Logical,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A malformed or locally disallowed wire representation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum CodecError {
|
||||||
|
/// The body exceeds its configured byte limit.
|
||||||
|
BodyTooLarge {
|
||||||
|
/// Actual body size.
|
||||||
|
actual: usize,
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// JSON syntax is invalid.
|
||||||
|
InvalidJson(serde_json::Error),
|
||||||
|
/// A JSON container exceeds the configured nesting depth.
|
||||||
|
NestingTooDeep {
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// A required field is absent.
|
||||||
|
MissingField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// An undeclared field is present.
|
||||||
|
UnknownField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// A field has an invalid JSON type or semantic representation.
|
||||||
|
InvalidField {
|
||||||
|
/// Field name or value location.
|
||||||
|
field: String,
|
||||||
|
/// Stable human-readable reason.
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
|
/// An optional field was represented by JSON null rather than omission.
|
||||||
|
NullOptionalField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// Base64 is not canonical RFC 4648 Section 4 encoding.
|
||||||
|
InvalidBase64 {
|
||||||
|
/// Field name or value location.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// Logical protocol validation rejected the decoded representation.
|
||||||
|
ProtocolValidation(wip_protocol::ValidationError),
|
||||||
|
/// The batch exceeds its configured item count.
|
||||||
|
TooManyBatchItems {
|
||||||
|
/// Actual item count.
|
||||||
|
actual: usize,
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// Batch item identifiers are not unique.
|
||||||
|
DuplicateBatchId {
|
||||||
|
/// Repeated identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A response contains a batch identifier that was not requested.
|
||||||
|
UnexpectedBatchId {
|
||||||
|
/// Unexpected identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A response omitted a requested batch identifier.
|
||||||
|
MissingBatchId {
|
||||||
|
/// Missing identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A batch item result does not match its requested interaction.
|
||||||
|
BatchInteractionMismatch {
|
||||||
|
/// Item identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CodecError {
|
||||||
|
/// Classifies this failure when it represents a canonical resource limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn resource_limit_kind(&self) -> Option<ResourceLimitKind> {
|
||||||
|
match self {
|
||||||
|
Self::BodyTooLarge { .. } => Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
Self::NestingTooDeep { .. } | Self::TooManyBatchItems { .. } => {
|
||||||
|
Some(ResourceLimitKind::Logical)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for CodecError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::BodyTooLarge { actual, maximum } => {
|
||||||
|
write!(formatter, "body has {actual} bytes; maximum is {maximum}")
|
||||||
|
}
|
||||||
|
Self::InvalidJson(error) => write!(formatter, "invalid JSON: {error}"),
|
||||||
|
Self::NestingTooDeep { maximum } => {
|
||||||
|
write!(formatter, "JSON nesting exceeds maximum {maximum}")
|
||||||
|
}
|
||||||
|
Self::MissingField { field } => write!(formatter, "missing field `{field}`"),
|
||||||
|
Self::UnknownField { field } => write!(formatter, "unknown field `{field}`"),
|
||||||
|
Self::InvalidField { field, reason } => {
|
||||||
|
write!(formatter, "invalid field `{field}`: {reason}")
|
||||||
|
}
|
||||||
|
Self::NullOptionalField { field } => {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"optional field `{field}` must be omitted instead of null"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Self::InvalidBase64 { field } => {
|
||||||
|
write!(formatter, "field `{field}` is not canonical base64")
|
||||||
|
}
|
||||||
|
Self::ProtocolValidation(error) => error.fmt(formatter),
|
||||||
|
Self::TooManyBatchItems { actual, maximum } => {
|
||||||
|
write!(formatter, "batch has {actual} items; maximum is {maximum}")
|
||||||
|
}
|
||||||
|
Self::DuplicateBatchId { id } => write!(formatter, "duplicate batch id `{id}`"),
|
||||||
|
Self::UnexpectedBatchId { id } => write!(formatter, "unexpected batch id `{id}`"),
|
||||||
|
Self::MissingBatchId { id } => write!(formatter, "missing batch id `{id}`"),
|
||||||
|
Self::BatchInteractionMismatch { id } => {
|
||||||
|
write!(formatter, "batch result does not match request `{id}`")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for CodecError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidJson(error) => Some(error),
|
||||||
|
Self::ProtocolValidation(error) => Some(error),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<wip_protocol::ValidationError> for CodecError {
|
||||||
|
fn from(value: wip_protocol::ValidationError) -> Self {
|
||||||
|
Self::ProtocolValidation(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
|||||||
|
//! Framework-independent standard WIP over HTTP v1 binding.
|
||||||
|
//!
|
||||||
|
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
||||||
|
//! success and error response handling, HTTP status mapping, descriptor-guided
|
||||||
|
//! operation-value conversion, and retrieval batching. It deliberately performs
|
||||||
|
//! no I/O and depends on no server framework, TLS implementation, filesystem
|
||||||
|
//! projection, client cache, or presentation layer. URL schemes, TLS,
|
||||||
|
//! certificates, authentication mechanisms, proxies, and caches are selected by
|
||||||
|
//! the HTTP implementation and deployment rather than by WIP conformance.
|
||||||
|
//!
|
||||||
|
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
||||||
|
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
||||||
|
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||||
|
//! use wip_protocol::ObserveRequest;
|
||||||
|
//!
|
||||||
|
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
||||||
|
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
|
||||||
|
//! let request = encode_observe_request(
|
||||||
|
//! &endpoint,
|
||||||
|
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
||||||
|
//! limits,
|
||||||
|
//! )?;
|
||||||
|
//! assert_eq!(request.uri(), "http://example.test/api/wip/v1/observe");
|
||||||
|
//! assert_eq!(request.method(), http::Method::POST);
|
||||||
|
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
mod batch;
|
||||||
|
mod codec;
|
||||||
|
mod endpoint;
|
||||||
|
mod error;
|
||||||
|
mod json;
|
||||||
|
mod response;
|
||||||
|
|
||||||
|
pub use batch::{
|
||||||
|
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
||||||
|
BatchResponseItem, BatchSuccess, decode_batch_request, decode_batch_response,
|
||||||
|
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
||||||
|
encode_batch_response,
|
||||||
|
};
|
||||||
|
pub use codec::{
|
||||||
|
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
||||||
|
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
||||||
|
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
||||||
|
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||||
|
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||||
|
encode_protocol_error_response, encode_resource_limit_error_response, is_json_content_type,
|
||||||
|
validate_http_request,
|
||||||
|
};
|
||||||
|
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||||
|
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
|
||||||
|
pub use response::{
|
||||||
|
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||||
|
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||||
|
status_for_resource_limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Framework-neutral HTTP types used by this binding's public API.
|
||||||
|
pub use http;
|
||||||
|
/// URL type used by [`Endpoint`].
|
||||||
|
pub use url;
|
||||||
|
/// Transport-independent logical protocol model used by this binding.
|
||||||
|
pub use wip_protocol;
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
use http::StatusCode;
|
||||||
|
use serde_json::{Map, Value as Json};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
|
use crate::{BodyKind, CodecError, Limits, ResourceLimitKind, json};
|
||||||
|
|
||||||
|
/// A successfully classified client response.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum DecodedResponse<T> {
|
||||||
|
/// A successful direct response body.
|
||||||
|
Success(T),
|
||||||
|
/// A canonical Host protocol failure.
|
||||||
|
ProtocolFailure {
|
||||||
|
/// The authoritative protocol error decoded from the envelope.
|
||||||
|
error: ProtocolError,
|
||||||
|
/// A diagnostic when the HTTP status differs from the canonical mapping.
|
||||||
|
status_mismatch: Option<StatusMismatch>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Diagnostic evidence that HTTP metadata disagrees with a valid error envelope.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct StatusMismatch {
|
||||||
|
/// Status received from the peer.
|
||||||
|
pub actual: StatusCode,
|
||||||
|
/// Canonical status for the envelope's protocol code.
|
||||||
|
pub expected: StatusCode,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Class of non-protocol HTTP failure returned without a valid WIP envelope.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TransportFailureKind {
|
||||||
|
/// HTTP 401, commonly emitted by authentication infrastructure.
|
||||||
|
AuthenticationRequired,
|
||||||
|
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
||||||
|
EndpointForbidden,
|
||||||
|
/// Another non-success HTTP response without a WIP error envelope.
|
||||||
|
HttpStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-success HTTP response that is not a valid WIP protocol failure.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct TransportBindingFailure {
|
||||||
|
/// HTTP status returned by the peer or intermediary.
|
||||||
|
pub status: StatusCode,
|
||||||
|
/// Coarse classification which does not invent a protocol error code.
|
||||||
|
pub kind: TransportFailureKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a response violates the WIP v1 response contract.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum InvalidResponseKind {
|
||||||
|
/// A 2xx response contained an error envelope.
|
||||||
|
ErrorEnvelopeOnSuccessStatus,
|
||||||
|
/// A non-2xx response contained a valid success body.
|
||||||
|
SuccessBodyOnErrorStatus,
|
||||||
|
/// A valid error envelope used a code forbidden for the interaction.
|
||||||
|
DisallowedProtocolCode,
|
||||||
|
/// A valid success body used a 2xx status other than canonical HTTP 200.
|
||||||
|
NonCanonicalSuccessStatus,
|
||||||
|
/// A 2xx body was malformed or semantically invalid.
|
||||||
|
InvalidSuccessBody,
|
||||||
|
/// A batch response did not correlate exactly with its request.
|
||||||
|
InvalidBatch,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A local failure while classifying or validating a peer response.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ClientResponseError {
|
||||||
|
/// The HTTP exchange failed outside the protocol envelope.
|
||||||
|
TransportBinding(TransportBindingFailure),
|
||||||
|
/// The peer supplied a contradictory or invalid WIP response.
|
||||||
|
InvalidResponse {
|
||||||
|
/// Stable response-failure category.
|
||||||
|
kind: InvalidResponseKind,
|
||||||
|
/// Bounded diagnostic from local decoding.
|
||||||
|
detail: String,
|
||||||
|
},
|
||||||
|
/// The descriptor is structurally valid but uses an unsupported format.
|
||||||
|
UnsupportedDescriptorFormat {
|
||||||
|
/// Format identifier received from the Host.
|
||||||
|
format: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientResponseError {
|
||||||
|
pub(crate) fn invalid(kind: InvalidResponseKind, detail: impl Into<String>) -> Self {
|
||||||
|
Self::InvalidResponse {
|
||||||
|
kind,
|
||||||
|
detail: detail.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ClientResponseError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::TransportBinding(failure) => write!(
|
||||||
|
formatter,
|
||||||
|
"transport binding failure ({:?}, HTTP {})",
|
||||||
|
failure.kind, failure.status
|
||||||
|
),
|
||||||
|
Self::InvalidResponse { kind, detail } => {
|
||||||
|
write!(formatter, "invalid WIP response ({kind:?}): {detail}")
|
||||||
|
}
|
||||||
|
Self::UnsupportedDescriptorFormat { format } => {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"unsupported interface descriptor format `{format}`"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ClientResponseError {}
|
||||||
|
|
||||||
|
/// Returns the canonical HTTP status for a wire-level protocol error.
|
||||||
|
///
|
||||||
|
/// [`ProtocolErrorCode::ResourceLimitExceeded`] defaults to the logical-limit
|
||||||
|
/// status. Use [`status_for_resource_limit`] when the concrete limit class is
|
||||||
|
/// known.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::InvalidRequest => StatusCode::BAD_REQUEST,
|
||||||
|
ProtocolErrorCode::NotFound | ProtocolErrorCode::InterfaceNotFound => StatusCode::NOT_FOUND,
|
||||||
|
ProtocolErrorCode::InterfaceMismatch => StatusCode::CONFLICT,
|
||||||
|
ProtocolErrorCode::OperationNotFound => StatusCode::NOT_FOUND,
|
||||||
|
ProtocolErrorCode::InvalidArguments => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ProtocolErrorCode::ValidatorRequired | ProtocolErrorCode::InterfaceValidatorRequired => {
|
||||||
|
StatusCode::PRECONDITION_REQUIRED
|
||||||
|
}
|
||||||
|
ProtocolErrorCode::ValidatorMismatch | ProtocolErrorCode::InterfaceValidatorMismatch => {
|
||||||
|
StatusCode::PRECONDITION_FAILED
|
||||||
|
}
|
||||||
|
ProtocolErrorCode::PermissionDenied => StatusCode::FORBIDDEN,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ProtocolErrorCode::Internal | ProtocolErrorCode::OperationOutcomeUnknown => {
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical HTTP status for a concrete resource-limit class.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status_for_resource_limit(kind: ResourceLimitKind) -> StatusCode {
|
||||||
|
match kind {
|
||||||
|
ResourceLimitKind::RepresentationBytes => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
ResourceLimitKind::Logical => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => {
|
||||||
|
status == StatusCode::PAYLOAD_TOO_LARGE || status == StatusCode::UNPROCESSABLE_ENTITY
|
||||||
|
}
|
||||||
|
_ => status == status_for_error(code),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the stable snake-case wire spelling of a protocol code.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn error_code_name(code: ProtocolErrorCode) -> &'static str {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::InvalidRequest => "invalid_request",
|
||||||
|
ProtocolErrorCode::NotFound => "not_found",
|
||||||
|
ProtocolErrorCode::InterfaceNotFound => "interface_not_found",
|
||||||
|
ProtocolErrorCode::InterfaceMismatch => "interface_mismatch",
|
||||||
|
ProtocolErrorCode::OperationNotFound => "operation_not_found",
|
||||||
|
ProtocolErrorCode::InvalidArguments => "invalid_arguments",
|
||||||
|
ProtocolErrorCode::ValidatorRequired => "validator_required",
|
||||||
|
ProtocolErrorCode::ValidatorMismatch => "validator_mismatch",
|
||||||
|
ProtocolErrorCode::InterfaceValidatorRequired => "interface_validator_required",
|
||||||
|
ProtocolErrorCode::InterfaceValidatorMismatch => "interface_validator_mismatch",
|
||||||
|
ProtocolErrorCode::PermissionDenied => "permission_denied",
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => "resource_limit_exceeded",
|
||||||
|
ProtocolErrorCode::Internal => "internal",
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown => "operation_outcome_unknown",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_code_from_name(name: &str) -> Option<ProtocolErrorCode> {
|
||||||
|
Some(match name {
|
||||||
|
"invalid_request" => ProtocolErrorCode::InvalidRequest,
|
||||||
|
"not_found" => ProtocolErrorCode::NotFound,
|
||||||
|
"interface_not_found" => ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
"interface_mismatch" => ProtocolErrorCode::InterfaceMismatch,
|
||||||
|
"operation_not_found" => ProtocolErrorCode::OperationNotFound,
|
||||||
|
"invalid_arguments" => ProtocolErrorCode::InvalidArguments,
|
||||||
|
"validator_required" => ProtocolErrorCode::ValidatorRequired,
|
||||||
|
"validator_mismatch" => ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
"interface_validator_required" => ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
|
"interface_validator_mismatch" => ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
|
"permission_denied" => ProtocolErrorCode::PermissionDenied,
|
||||||
|
"resource_limit_exceeded" => ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
"internal" => ProtocolErrorCode::Internal,
|
||||||
|
"operation_outcome_unknown" => ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn error_to_json(error: &ProtocolError) -> Json {
|
||||||
|
serde_json::json!({
|
||||||
|
"error": {
|
||||||
|
"code": error_code_name(error.code),
|
||||||
|
"message": error.message,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn item_error_to_json(error: &ProtocolError) -> Json {
|
||||||
|
serde_json::json!({
|
||||||
|
"code": error_code_name(error.code),
|
||||||
|
"message": error.message,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn item_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
||||||
|
let fields = value
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
||||||
|
exact(fields, &["code", "message"], "error")?;
|
||||||
|
let code_name = required_string(fields, "code")?;
|
||||||
|
let code = error_code_from_name(code_name)
|
||||||
|
.ok_or_else(|| invalid_field("error.code", "unknown protocol error code"))?;
|
||||||
|
let message = required_string(fields, "message")?.to_owned();
|
||||||
|
Ok(ProtocolError { code, message })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn envelope_error_from_json(value: &Json) -> Result<Option<ProtocolError>, CodecError> {
|
||||||
|
let Some(fields) = value.as_object() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if fields.len() != 1 || !fields.contains_key("error") {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
item_error_from_json(&fields["error"]).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !allowed.contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{parent}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name in allowed {
|
||||||
|
if !fields.contains_key(*name) {
|
||||||
|
return Err(CodecError::MissingField {
|
||||||
|
field: format!("{parent}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_string<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a str, CodecError> {
|
||||||
|
fields
|
||||||
|
.get(name)
|
||||||
|
.and_then(Json::as_str)
|
||||||
|
.ok_or_else(|| invalid_field(&format!("error.{name}"), "expected string"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_field(field: &str, reason: &str) -> CodecError {
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: reason.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn decode<T>(
|
||||||
|
status: StatusCode,
|
||||||
|
body: &[u8],
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
limits: Limits,
|
||||||
|
success: impl FnOnce(&Json) -> Result<T, CodecError>,
|
||||||
|
) -> Result<DecodedResponse<T>, ClientResponseError> {
|
||||||
|
let value = match json::parse(body, BodyKind::Response, limits) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) if !status.is_success() => {
|
||||||
|
return Err(transport_failure(status));
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match envelope_error_from_json(&value) {
|
||||||
|
Ok(Some(error)) => {
|
||||||
|
if status.is_success() {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||||
|
"protocol error envelope carried by a success status",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !error.code.is_allowed_for(interaction) {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::DisallowedProtocolCode,
|
||||||
|
format!(
|
||||||
|
"code `{}` is not allowed for {interaction:?}",
|
||||||
|
error_code_name(error.code)
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let expected = status_for_error(error.code);
|
||||||
|
let status_mismatch =
|
||||||
|
(!status_matches_error(status, error.code)).then_some(StatusMismatch {
|
||||||
|
actual: status,
|
||||||
|
expected,
|
||||||
|
});
|
||||||
|
Ok(DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(_) if !status.is_success() => Err(transport_failure(status)),
|
||||||
|
Err(error) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)),
|
||||||
|
Ok(None) if status == StatusCode::OK => success(&value)
|
||||||
|
.map(DecodedResponse::Success)
|
||||||
|
.map_err(|error| {
|
||||||
|
ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
Ok(None) if status.is_success() => match success(&value) {
|
||||||
|
Ok(_) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||||
|
format!("success body carried by non-canonical HTTP {status}"),
|
||||||
|
)),
|
||||||
|
Err(error) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
Ok(None) => match success(&value) {
|
||||||
|
Ok(_) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||||
|
"valid success body carried by a non-success status",
|
||||||
|
)),
|
||||||
|
Err(_) => Err(transport_failure(status)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
||||||
|
let kind = match status {
|
||||||
|
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
||||||
|
StatusCode::FORBIDDEN => TransportFailureKind::EndpointForbidden,
|
||||||
|
_ => TransportFailureKind::HttpStatus,
|
||||||
|
};
|
||||||
|
ClientResponseError::TransportBinding(TransportBindingFailure { status, kind })
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
use wip_http::http::StatusCode;
|
||||||
|
use wip_http::wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
|
Object, ObjectObservation, ObserveRequest, ProtocolError, ProtocolErrorCode,
|
||||||
|
};
|
||||||
|
use wip_http::{
|
||||||
|
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
||||||
|
BatchResponseItem, BatchSuccess, ClientResponseError, DecodedResponse, Endpoint,
|
||||||
|
InvalidResponseKind, Limits, ResourceLimitKind, decode_batch_request, decode_batch_response,
|
||||||
|
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
||||||
|
encode_batch_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(100_000, 100_000, 64, 4).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn observed_item(validator: Option<Vec<u8>>) -> ObjectObservation {
|
||||||
|
ObjectObservation {
|
||||||
|
object: Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator,
|
||||||
|
},
|
||||||
|
children: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request() -> BatchRequest {
|
||||||
|
BatchRequest {
|
||||||
|
requests: vec![
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "object".into(),
|
||||||
|
request: BatchRequestKind::Observe(ObserveRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
depth: 0,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_round_trips_by_unique_id_with_item_failures_and_validators() {
|
||||||
|
let request = request();
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
||||||
|
let encoded_request = encode_batch_request(&endpoint, &request, limits()).unwrap();
|
||||||
|
assert_eq!(encoded_request.uri().path(), "/wip/v1/batch");
|
||||||
|
assert_eq!(encoded_request.headers()["accept"], "application/json");
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Err(ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "gone".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Observe(observed_item(Some(vec![
|
||||||
|
0, 1, 2, 255,
|
||||||
|
])))),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("AAEC/w==")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_interface_validator_round_trips_in_item_body() {
|
||||||
|
let request = BatchRequest {
|
||||||
|
requests: vec![BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Ok(BatchSuccess::FetchInterface(FetchInterfaceResponse {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
descriptor: InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![],
|
||||||
|
},
|
||||||
|
validator: Some(vec![255, 254, 253]),
|
||||||
|
})),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("//79")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_known_method_arguments_are_item_local() {
|
||||||
|
let body = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"valid","method":"observe","arguments":{"path":"/item","depth":0}},
|
||||||
|
{"id":"invalid","method":"observe","arguments":{"path":"/","depth":"deep"}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
let decoded = decode_batch_request(body, limits()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decoded.requests[0].request,
|
||||||
|
BatchRequestKind::Observe(_)
|
||||||
|
));
|
||||||
|
let invalid = match &decoded.requests[1].request {
|
||||||
|
BatchRequestKind::Invalid { method, error } => {
|
||||||
|
assert_eq!(*method, BatchMethod::Observe);
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::InvalidRequest);
|
||||||
|
error.clone()
|
||||||
|
}
|
||||||
|
other => panic!("expected item-local invalid request, got {other:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "valid".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "invalid".into(),
|
||||||
|
outcome: Err(invalid),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&decoded, &response, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&decoded, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_batch_envelopes_are_rejected_at_top_level() {
|
||||||
|
assert!(decode_batch_request(br#"{}"#, limits()).is_err());
|
||||||
|
|
||||||
|
let malformed_item = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"item","method":"observe","arguments":{"path":"/","depth":0},"extra":true}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
assert!(decode_batch_request(malformed_item, limits()).is_err());
|
||||||
|
|
||||||
|
let duplicate = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"same","method":"observe","arguments":{"path":"/a","depth":0}},
|
||||||
|
{"id":"same","method":"observe","arguments":{"path":"/b","depth":0}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
assert!(decode_batch_request(duplicate, limits()).is_err());
|
||||||
|
|
||||||
|
let operation = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"call","method":"call_operation","arguments":{}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
assert!(decode_batch_request(operation, limits()).is_err());
|
||||||
|
|
||||||
|
let too_many = Limits::new(100_000, 100_000, 64, 1).unwrap();
|
||||||
|
assert!(decode_batch_request(duplicate, too_many).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_resource_limits_use_413_or_422_and_never_429() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "bounded".into(),
|
||||||
|
};
|
||||||
|
for (kind, status) in [
|
||||||
|
(
|
||||||
|
ResourceLimitKind::RepresentationBytes,
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
),
|
||||||
|
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
] {
|
||||||
|
let encoded = encode_batch_resource_limit_error_response(&error, kind, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), status);
|
||||||
|
assert_ne!(encoded.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_success_body_requires_exactly_http_200() {
|
||||||
|
let request = request();
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Err(ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "gone".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
||||||
|
let mut noncanonical = encoded.clone();
|
||||||
|
*noncanonical.status_mut() = status;
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request, &noncanonical, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn top_level_batch_errors_use_the_batch_allowed_code_set() {
|
||||||
|
let invalid = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "bad envelope".into(),
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_error_response(&invalid, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: invalid,
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let not_found = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::NOT_FOUND)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(br#"{"error":{"code":"not_found","message":"not a batch failure"}}"#.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), ¬_found, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
|
||||||
|
let duplicate = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future":true}}},{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), &duplicate, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let missing = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), &missing, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let request = BatchRequest {
|
||||||
|
requests: vec![BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request, &missing, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { format }
|
||||||
|
if format == "wip-interface/2"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_response_must_have_exactly_the_requested_ids() {
|
||||||
|
let request = request();
|
||||||
|
let missing = BatchResponse {
|
||||||
|
responses: vec![BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
assert!(encode_batch_response(&request, &missing, limits()).is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,526 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use wip_http::http::StatusCode;
|
||||||
|
use wip_http::wip_protocol::{
|
||||||
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
|
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
|
InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
|
||||||
|
OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target, TypeDeclaration,
|
||||||
|
TypeExpr, UnionCase, Value,
|
||||||
|
};
|
||||||
|
use wip_http::{
|
||||||
|
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||||
|
ResourceLimitKind, decode_call_operation_metadata, decode_call_operation_request,
|
||||||
|
decode_call_operation_response, decode_fetch_interface_request,
|
||||||
|
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
||||||
|
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||||
|
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(1_000_000, 1_000_000, 100, 100).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint() -> Endpoint {
|
||||||
|
Endpoint::parse("https://example.test/wip").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object(name: &str, validator: &[u8]) -> Object {
|
||||||
|
Object {
|
||||||
|
name: name.into(),
|
||||||
|
description: Some("description".into()),
|
||||||
|
interfaces: vec!["interface-v1".into()],
|
||||||
|
r#ref: Some(format!("object:{name}")),
|
||||||
|
validator: Some(validator.to_vec()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn descriptor() -> InterfaceDescriptor {
|
||||||
|
InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: Some(Documentation {
|
||||||
|
summary: "Codec fixture".into(),
|
||||||
|
details: None,
|
||||||
|
}),
|
||||||
|
types: vec![TypeDeclaration {
|
||||||
|
name: "Pair".into(),
|
||||||
|
documentation: None,
|
||||||
|
definition: TypeExpr::Record {
|
||||||
|
fields: vec![
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "required".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "optional".into(),
|
||||||
|
required: false,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "optional_json".into(),
|
||||||
|
required: false,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Json,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "everything".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![
|
||||||
|
parameter("unit", TypeExpr::Unit),
|
||||||
|
parameter("boolean", TypeExpr::Boolean),
|
||||||
|
parameter("integer", TypeExpr::Integer),
|
||||||
|
parameter("number", TypeExpr::Number),
|
||||||
|
parameter("string", TypeExpr::String),
|
||||||
|
parameter("bytes", TypeExpr::Bytes),
|
||||||
|
parameter("entry", TypeExpr::Entry),
|
||||||
|
parameter(
|
||||||
|
"list",
|
||||||
|
TypeExpr::List {
|
||||||
|
items: Box::new(TypeExpr::Integer),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"record",
|
||||||
|
TypeExpr::Named {
|
||||||
|
name: "Pair".into(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"enum",
|
||||||
|
TypeExpr::Enum {
|
||||||
|
cases: vec![EnumCase {
|
||||||
|
name: "ready".into(),
|
||||||
|
documentation: None,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"union",
|
||||||
|
TypeExpr::Union {
|
||||||
|
cases: vec![
|
||||||
|
UnionCase {
|
||||||
|
name: "empty".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: None,
|
||||||
|
},
|
||||||
|
UnionCase {
|
||||||
|
name: "found".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: Some(TypeExpr::Entry),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter("json", TypeExpr::Json),
|
||||||
|
],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Bytes,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter(name: &str, r#type: TypeExpr) -> ParameterDeclaration {
|
||||||
|
ParameterDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(fields: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||||
|
Value::Record(
|
||||||
|
fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, value)| (name.into(), value))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call_request() -> CallOperationRequest {
|
||||||
|
CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/items/123".into(),
|
||||||
|
validator: Some(vec![0, 1, 2, 255]),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: "interface-v1".into(),
|
||||||
|
validator: Some(vec![9, 8, 7]),
|
||||||
|
},
|
||||||
|
operation: "everything".into(),
|
||||||
|
arguments: BTreeMap::from([
|
||||||
|
("unit".into(), Value::Unit),
|
||||||
|
("boolean".into(), Value::Boolean(true)),
|
||||||
|
("integer".into(), Value::Integer(MAX_SAFE_INTEGER)),
|
||||||
|
("number".into(), Value::Number(1.5)),
|
||||||
|
("string".into(), Value::String("text".into())),
|
||||||
|
("bytes".into(), Value::Bytes(vec![0, 1, 2, 255])),
|
||||||
|
("entry".into(), Value::String("/items/123".into())),
|
||||||
|
(
|
||||||
|
"list".into(),
|
||||||
|
Value::List(vec![Value::Integer(1), Value::Integer(2)]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"record".into(),
|
||||||
|
record([("required", Value::String("present".into()))]),
|
||||||
|
),
|
||||||
|
("enum".into(), Value::String("ready".into())),
|
||||||
|
(
|
||||||
|
"union".into(),
|
||||||
|
record([
|
||||||
|
("$case", Value::String("found".into())),
|
||||||
|
("value", Value::String("/items/123".into())),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"json".into(),
|
||||||
|
record([
|
||||||
|
("null", Value::Unit),
|
||||||
|
("number", Value::Integer(2)),
|
||||||
|
("path_like", Value::String("/not-an-entry".into())),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_single_interaction_request_accepts_json() {
|
||||||
|
let observe = encode_observe_request(
|
||||||
|
&endpoint(),
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let fetch_interface = encode_fetch_interface_request(
|
||||||
|
&endpoint(),
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let call = encode_call_operation_request(&endpoint(), &call_request(), &descriptor(), limits())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for request in [observe, fetch_interface, call] {
|
||||||
|
assert_eq!(request.headers()["accept"], "application/json");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn depth_zero_observe_round_trips_direct_body_and_validator() {
|
||||||
|
let request = ObserveRequest {
|
||||||
|
path: "/items/123".into(),
|
||||||
|
depth: 0,
|
||||||
|
};
|
||||||
|
let encoded_request = encode_observe_request(&endpoint(), &request, limits()).unwrap();
|
||||||
|
assert_eq!(encoded_request.uri().path(), "/wip/v1/observe");
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = ObjectObservation {
|
||||||
|
object: object("123", &[0, 1, 2, 255]),
|
||||||
|
children: None,
|
||||||
|
};
|
||||||
|
let encoded = encode_observe_response(&request, &expected, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
!std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("children")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(expected)
|
||||||
|
);
|
||||||
|
assert!(encoded.headers().get("etag").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observe_and_interface_round_trip_nested_logical_models() {
|
||||||
|
let observe_request = ObserveRequest {
|
||||||
|
path: "/items".into(),
|
||||||
|
depth: 1,
|
||||||
|
};
|
||||||
|
let encoded_request = encode_observe_request(&endpoint(), &observe_request, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
observe_request
|
||||||
|
);
|
||||||
|
let observation = ObjectObservation {
|
||||||
|
object: object("items", b"root-validator"),
|
||||||
|
children: Some(vec![ObjectObservation {
|
||||||
|
object: object("123", b"child-validator"),
|
||||||
|
children: None,
|
||||||
|
}]),
|
||||||
|
};
|
||||||
|
let encoded = encode_observe_response(&observe_request, &observation, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&observe_request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(observation)
|
||||||
|
);
|
||||||
|
|
||||||
|
let empty = ObjectObservation {
|
||||||
|
object: object("items", b"root-validator"),
|
||||||
|
children: Some(vec![]),
|
||||||
|
};
|
||||||
|
let encoded_empty = encode_observe_response(&observe_request, &empty, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded_empty.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("\"children\":[]")
|
||||||
|
);
|
||||||
|
|
||||||
|
let interface_request = FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
};
|
||||||
|
let encoded_request =
|
||||||
|
encode_fetch_interface_request(&endpoint(), &interface_request, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_interface_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
interface_request
|
||||||
|
);
|
||||||
|
let interface = FetchInterfaceResponse {
|
||||||
|
interface: interface_request.interface.clone(),
|
||||||
|
descriptor: descriptor(),
|
||||||
|
validator: Some(vec![4, 5, 6, 255]),
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_fetch_interface_response(&interface_request, &interface, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_interface_response(&interface_request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(interface)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn descriptor_guided_values_and_validators_round_trip_both_directions() {
|
||||||
|
let descriptor = descriptor();
|
||||||
|
let request = call_request();
|
||||||
|
let encoded =
|
||||||
|
encode_call_operation_request(&endpoint(), &request, &descriptor, limits()).unwrap();
|
||||||
|
let body = std::str::from_utf8(encoded.body()).unwrap();
|
||||||
|
assert!(body.contains("AAEC/w=="));
|
||||||
|
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||||
|
assert_eq!(metadata.target, request.target);
|
||||||
|
assert_eq!(metadata.interface, request.interface);
|
||||||
|
assert_eq!(metadata.operation, request.operation);
|
||||||
|
assert_eq!(
|
||||||
|
metadata
|
||||||
|
.decode_request(encoded.body(), &descriptor, limits())
|
||||||
|
.unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
let mut changed_route = request.clone();
|
||||||
|
changed_route.target.path = "/items/other".into();
|
||||||
|
let changed =
|
||||||
|
encode_call_operation_request(&endpoint(), &changed_route, &descriptor, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
metadata
|
||||||
|
.decode_request(changed.body(), &descriptor, limits())
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut null_json_request = request.clone();
|
||||||
|
null_json_request
|
||||||
|
.arguments
|
||||||
|
.insert("json".into(), Value::Unit);
|
||||||
|
null_json_request.arguments.insert(
|
||||||
|
"record".into(),
|
||||||
|
record([
|
||||||
|
("required", Value::String("present".into())),
|
||||||
|
("optional_json", Value::Unit),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
let null_json =
|
||||||
|
encode_call_operation_request(&endpoint(), &null_json_request, &descriptor, limits())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_call_operation_request(null_json.body(), &descriptor, limits()).unwrap(),
|
||||||
|
null_json_request
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = CallOperationResponse {
|
||||||
|
result: Value::Bytes(vec![255, 0, 1]),
|
||||||
|
validator: Some(vec![3, 2, 1, 0]),
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_call_operation_response(&request, &descriptor, &expected, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("/wAB")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_call_operation_response(&request, &descriptor, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(expected)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
|
||||||
|
let limits = limits();
|
||||||
|
assert!(decode_observe_request(br#"{"path":"/","depth":0,"extra":true}"#, limits).is_err());
|
||||||
|
assert!(
|
||||||
|
decode_observe_request(br#"{"path":"relative","path":"/","depth":0}"#, limits).is_err()
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = call_request();
|
||||||
|
let descriptor = descriptor();
|
||||||
|
let body = serde_json::to_vec(&serde_json::json!({
|
||||||
|
"target": {"path": "/items/123", "validator": null},
|
||||||
|
"interface": {"reference": "interface-v1"},
|
||||||
|
"operation": "everything",
|
||||||
|
"arguments": {}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(decode_call_operation_request(&body, &descriptor, limits).is_err());
|
||||||
|
|
||||||
|
let mut json: serde_json::Value = serde_json::from_slice(
|
||||||
|
encode_call_operation_request(&endpoint(), &request, &descriptor, limits)
|
||||||
|
.unwrap()
|
||||||
|
.body(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
json["arguments"]["bytes"] = serde_json::Value::String("AAEC_w==".into());
|
||||||
|
assert!(
|
||||||
|
decode_call_operation_request(&serde_json::to_vec(&json).unwrap(), &descriptor, limits)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caller_limits_bound_bytes_and_nesting() {
|
||||||
|
let tiny = Limits::new(8, 8, 2, 1).unwrap();
|
||||||
|
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
||||||
|
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
too_large.resource_limit_kind(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes)
|
||||||
|
);
|
||||||
|
|
||||||
|
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
||||||
|
let nesting_limited = Limits::new(1024, 1024, 2, 1).unwrap();
|
||||||
|
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
||||||
|
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
too_deep.resource_limit_kind(),
|
||||||
|
Some(ResourceLimitKind::Logical)
|
||||||
|
);
|
||||||
|
|
||||||
|
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1, 10).unwrap();
|
||||||
|
assert!(
|
||||||
|
encode_call_operation_request(
|
||||||
|
&endpoint(),
|
||||||
|
&call_request(),
|
||||||
|
&descriptor(),
|
||||||
|
outbound_limited,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
encode_observe_response(
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
&ObjectObservation {
|
||||||
|
object: object("item", b"validator"),
|
||||||
|
children: None,
|
||||||
|
},
|
||||||
|
outbound_limited,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_descriptor_format_is_client_local() {
|
||||||
|
let request = FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
};
|
||||||
|
let mut interface = FetchInterfaceResponse {
|
||||||
|
interface: request.interface.clone(),
|
||||||
|
descriptor: descriptor(),
|
||||||
|
validator: None,
|
||||||
|
};
|
||||||
|
interface.descriptor.format = "future-format".into();
|
||||||
|
let response = encode_fetch_interface_response(&request, &interface, limits()).unwrap();
|
||||||
|
let error = decode_fetch_interface_response(&request, &response, limits()).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { .. }
|
||||||
|
));
|
||||||
|
|
||||||
|
let future_shape = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future_shape":true}}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_interface_response(&request, &future_shape, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { format }
|
||||||
|
if format == "wip-interface/2"
|
||||||
|
));
|
||||||
|
|
||||||
|
for malformed in [
|
||||||
|
br#"{"interface":"wrong","descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
||||||
|
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
||||||
|
.as_slice(),
|
||||||
|
] {
|
||||||
|
let response = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(malformed.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_interface_response(&request, &response, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_success_is_classified_as_invalid_response() {
|
||||||
|
let response = wip_http::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(br#"{"object":{"name":"wrong","interfaces":[]}}"#.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
let error = decode_observe_response(
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/expected".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
&response,
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
use wip_http::http::{Response, StatusCode};
|
||||||
|
use wip_http::wip_protocol::{
|
||||||
|
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
|
};
|
||||||
|
use wip_http::{
|
||||||
|
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, ResourceLimitKind,
|
||||||
|
TransportFailureKind, decode_observe_response, encode_protocol_error_response,
|
||||||
|
encode_resource_limit_error_response, error_code_name, is_json_content_type, status_for_error,
|
||||||
|
status_for_resource_limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(64 * 1024, 64 * 1024, 32, 16).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request() -> ObserveRequest {
|
||||||
|
ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: StatusCode, body: impl Into<Vec<u8>>) -> Response<Vec<u8>> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(body.into())
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_type_accepts_only_utf8_json_syntax() {
|
||||||
|
assert!(is_json_content_type("application/json"));
|
||||||
|
assert!(is_json_content_type("Application/JSON; Charset=\"UTF-8\""));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=utf-16"));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=\"utf-8"));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=utf-8\""));
|
||||||
|
assert!(!is_json_content_type("application/json; profile=other"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_protocol_code_has_stable_name_and_status() {
|
||||||
|
let expected = [
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InvalidRequest,
|
||||||
|
"invalid_request",
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::NotFound,
|
||||||
|
"not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
"interface_not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceMismatch,
|
||||||
|
"interface_mismatch",
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::OperationNotFound,
|
||||||
|
"operation_not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InvalidArguments,
|
||||||
|
"invalid_arguments",
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ValidatorRequired,
|
||||||
|
"validator_required",
|
||||||
|
StatusCode::PRECONDITION_REQUIRED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
"validator_mismatch",
|
||||||
|
StatusCode::PRECONDITION_FAILED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
|
"interface_validator_required",
|
||||||
|
StatusCode::PRECONDITION_REQUIRED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
|
"interface_validator_mismatch",
|
||||||
|
StatusCode::PRECONDITION_FAILED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::PermissionDenied,
|
||||||
|
"permission_denied",
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
"resource_limit_exceeded",
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
"internal",
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
"operation_outcome_unknown",
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
assert_eq!(expected.len(), ProtocolErrorCode::ALL.len());
|
||||||
|
for (code, name, status) in expected {
|
||||||
|
assert_eq!(error_code_name(code), name);
|
||||||
|
assert_eq!(status_for_error(code), status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "bounded".into(),
|
||||||
|
};
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
ResourceLimitKind::RepresentationBytes,
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
),
|
||||||
|
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
];
|
||||||
|
for (kind, status) in cases {
|
||||||
|
assert_eq!(status_for_resource_limit(kind), status);
|
||||||
|
let encoded = encode_resource_limit_error_response(
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
&error,
|
||||||
|
kind,
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(encoded.status(), status);
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let default =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
|
assert_eq!(default.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert_ne!(default.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
|
||||||
|
let response = Response::builder()
|
||||||
|
.status(StatusCode::TOO_MANY_REQUESTS)
|
||||||
|
.body(b"rate limited".to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &response, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::TOO_MANY_REQUESTS
|
||||||
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_success_body_requires_exactly_http_200() {
|
||||||
|
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||||
|
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &response(status, success_body), limits())
|
||||||
|
.unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_encoder_rejects_codes_disallowed_for_the_interaction() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "not valid for observe".into(),
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_envelope_code_is_authoritative_when_status_mismatches() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
|
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: Some(wip_http::StatusMismatch {
|
||||||
|
actual: StatusCode::IM_A_TEAPOT,
|
||||||
|
expected: StatusCode::NOT_FOUND,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn envelope_and_status_contradictions_are_invalid_responses() {
|
||||||
|
let error_body = br#"{"error":{"code":"not_found","message":"missing"}}"#;
|
||||||
|
let on_success =
|
||||||
|
decode_observe_response(&request(), &response(StatusCode::OK, error_body), limits())
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
on_success,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||||
|
let on_error = decode_observe_response(
|
||||||
|
&request(),
|
||||||
|
&response(StatusCode::BAD_GATEWAY, success_body),
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
on_error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disallowed_protocol_code_is_invalid_instead_of_reclassified() {
|
||||||
|
let body = br#"{"error":{"code":"interface_not_found","message":"wrong interaction"}}"#;
|
||||||
|
let error =
|
||||||
|
decode_observe_response(&request(), &response(StatusCode::NOT_FOUND, body), limits())
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::DisallowedProtocolCode,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn proxy_authentication_and_endpoint_failures_stay_transport_failures() {
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
TransportFailureKind::HttpStatus,
|
||||||
|
b"proxy failure".as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
TransportFailureKind::AuthenticationRequired,
|
||||||
|
b"login required".as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
TransportFailureKind::EndpointForbidden,
|
||||||
|
b"denied".as_slice(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (status, expected_kind, body) in cases {
|
||||||
|
let response = Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.body(body.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
let error = decode_observe_response(&request(), &response, limits()).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == status && failure.kind == expected_kind
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_non_success_envelope_is_transport_binding_failure() {
|
||||||
|
let malformed = response(
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
br#"{"error":{"code":"not_found","message":null}}"#,
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &malformed, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(_)
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
use wip_http::http::{Method, Request, StatusCode};
|
||||||
|
use wip_http::{Endpoint, RequestMetadataError, Route, validate_http_request};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endpoint_preserves_http_and_https_when_resolving_canonical_routes() {
|
||||||
|
for scheme in ["http", "https"] {
|
||||||
|
let endpoint = Endpoint::parse(&format!("{scheme}://example.test/root/prefix")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.to_string(),
|
||||||
|
format!("{scheme}://example.test/root/prefix/")
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = [
|
||||||
|
(Route::Observe, "v1/observe"),
|
||||||
|
(Route::FetchInterface, "v1/fetch_interface"),
|
||||||
|
(Route::CallOperation, "v1/call_operation"),
|
||||||
|
(Route::Batch, "v1/batch"),
|
||||||
|
];
|
||||||
|
for (route, suffix) in expected {
|
||||||
|
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
|
||||||
|
assert_eq!(endpoint.route(route).as_str(), url);
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(&wip_http::url::Url::parse(&url).unwrap()),
|
||||||
|
Some(route)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(
|
||||||
|
&wip_http::url::Url::parse(&format!(
|
||||||
|
"{scheme}://example.test/root/prefix/v1/observe?path=/items"
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
|
||||||
|
let route = endpoint.route(Route::Observe);
|
||||||
|
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/observe");
|
||||||
|
assert!(!route.as_str().contains("items"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inbound_http_metadata_enforces_post_route_and_json() {
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
||||||
|
let valid = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &valid).is_ok());
|
||||||
|
|
||||||
|
let wrong_method = Request::builder()
|
||||||
|
.method(Method::GET)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_method).is_err());
|
||||||
|
|
||||||
|
let wrong_route = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/fetch_interface")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_route).is_err());
|
||||||
|
|
||||||
|
for accept in [
|
||||||
|
"text/plain, */*;q=1, application/json;q=0",
|
||||||
|
"application/json; charset=utf-16",
|
||||||
|
"application/json; profile=future",
|
||||||
|
] {
|
||||||
|
let incompatible_accept = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("accept", accept)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &incompatible_accept).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
|
||||||
|
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
for accept in [
|
||||||
|
"application/json; charset=UTF-8",
|
||||||
|
"application/json; q=1; profile=accept-extension",
|
||||||
|
] {
|
||||||
|
let compatible_accept = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("accept", accept)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &compatible_accept).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
let unsupported_media_type = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "text/plain")
|
||||||
|
.header("accept", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||||
|
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_endpoint_components_and_non_routes_are_rejected() {
|
||||||
|
assert!(Endpoint::parse("/relative").is_err());
|
||||||
|
assert!(Endpoint::parse("file:///wip").is_err());
|
||||||
|
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
|
||||||
|
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
|
||||||
|
|
||||||
|
let deployment_endpoint = Endpoint::parse("http://user:secret@example.test/wip").unwrap();
|
||||||
|
assert_eq!(deployment_endpoint.as_url().scheme(), "http");
|
||||||
|
assert_eq!(deployment_endpoint.as_url().username(), "user");
|
||||||
|
|
||||||
|
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
|
||||||
|
for outside in [
|
||||||
|
"http://example.test/wip/v1/unknown",
|
||||||
|
"http://example.test/wip/v1/observe/extra",
|
||||||
|
"https://example.test/wip/v1/observe",
|
||||||
|
"http://other.test/wip/v1/observe",
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(&wip_http::url::Url::parse(outside).unwrap()),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
//! Procedural macros backing the public `wip-interface` authoring facade.
|
//! Procedural macros backing the public `wip-interface` authoring facade.
|
||||||
|
//!
|
||||||
|
//! This is an implementation crate. Applications should depend on
|
||||||
|
//! `wip-interface`, which re-exports both macros alongside the traits and types
|
||||||
|
//! used by their generated code.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
@@ -162,14 +168,40 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
|||||||
#(#declaration_collectors)*
|
#(#declaration_collectors)*
|
||||||
|
|
||||||
::wip_interface::wip_protocol::InterfaceDescriptor {
|
::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,
|
documentation: #trait_doc,
|
||||||
declarations,
|
types: declarations,
|
||||||
operations: ::std::vec![#(#operation_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 {
|
impl #definition_ident {
|
||||||
/// Builds the interface descriptor generated from the trait declaration.
|
/// Builds the interface descriptor generated from the trait declaration.
|
||||||
pub fn descriptor() -> ::wip_interface::wip_protocol::InterfaceDescriptor {
|
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>(
|
pub fn dispatch<T: #trait_ident>(
|
||||||
implementation: &T,
|
implementation: &T,
|
||||||
operation: &str,
|
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::result::Result<
|
||||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
::wip_interface::wip_protocol::Value,
|
||||||
::wip_interface::DispatchError,
|
::wip_interface::DispatchError,
|
||||||
> {
|
> {
|
||||||
let descriptor = Self::descriptor();
|
<Self as ::wip_interface::InterfaceImplementation<T>>::dispatch(
|
||||||
match operation {
|
implementation,
|
||||||
#(#dispatch_arms)*
|
operation,
|
||||||
_ => ::std::result::Result::Err(
|
arguments,
|
||||||
::wip_interface::DispatchError::UnknownOperation(
|
)
|
||||||
::std::string::String::from(operation),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,13 +484,18 @@ fn parse_operation_result(output: &ReturnType) -> syn::Result<Type> {
|
|||||||
_ => None,
|
_ => None,
|
||||||
});
|
});
|
||||||
let result = types.next().cloned();
|
let result = types.next().cloned();
|
||||||
if arguments.args.len() != 1 || result.is_none() || types.next().is_some() {
|
if arguments.args.len() != 1 || types.next().is_some() {
|
||||||
return Err(Error::new_spanned(
|
return Err(Error::new_spanned(
|
||||||
arguments,
|
arguments,
|
||||||
"`OperationResult` must have exactly one application result type",
|
"`OperationResult` must have exactly one application result type",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let result = result.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) {
|
if direct_option(&result)?.is_some() || contains_option(&result) {
|
||||||
return Err(Error::new_spanned(
|
return Err(Error::new_spanned(
|
||||||
result,
|
result,
|
||||||
@@ -473,8 +509,13 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
|||||||
let arguments_ident = &operation.arguments_ident;
|
let arguments_ident = &operation.arguments_ident;
|
||||||
let fields = operation.parameters.iter().map(|parameter| {
|
let fields = operation.parameters.iter().map(|parameter| {
|
||||||
let ident = ¶meter.ident;
|
let ident = ¶meter.ident;
|
||||||
|
let name = ¶meter.name;
|
||||||
let ty = parameter_rust_type(parameter);
|
let ty = parameter_rust_type(parameter);
|
||||||
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 decoders = operation.parameters.iter().map(|parameter| {
|
||||||
let ident = ¶meter.ident;
|
let ident = ¶meter.ident;
|
||||||
@@ -490,12 +531,11 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
|||||||
let encode_result = if operation.unit_result {
|
let encode_result = if operation.unit_result {
|
||||||
quote! {
|
quote! {
|
||||||
let () = result;
|
let () = result;
|
||||||
::std::result::Result::Ok(::std::option::Option::None)
|
::std::result::Result::Ok(::wip_interface::wip_protocol::Value::Unit)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
quote! {
|
quote! {
|
||||||
<#result_ty as ::wip_interface::WipType>::encode(result)
|
<#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 {
|
impl #arguments_ident {
|
||||||
/// Decodes named logical values into typed operation arguments.
|
/// Decodes named logical values into typed operation arguments.
|
||||||
pub fn decode(
|
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> {
|
) -> ::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 {
|
let decoded = Self {
|
||||||
#(#decoders,)*
|
#(#decoders,)*
|
||||||
};
|
};
|
||||||
@@ -522,7 +565,7 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
|||||||
pub fn encode_result(
|
pub fn encode_result(
|
||||||
result: #result_ty,
|
result: #result_ty,
|
||||||
) -> ::std::result::Result<
|
) -> ::std::result::Result<
|
||||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
::wip_interface::wip_protocol::Value,
|
||||||
::wip_interface::CodecError,
|
::wip_interface::CodecError,
|
||||||
> {
|
> {
|
||||||
#encode_result
|
#encode_result
|
||||||
@@ -542,22 +585,18 @@ fn operation_declaration(operation: &Operation) -> TokenStream2 {
|
|||||||
quote! {
|
quote! {
|
||||||
::wip_interface::wip_protocol::ParameterDeclaration {
|
::wip_interface::wip_protocol::ParameterDeclaration {
|
||||||
name: ::std::string::String::from(#parameter_name),
|
name: ::std::string::String::from(#parameter_name),
|
||||||
|
required: !#optional,
|
||||||
documentation: #parameter_doc,
|
documentation: #parameter_doc,
|
||||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||||
optional: #optional,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let returns = if operation.unit_result {
|
let result_ty = &operation.result_ty;
|
||||||
quote!(::std::option::Option::None)
|
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
||||||
} else {
|
let returns = quote! {
|
||||||
let result_ty = &operation.result_ty;
|
::wip_interface::wip_protocol::ReturnDeclaration {
|
||||||
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
documentation: #return_doc,
|
||||||
quote! {
|
r#type: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
||||||
::std::option::Option::Some(::wip_interface::wip_protocol::ReturnDeclaration {
|
|
||||||
documentation: #return_doc,
|
|
||||||
ty: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -608,14 +647,17 @@ fn dispatch_arm(operation: &Operation) -> TokenStream2 {
|
|||||||
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
||||||
let decoded = #arguments_ident::decode(arguments)
|
let decoded = #arguments_ident::decode(arguments)
|
||||||
.map_err(::wip_interface::DispatchError::Decode)?;
|
.map_err(::wip_interface::DispatchError::Decode)?;
|
||||||
let result = implementation.#method_ident(#(#arguments),*)
|
::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
|
||||||
.map_err(::wip_interface::DispatchError::Host)?;
|
let result = implementation.#method_ident(#(#arguments),*)
|
||||||
let encoded = #arguments_ident::encode_result(result)
|
.map_err(::wip_interface::DispatchError::Host)?;
|
||||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
let encoded = #arguments_ident::encode_result(result)
|
||||||
descriptor
|
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||||
.validate_return(#operation_name, encoded.as_ref())
|
descriptor
|
||||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
.validate_result(#operation_name, &encoded)
|
||||||
::std::result::Result::Ok(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 parsed_fields = Vec::new();
|
||||||
let mut names = HashSet::new();
|
let mut names = HashSet::new();
|
||||||
for field in fields {
|
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);
|
let name = source_name(&field_ident);
|
||||||
if !names.insert(name.clone()) {
|
if !names.insert(name.clone()) {
|
||||||
return Err(Error::new(
|
return Err(Error::new(
|
||||||
@@ -709,9 +756,9 @@ fn derive_record(
|
|||||||
quote! {
|
quote! {
|
||||||
::wip_interface::wip_protocol::FieldDeclaration {
|
::wip_interface::wip_protocol::FieldDeclaration {
|
||||||
name: ::std::string::String::from(#name),
|
name: ::std::string::String::from(#name),
|
||||||
|
required: !#optional,
|
||||||
documentation: #documentation,
|
documentation: #documentation,
|
||||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||||
optional: #optional,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -727,18 +774,18 @@ fn derive_record(
|
|||||||
if field.optional {
|
if field.optional {
|
||||||
quote! {
|
quote! {
|
||||||
if let ::std::option::Option::Some(value) = #field_ident {
|
if let ::std::option::Option::Some(value) = #field_ident {
|
||||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
fields.insert(
|
||||||
name: ::std::string::String::from(#field_name),
|
::std::string::String::from(#field_name),
|
||||||
value: <#ty as ::wip_interface::WipType>::encode(value)?,
|
<#ty as ::wip_interface::WipType>::encode(value)?,
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
quote! {
|
quote! {
|
||||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
fields.insert(
|
||||||
name: ::std::string::String::from(#field_name),
|
::std::string::String::from(#field_name),
|
||||||
value: <#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
<#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -756,9 +803,9 @@ fn derive_record(
|
|||||||
Ok(quote! {
|
Ok(quote! {
|
||||||
impl ::wip_interface::WipType for #ident {
|
impl ::wip_interface::WipType for #ident {
|
||||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||||
::std::string::String::from(#type_name),
|
name: ::std::string::String::from(#type_name),
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_declarations(
|
fn collect_declarations(
|
||||||
@@ -766,13 +813,13 @@ fn derive_record(
|
|||||||
::wip_interface::wip_protocol::TypeDeclaration,
|
::wip_interface::wip_protocol::TypeDeclaration,
|
||||||
>,
|
>,
|
||||||
) {
|
) {
|
||||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Record(
|
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||||
::wip_interface::wip_protocol::RecordDeclaration {
|
name: ::std::string::String::from(#type_name),
|
||||||
name: ::std::string::String::from(#type_name),
|
documentation: #declaration_doc,
|
||||||
documentation: #declaration_doc,
|
definition: ::wip_interface::wip_protocol::TypeExpr::Record {
|
||||||
fields: ::std::vec![#(#field_declarations),*],
|
fields: ::std::vec![#(#field_declarations),*],
|
||||||
},
|
},
|
||||||
);
|
};
|
||||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||||
#(#dependency_collectors)*
|
#(#dependency_collectors)*
|
||||||
}
|
}
|
||||||
@@ -785,7 +832,7 @@ fn derive_record(
|
|||||||
::wip_interface::CodecError,
|
::wip_interface::CodecError,
|
||||||
> {
|
> {
|
||||||
let Self { #(#destructured_fields),* } = self;
|
let Self { #(#destructured_fields),* } = self;
|
||||||
let mut fields = ::std::vec::Vec::new();
|
let mut fields = ::std::collections::BTreeMap::new();
|
||||||
#(#encoders)*
|
#(#encoders)*
|
||||||
::std::result::Result::Ok(
|
::std::result::Result::Ok(
|
||||||
::wip_interface::wip_protocol::Value::Record(fields),
|
::wip_interface::wip_protocol::Value::Record(fields),
|
||||||
@@ -797,7 +844,7 @@ fn derive_record(
|
|||||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||||
match value {
|
match value {
|
||||||
::wip_interface::wip_protocol::Value::Record(fields) => {
|
::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 {
|
let decoded = Self {
|
||||||
#(#decoders,)*
|
#(#decoders,)*
|
||||||
};
|
};
|
||||||
@@ -832,14 +879,14 @@ fn derive_enum(
|
|||||||
.variants
|
.variants
|
||||||
.iter()
|
.iter()
|
||||||
.all(|variant| matches!(variant.fields, Fields::Unit));
|
.all(|variant| matches!(variant.fields, Fields::Unit));
|
||||||
let all_payload = !data.variants.is_empty()
|
let valid_union = data.variants.iter().all(|variant| {
|
||||||
&& data.variants.iter().all(|variant| {
|
matches!(variant.fields, Fields::Unit)
|
||||||
matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
|| matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
||||||
});
|
});
|
||||||
|
|
||||||
if all_unit {
|
if all_unit {
|
||||||
derive_unit_enum(ident, type_name, type_documentation, data)
|
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)
|
derive_union_enum(ident, type_name, type_documentation, data)
|
||||||
} else {
|
} else {
|
||||||
let span = data
|
let span = data
|
||||||
@@ -852,7 +899,7 @@ fn derive_enum(
|
|||||||
.map_or_else(|| data.enum_token.span, Spanned::span);
|
.map_or_else(|| data.enum_token.span, Spanned::span);
|
||||||
Err(Error::new(
|
Err(Error::new(
|
||||||
span,
|
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 name = source_name(&variant.ident);
|
||||||
let documentation = documentation_tokens(documentation(&variant.attrs).as_ref());
|
let documentation = documentation_tokens(documentation(&variant.attrs).as_ref());
|
||||||
quote! {
|
quote! {
|
||||||
::wip_interface::wip_protocol::EnumVariantDeclaration {
|
::wip_interface::wip_protocol::EnumCase {
|
||||||
name: ::std::string::String::from(#name),
|
name: ::std::string::String::from(#name),
|
||||||
documentation: #documentation,
|
documentation: #documentation,
|
||||||
}
|
}
|
||||||
@@ -888,9 +935,9 @@ fn derive_unit_enum(
|
|||||||
Ok(quote! {
|
Ok(quote! {
|
||||||
impl ::wip_interface::WipType for #ident {
|
impl ::wip_interface::WipType for #ident {
|
||||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||||
::std::string::String::from(#type_name),
|
name: ::std::string::String::from(#type_name),
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_declarations(
|
fn collect_declarations(
|
||||||
@@ -898,13 +945,13 @@ fn derive_unit_enum(
|
|||||||
::wip_interface::wip_protocol::TypeDeclaration,
|
::wip_interface::wip_protocol::TypeDeclaration,
|
||||||
>,
|
>,
|
||||||
) {
|
) {
|
||||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Enum(
|
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||||
::wip_interface::wip_protocol::EnumDeclaration {
|
name: ::std::string::String::from(#type_name),
|
||||||
name: ::std::string::String::from(#type_name),
|
documentation: #declaration_doc,
|
||||||
documentation: #declaration_doc,
|
definition: ::wip_interface::wip_protocol::TypeExpr::Enum {
|
||||||
variants: ::std::vec![#(#declarations),*],
|
cases: ::std::vec![#(#declarations),*],
|
||||||
},
|
},
|
||||||
);
|
};
|
||||||
let _ = ::wip_interface::__private::register_declaration(
|
let _ = ::wip_interface::__private::register_declaration(
|
||||||
declarations,
|
declarations,
|
||||||
declaration,
|
declaration,
|
||||||
@@ -921,7 +968,7 @@ fn derive_unit_enum(
|
|||||||
#(#encoders,)*
|
#(#encoders,)*
|
||||||
};
|
};
|
||||||
::std::result::Result::Ok(
|
::std::result::Result::Ok(
|
||||||
::wip_interface::wip_protocol::Value::Enum(
|
::wip_interface::wip_protocol::Value::String(
|
||||||
::std::string::String::from(variant),
|
::std::string::String::from(variant),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -931,7 +978,7 @@ fn derive_unit_enum(
|
|||||||
value: ::wip_interface::wip_protocol::Value,
|
value: ::wip_interface::wip_protocol::Value,
|
||||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||||
match value {
|
match value {
|
||||||
::wip_interface::wip_protocol::Value::Enum(variant) => {
|
::wip_interface::wip_protocol::Value::String(variant) => {
|
||||||
match variant.as_str() {
|
match variant.as_str() {
|
||||||
#(#decoders,)*
|
#(#decoders,)*
|
||||||
_ => ::std::result::Result::Err(
|
_ => ::std::result::Result::Err(
|
||||||
@@ -960,30 +1007,36 @@ fn derive_union_enum(
|
|||||||
struct Variant<'a> {
|
struct Variant<'a> {
|
||||||
ident: &'a Ident,
|
ident: &'a Ident,
|
||||||
name: String,
|
name: String,
|
||||||
ty: &'a Type,
|
payload: Option<&'a Type>,
|
||||||
documentation: Option<Documentation>,
|
documentation: Option<Documentation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut variants = Vec::new();
|
let mut variants = Vec::new();
|
||||||
for variant in &data.variants {
|
for variant in &data.variants {
|
||||||
let Fields::Unnamed(fields) = &variant.fields else {
|
let payload = match &variant.fields {
|
||||||
unreachable!("enum shape was checked before union generation");
|
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 {
|
variants.push(Variant {
|
||||||
ident: &variant.ident,
|
ident: &variant.ident,
|
||||||
name: source_name(&variant.ident),
|
name: source_name(&variant.ident),
|
||||||
ty: &field.ty,
|
payload,
|
||||||
documentation: documentation(&variant.attrs),
|
documentation: documentation(&variant.attrs),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -992,50 +1045,95 @@ fn derive_union_enum(
|
|||||||
let declarations = variants.iter().map(|variant| {
|
let declarations = variants.iter().map(|variant| {
|
||||||
let name = &variant.name;
|
let name = &variant.name;
|
||||||
let documentation = documentation_tokens(variant.documentation.as_ref());
|
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! {
|
quote! {
|
||||||
::wip_interface::wip_protocol::UnionVariantDeclaration {
|
::wip_interface::wip_protocol::UnionCase {
|
||||||
name: ::std::string::String::from(#name),
|
name: ::std::string::String::from(#name),
|
||||||
documentation: #documentation,
|
documentation: #documentation,
|
||||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
payload: #payload,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let dependency_collectors = variants.iter().map(|variant| {
|
let dependency_collectors = variants.iter().filter_map(|variant| {
|
||||||
let ty = variant.ty;
|
variant.payload.map(
|
||||||
quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);)
|
|ty| quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);),
|
||||||
|
)
|
||||||
});
|
});
|
||||||
let encoders = variants.iter().map(|variant| {
|
let encoders = variants.iter().map(|variant| {
|
||||||
let variant_ident = variant.ident;
|
let variant_ident = variant.ident;
|
||||||
let name = &variant.name;
|
let name = &variant.name;
|
||||||
let ty = variant.ty;
|
match variant.payload {
|
||||||
quote! {
|
Some(ty) => quote! {
|
||||||
Self::#variant_ident(value) => {
|
Self::#variant_ident(value) => {
|
||||||
::wip_interface::wip_protocol::Value::Union {
|
let mut fields = ::std::collections::BTreeMap::new();
|
||||||
variant: ::std::string::String::from(#name),
|
fields.insert(
|
||||||
value: ::std::boxed::Box::new(
|
::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)?,
|
<#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 decoders = variants.iter().map(|variant| {
|
||||||
let variant_ident = variant.ident;
|
let variant_ident = variant.ident;
|
||||||
let name = &variant.name;
|
let name = &variant.name;
|
||||||
let ty = variant.ty;
|
match variant.payload {
|
||||||
quote! {
|
Some(ty) => quote! {
|
||||||
#name => <#ty as ::wip_interface::WipType>::decode(*value)
|
#name => {
|
||||||
.map(Self::#variant_ident)
|
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! {
|
Ok(quote! {
|
||||||
impl ::wip_interface::WipType for #ident {
|
impl ::wip_interface::WipType for #ident {
|
||||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||||
::std::string::String::from(#type_name),
|
name: ::std::string::String::from(#type_name),
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_declarations(
|
fn collect_declarations(
|
||||||
@@ -1043,13 +1141,13 @@ fn derive_union_enum(
|
|||||||
::wip_interface::wip_protocol::TypeDeclaration,
|
::wip_interface::wip_protocol::TypeDeclaration,
|
||||||
>,
|
>,
|
||||||
) {
|
) {
|
||||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Union(
|
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||||
::wip_interface::wip_protocol::UnionDeclaration {
|
name: ::std::string::String::from(#type_name),
|
||||||
name: ::std::string::String::from(#type_name),
|
documentation: #declaration_doc,
|
||||||
documentation: #declaration_doc,
|
definition: ::wip_interface::wip_protocol::TypeExpr::Union {
|
||||||
variants: ::std::vec![#(#declarations),*],
|
cases: ::std::vec![#(#declarations),*],
|
||||||
},
|
},
|
||||||
);
|
};
|
||||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||||
#(#dependency_collectors)*
|
#(#dependency_collectors)*
|
||||||
}
|
}
|
||||||
@@ -1071,26 +1169,30 @@ fn derive_union_enum(
|
|||||||
value: ::wip_interface::wip_protocol::Value,
|
value: ::wip_interface::wip_protocol::Value,
|
||||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||||
match value {
|
match value {
|
||||||
::wip_interface::wip_protocol::Value::Union { variant, value } => {
|
::wip_interface::wip_protocol::Value::Record(fields) => {
|
||||||
match variant.as_str() {
|
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,)*
|
#(#decoders,)*
|
||||||
_ => ::std::result::Result::Err(
|
_ => ::std::result::Result::Err(
|
||||||
::wip_interface::__private::decode_unknown_variant(
|
::wip_interface::__private::decode_unknown_variant(
|
||||||
#type_name,
|
#type_name,
|
||||||
variant,
|
case,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
actual => ::std::result::Result::Err(
|
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)> {
|
fn optional_type(ty: &Type, context: &str) -> syn::Result<(bool, Type)> {
|
||||||
if let Some(inner) = direct_option(ty)? {
|
if let Some(inner) = direct_option(ty)? {
|
||||||
if contains_option(&inner) {
|
if contains_option(&inner) {
|
||||||
|
|||||||
+369
-110
@@ -30,37 +30,65 @@
|
|||||||
//!
|
//!
|
||||||
//! | Rust type | Protocol type/value |
|
//! | Rust type | Protocol type/value |
|
||||||
//! | --- | --- |
|
//! | --- | --- |
|
||||||
//! | `()` as an operation result | no return declaration / no value |
|
//! | `()` | `Unit` |
|
||||||
//! | `bool` | `Boolean` |
|
//! | `bool` | `Boolean` |
|
||||||
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
||||||
//! | `f32`, `f64` | finite `Number` |
|
//! | `f32`, `f64` | finite `Number` |
|
||||||
//! | `String` | `String` |
|
//! | `String` | `String` |
|
||||||
//! | [`Bytes`] | `Bytes` |
|
//! | [`Bytes`] | `Bytes` |
|
||||||
//! | [`wip_protocol::JsonValue`] | `Json` |
|
//! | [`JsonValue`] | schema-neutral `Json` value tree |
|
||||||
//! | [`Entry<K, V>`] | `Entry<K, V>` |
|
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
|
||||||
//! | `Vec<T>` | `List<T>` |
|
//! | `Vec<T>` | `List<T>` |
|
||||||
//! | a named-field struct deriving [`WipType`] | named record |
|
//! | a named-field struct deriving [`WipType`] | named record |
|
||||||
//! | an all-unit enum deriving [`WipType`] | named enum |
|
//! | 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
|
//! `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
|
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||||
//! an application return enum/union and is returned as `Ok(value)`.
|
//! an application return enum/union and is returned as `Ok(value)`.
|
||||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
|
||||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
//! [`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)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
pub use wip_interface_macros::{WipType, interface};
|
pub use wip_interface_macros::{WipType, interface};
|
||||||
pub use wip_protocol;
|
pub use wip_protocol;
|
||||||
pub use wip_protocol::{
|
pub use wip_protocol::{
|
||||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
|
||||||
JsonMember, JsonValue, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NamedValue, OperationDeclaration,
|
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
|
||||||
ParameterDeclaration, RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
|
||||||
UnionDeclaration, UnionVariantDeclaration, ValidationError, Value,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Converts one Rust application type to and from its protocol representation.
|
/// Converts one Rust application type to and from its protocol representation.
|
||||||
@@ -92,35 +120,128 @@ pub trait InterfaceDefinition {
|
|||||||
fn descriptor() -> InterfaceDescriptor;
|
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.
|
/// Result convention required for generated interface operations.
|
||||||
///
|
///
|
||||||
/// `Ok(T)` is an application result, including domain-failure union cases.
|
/// `Ok(T)` is an application result, including domain-failure union cases.
|
||||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||||
pub type OperationResult<T> = Result<T, HostError>;
|
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.
|
/// 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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct HostError {
|
pub struct HostError {
|
||||||
|
kind: HostErrorKind,
|
||||||
|
effect_guarantee: EffectGuarantee,
|
||||||
message: String,
|
message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HostError {
|
impl HostError {
|
||||||
/// Creates a host failure with a human-readable diagnostic.
|
/// Creates an internal Host failure with an explicit effect guarantee.
|
||||||
#[must_use]
|
#[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 {
|
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]
|
#[must_use]
|
||||||
pub fn message(&self) -> &str {
|
pub fn message(&self) -> &str {
|
||||||
&self.message
|
&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 {
|
impl Display for HostError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
formatter.write_str(&self.message)
|
formatter.write_str(&self.message)
|
||||||
@@ -200,12 +321,59 @@ pub enum DispatchError {
|
|||||||
Decode(CodecError),
|
Decode(CodecError),
|
||||||
/// The implementation reported a host/runtime failure.
|
/// The implementation reported a host/runtime failure.
|
||||||
Host(HostError),
|
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.
|
/// The Rust result could not be encoded.
|
||||||
Encode(CodecError),
|
Encode(CodecError),
|
||||||
/// The encoded result did not match the generated declaration.
|
/// The encoded result did not match the generated declaration.
|
||||||
InvalidResult(wip_protocol::ValidationError),
|
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 {
|
impl Display for DispatchError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
@@ -215,6 +383,7 @@ impl Display for DispatchError {
|
|||||||
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
||||||
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
||||||
Self::Host(error) => write!(formatter, "host operation 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::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
||||||
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
||||||
}
|
}
|
||||||
@@ -224,7 +393,7 @@ impl Display for DispatchError {
|
|||||||
impl Error for DispatchError {
|
impl Error for DispatchError {
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
match self {
|
match self {
|
||||||
Self::UnknownOperation(_) => None,
|
Self::UnknownOperation(_) | Self::Panic => None,
|
||||||
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
||||||
Self::Decode(error) | Self::Encode(error) => Some(error),
|
Self::Decode(error) | Self::Encode(error) => Some(error),
|
||||||
Self::Host(error) => Some(error),
|
Self::Host(error) => Some(error),
|
||||||
@@ -251,13 +420,101 @@ impl From<Bytes> for Vec<u8> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A typed protocol key/value entry.
|
/// A canonical absolute path to an entry in the current Worldspace.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
///
|
||||||
pub struct Entry<K, V> {
|
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
|
||||||
/// Entry key.
|
/// entry from a path such as `/articles/1`; application data associated with
|
||||||
pub key: K,
|
/// that entry belongs in an ordinary record alongside this value.
|
||||||
/// Entry value.
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub value: V,
|
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 {
|
impl WipType for bool {
|
||||||
@@ -426,52 +683,87 @@ impl WipType for JsonValue {
|
|||||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||||
|
|
||||||
fn encode(self) -> Result<Value, CodecError> {
|
fn encode(self) -> Result<Value, CodecError> {
|
||||||
validate_json(&self)?;
|
encode_json(self)
|
||||||
Ok(Value::Json(self))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||||
match value {
|
decode_json(value)
|
||||||
Value::Json(value) => {
|
}
|
||||||
validate_json(&value)?;
|
}
|
||||||
Ok(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 {
|
match value {
|
||||||
JsonValue::Integer(value) => ensure_safe_integer(*value),
|
Value::Unit => Ok(JsonValue::Null),
|
||||||
JsonValue::Number(value) => ensure_finite(*value),
|
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
|
||||||
JsonValue::Array(values) => {
|
Value::Integer(value) => {
|
||||||
for (index, value) in values.iter().enumerate() {
|
ensure_safe_integer(value)?;
|
||||||
validate_json(value).map_err(|error| error.at(index.to_string()))?;
|
Ok(JsonValue::Integer(value))
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
JsonValue::Object(members) => {
|
Value::Number(value) => {
|
||||||
let mut names = std::collections::HashSet::new();
|
ensure_finite(value)?;
|
||||||
for member in members {
|
Ok(JsonValue::Number(value))
|
||||||
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(())
|
|
||||||
}
|
}
|
||||||
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> {
|
impl<T: WipType> WipType for Vec<T> {
|
||||||
fn type_expr() -> TypeExpr {
|
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>) {
|
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 {
|
fn type_expr() -> TypeExpr {
|
||||||
TypeExpr::Entry {
|
TypeExpr::Entry
|
||||||
key: Box::new(K::type_expr()),
|
|
||||||
value: Box::new(V::type_expr()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||||
K::collect_declarations(declarations);
|
|
||||||
V::collect_declarations(declarations);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn encode(self) -> Result<Value, CodecError> {
|
fn encode(self) -> Result<Value, CodecError> {
|
||||||
Ok(Value::Entry {
|
validate_entry_path(&self.0)?;
|
||||||
key: Box::new(self.key.encode().map_err(|error| error.at("key"))?),
|
Ok(Value::String(self.0))
|
||||||
value: Box::new(self.value.encode().map_err(|error| error.at("value"))?),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||||
let Value::Entry { key, value } = value else {
|
let Value::String(path) = value else {
|
||||||
return Err(CodecError::expected("entry", &value));
|
return Err(CodecError::expected("entry path string", &value));
|
||||||
};
|
};
|
||||||
Ok(Self {
|
Self::new(path)
|
||||||
key: K::decode(*key).map_err(|error| error.at("key"))?,
|
|
||||||
value: V::decode(*value).map_err(|error| error.at("value"))?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.
|
/// Implementation details used by code emitted from the facade's macros.
|
||||||
///
|
///
|
||||||
/// These APIs are public only because macro expansions execute in the
|
/// 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.
|
/// and are not intended for direct use.
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub mod __private {
|
pub mod __private {
|
||||||
use std::collections::HashSet;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use wip_protocol::{
|
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
|
||||||
InterfaceDescriptor, NamedValue, ObjectId, OperationCall, OperationTarget, TypeDeclaration,
|
|
||||||
ValidationError, Value,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{CodecError, Documentation, WipType};
|
use crate::{CodecError, Documentation, WipType};
|
||||||
|
|
||||||
@@ -576,16 +859,9 @@ pub mod __private {
|
|||||||
pub fn validate_arguments(
|
pub fn validate_arguments(
|
||||||
descriptor: &InterfaceDescriptor,
|
descriptor: &InterfaceDescriptor,
|
||||||
operation: &str,
|
operation: &str,
|
||||||
arguments: &[NamedValue],
|
arguments: &BTreeMap<String, Value>,
|
||||||
) -> Result<(), ValidationError> {
|
) -> Result<(), ValidationError> {
|
||||||
descriptor.validate_call(&OperationCall {
|
descriptor.validate_arguments(operation, arguments)
|
||||||
target: OperationTarget {
|
|
||||||
object: ObjectId("<typed-dispatch>".into()),
|
|
||||||
interface: descriptor.name.clone(),
|
|
||||||
operation: operation.into(),
|
|
||||||
},
|
|
||||||
arguments: arguments.to_vec(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a codec error for a generated structural mismatch.
|
/// 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.
|
/// Decoder for a protocol record or operation's named argument collection.
|
||||||
pub struct RecordDecoder {
|
pub struct RecordDecoder {
|
||||||
fields: Vec<NamedValue>,
|
fields: BTreeMap<String, Value>,
|
||||||
seen: HashSet<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RecordDecoder {
|
impl RecordDecoder {
|
||||||
/// Starts decoding record fields or named operation arguments and
|
/// Starts decoding record fields or named operation arguments.
|
||||||
/// rejects duplicate names.
|
pub fn new(fields: BTreeMap<String, Value>) -> Self {
|
||||||
pub fn new(fields: Vec<NamedValue>) -> Result<Self, CodecError> {
|
Self { fields }
|
||||||
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 })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decodes a required field.
|
/// Decodes a required field.
|
||||||
@@ -639,23 +906,15 @@ pub mod __private {
|
|||||||
|
|
||||||
/// Rejects any fields that were not consumed by generated code.
|
/// Rejects any fields that were not consumed by generated code.
|
||||||
pub fn finish(self) -> Result<(), CodecError> {
|
pub fn finish(self) -> Result<(), CodecError> {
|
||||||
if let Some(field) = self.fields.first() {
|
if let Some(name) = self.fields.keys().next() {
|
||||||
Err(CodecError::new(format!("unknown field `{}`", field.name))
|
Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
|
||||||
.at(field.name.clone()))
|
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn take(&mut self, name: &str) -> Option<Value> {
|
fn take(&mut self, name: &str) -> Option<Value> {
|
||||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
self.fields.remove(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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
use wip_interface::wip_protocol::{
|
use std::collections::BTreeMap;
|
||||||
EnumDeclaration, JsonMember, JsonValue, NamedValue, RecordDeclaration, TypeDeclaration,
|
|
||||||
TypeExpr, UnionDeclaration, Value,
|
use wip_interface::wip_protocol::{TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, Value};
|
||||||
};
|
use wip_interface::{Bytes, Entry, JsonMember, JsonValue, WipType};
|
||||||
use wip_interface::{Bytes, Entry, WipType};
|
|
||||||
|
|
||||||
/// A request record.
|
/// A request record.
|
||||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||||
@@ -11,8 +10,8 @@ struct Request {
|
|||||||
title: String,
|
title: String,
|
||||||
/// Optional priority.
|
/// Optional priority.
|
||||||
priority: Option<i32>,
|
priority: Option<i32>,
|
||||||
/// Related entries.
|
/// Related Worldspace entries.
|
||||||
related: Vec<Entry<String, bool>>,
|
related: Vec<Entry>,
|
||||||
/// Opaque bytes.
|
/// Opaque bytes.
|
||||||
body: Bytes,
|
body: Bytes,
|
||||||
/// Arbitrary metadata.
|
/// Arbitrary metadata.
|
||||||
@@ -38,33 +37,53 @@ struct Receipt {
|
|||||||
/// Application-level publication outcome.
|
/// Application-level publication outcome.
|
||||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||||
enum PublishOutcome {
|
enum PublishOutcome {
|
||||||
|
/// Work has not completed and carries no payload.
|
||||||
|
Pending,
|
||||||
/// Application success.
|
/// Application success.
|
||||||
Published(Receipt),
|
Published(Receipt),
|
||||||
/// Domain rejection, not a host failure.
|
/// Domain rejection, not a host failure.
|
||||||
Rejected(String),
|
Rejected(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn field<'a>(record: &'a BTreeMap<String, Value>, name: &str) -> &'a Value {
|
||||||
|
record
|
||||||
|
.get(name)
|
||||||
|
.unwrap_or_else(|| panic!("missing `{name}`"))
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 {
|
let request = Request {
|
||||||
title: "hello".into(),
|
title: "hello".into(),
|
||||||
priority: None,
|
priority: None,
|
||||||
related: vec![Entry {
|
related: vec![Entry::new("/articles/1").unwrap()],
|
||||||
key: "/articles/1".into(),
|
|
||||||
value: true,
|
|
||||||
}],
|
|
||||||
body: Bytes(vec![1, 2, 3]),
|
body: Bytes(vec![1, 2, 3]),
|
||||||
metadata: JsonValue::Object(vec![JsonMember {
|
metadata: JsonValue::Object(vec![JsonMember {
|
||||||
name: "source".into(),
|
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 encoded = request.clone().encode().unwrap();
|
||||||
let Value::Record(fields) = &encoded else {
|
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);
|
assert_eq!(Request::decode(encoded).unwrap(), request);
|
||||||
|
|
||||||
let number = 42.5_f64;
|
let number = 42.5_f64;
|
||||||
@@ -77,92 +96,136 @@ fn supported_values_round_trip() {
|
|||||||
f32::decode(narrow_number.encode().unwrap()).unwrap(),
|
f32::decode(narrow_number.encode().unwrap()).unwrap(),
|
||||||
narrow_number
|
narrow_number
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn enums_are_strings_and_unions_are_discriminated_records() {
|
||||||
for color in [Color::Red, Color::Blue] {
|
for color in [Color::Red, Color::Blue] {
|
||||||
let encoded = color.clone().encode().unwrap();
|
let encoded = color.clone().encode().unwrap();
|
||||||
let decoded = Color::decode(encoded).unwrap();
|
assert!(matches!(encoded, Value::String(_)));
|
||||||
assert_eq!(decoded, color);
|
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 [
|
for outcome in [
|
||||||
|
PublishOutcome::Pending,
|
||||||
PublishOutcome::Published(Receipt { number: 7 }),
|
PublishOutcome::Published(Receipt { number: 7 }),
|
||||||
PublishOutcome::Rejected("policy".into()),
|
PublishOutcome::Rejected("policy".into()),
|
||||||
] {
|
] {
|
||||||
let encoded = outcome.clone().encode().unwrap();
|
let encoded = outcome.clone().encode().unwrap();
|
||||||
let decoded = PublishOutcome::decode(encoded).unwrap();
|
assert_eq!(PublishOutcome::decode(encoded).unwrap(), outcome);
|
||||||
assert_eq!(decoded, outcome);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn derived_declarations_include_docs_optionality_and_dependencies() {
|
fn derived_declarations_use_canonical_named_type_expressions() {
|
||||||
let mut declarations = Vec::new();
|
let mut declarations = Vec::new();
|
||||||
Request::collect_declarations(&mut declarations);
|
Request::collect_declarations(&mut declarations);
|
||||||
Color::collect_declarations(&mut declarations);
|
Color::collect_declarations(&mut declarations);
|
||||||
PublishOutcome::collect_declarations(&mut declarations);
|
PublishOutcome::collect_declarations(&mut declarations);
|
||||||
|
|
||||||
let TypeDeclaration::Record(RecordDeclaration {
|
let request = declarations
|
||||||
documentation,
|
.iter()
|
||||||
fields,
|
.find(|declaration| declaration.name == "Request")
|
||||||
..
|
.unwrap();
|
||||||
}) = &declarations[0]
|
assert_eq!(
|
||||||
else {
|
request.documentation.as_ref().unwrap().summary,
|
||||||
|
"A request record."
|
||||||
|
);
|
||||||
|
let TypeExpr::Record { fields } = &request.definition else {
|
||||||
panic!("Request must be a record declaration")
|
panic!("Request must be a record declaration")
|
||||||
};
|
};
|
||||||
assert_eq!(documentation.as_ref().unwrap().summary, "A request record.");
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fields[0].documentation.as_ref().unwrap().summary,
|
fields[0].documentation.as_ref().unwrap().summary,
|
||||||
"Required title."
|
"Required title."
|
||||||
);
|
);
|
||||||
assert!(!fields[0].optional);
|
assert!(fields[0].required);
|
||||||
assert!(fields[1].optional);
|
assert!(!fields[1].required);
|
||||||
assert_eq!(fields[1].ty, TypeExpr::Integer);
|
assert_eq!(fields[1].r#type, TypeExpr::Integer);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fields[2].ty,
|
fields[2].r#type,
|
||||||
TypeExpr::List(Box::new(TypeExpr::Entry {
|
TypeExpr::List {
|
||||||
key: Box::new(TypeExpr::String),
|
items: Box::new(TypeExpr::Entry),
|
||||||
value: Box::new(TypeExpr::Boolean),
|
}
|
||||||
}))
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let color = declarations
|
let color = declarations
|
||||||
.iter()
|
.iter()
|
||||||
.find(|declaration| declaration.name() == "Color")
|
.find(|declaration| declaration.name == "Color")
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let TypeDeclaration::Enum(EnumDeclaration { variants, .. }) = color else {
|
let TypeExpr::Enum { cases } = &color.definition else {
|
||||||
panic!("Color must be an enum declaration")
|
panic!("Color must be an enum declaration")
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
variants[0].documentation.as_ref().unwrap().summary,
|
cases[0].documentation.as_ref().unwrap().summary,
|
||||||
"Warm red."
|
"Warm red."
|
||||||
);
|
);
|
||||||
|
|
||||||
let outcome = declarations
|
let outcome = declarations
|
||||||
.iter()
|
.iter()
|
||||||
.find(|declaration| declaration.name() == "PublishOutcome")
|
.find(|declaration| declaration.name == "PublishOutcome")
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let TypeDeclaration::Union(UnionDeclaration { variants, .. }) = outcome else {
|
let TypeExpr::Union { cases } = &outcome.definition else {
|
||||||
panic!("PublishOutcome must be a union declaration")
|
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!(
|
assert!(
|
||||||
declarations
|
declarations
|
||||||
.iter()
|
.iter()
|
||||||
.any(|declaration| declaration.name() == "Receipt")
|
.any(|declaration| declaration.name == "Receipt")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn codecs_reject_invalid_boundaries() {
|
fn codecs_reject_invalid_boundaries_and_json_bytes() {
|
||||||
assert!(i64::MAX.encode().is_err());
|
assert!(i64::MAX.encode().is_err());
|
||||||
assert!(f64::NAN.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!(
|
assert!(
|
||||||
Request::decode(Value::Record(vec![NamedValue {
|
Request::decode(Value::Record(BTreeMap::from([(
|
||||||
name: "unknown".into(),
|
"unknown".into(),
|
||||||
value: Value::String("value".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()
|
.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 std::collections::BTreeMap;
|
||||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
|
||||||
|
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||||
|
use wip_interface::{
|
||||||
|
DispatchError, DispatchPhase, EffectGuarantee, HostError, HostErrorKind, OperationResult,
|
||||||
|
WipType, interface,
|
||||||
|
};
|
||||||
|
|
||||||
/// Publication request.
|
/// Publication request.
|
||||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||||
@@ -36,7 +41,7 @@ pub trait Catalog {
|
|||||||
note: Option<String>,
|
note: Option<String>,
|
||||||
) -> OperationResult<PublishOutcome>;
|
) -> OperationResult<PublishOutcome>;
|
||||||
|
|
||||||
/// Checks connectivity without returning an application value.
|
/// Checks connectivity without returning application data.
|
||||||
fn ping(&self) -> OperationResult<()>;
|
fn ping(&self) -> OperationResult<()>;
|
||||||
|
|
||||||
/// Demonstrates a host/runtime failure.
|
/// Demonstrates a host/runtime failure.
|
||||||
@@ -64,7 +69,10 @@ impl Catalog for AcceptingCatalog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn host_value(&self) -> OperationResult<String> {
|
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 {
|
struct PanickingCatalog;
|
||||||
NamedValue {
|
|
||||||
name: name.into(),
|
impl Catalog for PanickingCatalog {
|
||||||
value,
|
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> {
|
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||||
let mut arguments = vec![named(
|
let mut arguments = BTreeMap::from([(
|
||||||
"request",
|
"request".into(),
|
||||||
PublishRequest {
|
PublishRequest {
|
||||||
title: "example".into(),
|
title: "example".into(),
|
||||||
}
|
}
|
||||||
.encode()
|
.encode()
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)];
|
)]);
|
||||||
if with_note {
|
if with_note {
|
||||||
arguments.push(named("note", Value::String("audit".into())));
|
arguments.insert("note".into(), Value::String("audit".into()));
|
||||||
}
|
}
|
||||||
arguments
|
arguments
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 first = CatalogDefinition::descriptor();
|
||||||
let second = CatalogDefinition::descriptor();
|
let second = CatalogDefinition::descriptor();
|
||||||
assert_eq!(first, second);
|
assert_eq!(first, second);
|
||||||
first.validate().unwrap();
|
first.validate().unwrap();
|
||||||
|
|
||||||
assert_eq!(first.name, "Catalog");
|
assert_eq!(first.format, INTERFACE_FORMAT_V1);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
first.documentation.as_ref().unwrap().summary,
|
first.documentation.as_ref().unwrap().summary,
|
||||||
"Catalog editing capability."
|
"Catalog editing capability."
|
||||||
@@ -139,84 +160,110 @@ fn descriptor_is_generated_only_from_the_trait_declaration() {
|
|||||||
.summary,
|
.summary,
|
||||||
"Item to publish."
|
"Item to publish."
|
||||||
);
|
);
|
||||||
assert!(!publish.parameters[0].optional);
|
assert!(publish.parameters[0].required);
|
||||||
assert!(publish.parameters[1].optional);
|
assert!(!publish.parameters[1].required);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
publish
|
publish.returns.documentation.as_ref().unwrap().summary,
|
||||||
.returns
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.documentation
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.summary,
|
|
||||||
"The application publication outcome."
|
"The application publication outcome."
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
publish.returns.as_ref().unwrap().ty,
|
publish.returns.r#type,
|
||||||
TypeExpr::Named("PublishOutcome".into())
|
TypeExpr::Named {
|
||||||
|
name: "PublishOutcome".into(),
|
||||||
|
}
|
||||||
);
|
);
|
||||||
assert!(first.operations[1].returns.is_none());
|
assert_eq!(first.operations[1].returns.r#type, TypeExpr::Unit);
|
||||||
assert!(
|
assert!(
|
||||||
first
|
first
|
||||||
.declarations
|
.types
|
||||||
.iter()
|
.iter()
|
||||||
.any(|declaration| matches!(declaration, TypeDeclaration::Record(_)))
|
.any(|declaration| matches!(declaration.definition, TypeExpr::Record { .. }))
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
first
|
first
|
||||||
.declarations
|
.types
|
||||||
.iter()
|
.iter()
|
||||||
.any(|declaration| matches!(declaration, TypeDeclaration::Union(_)))
|
.any(|declaration| matches!(declaration.definition, TypeExpr::Union { .. }))
|
||||||
);
|
);
|
||||||
|
|
||||||
// Both implementation types satisfy the same generated dispatch boundary;
|
// Both implementation types satisfy one immutable generated definition;
|
||||||
// neither can affect the descriptor shape.
|
// implementation selection cannot contribute fields to the descriptor.
|
||||||
fn accepts_definition<T: Catalog>(_: &T) {}
|
fn accepts_definition<T: Catalog>(_: &T) {}
|
||||||
accepts_definition(&AcceptingCatalog);
|
accepts_definition(&AcceptingCatalog);
|
||||||
accepts_definition(&RejectingCatalog);
|
accepts_definition(&RejectingCatalog);
|
||||||
|
assert_eq!(CatalogDefinition::descriptor(), first);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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();
|
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
|
||||||
assert_eq!(decoded.request.title, "example");
|
assert_eq!(decoded.request.title, "example");
|
||||||
assert_eq!(decoded.note, None);
|
assert_eq!(decoded.note, None);
|
||||||
|
|
||||||
let encoded = CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into()))
|
let encoded =
|
||||||
.unwrap()
|
CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into())).unwrap();
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
PublishOutcome::decode(encoded).unwrap(),
|
PublishOutcome::decode(encoded).unwrap(),
|
||||||
PublishOutcome::Rejected("domain".into())
|
PublishOutcome::Rejected("domain".into())
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
CatalogPingArguments::encode_result(()).unwrap(),
|
||||||
|
Value::Unit
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||||
let value = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true))
|
let value =
|
||||||
.unwrap()
|
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true)).unwrap();
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
PublishOutcome::decode(value).unwrap(),
|
PublishOutcome::decode(value).unwrap(),
|
||||||
PublishOutcome::Published(true)
|
PublishOutcome::Published(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", vec![]).unwrap(),
|
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", BTreeMap::new()).unwrap(),
|
||||||
None
|
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!(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();
|
let host =
|
||||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
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"));
|
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.
|
/// Operations whose distinct source names normalize to the same PascalCase.
|
||||||
#[interface]
|
#[interface]
|
||||||
pub trait DistinctOperations {
|
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[0].name, "item");
|
||||||
assert_eq!(descriptor.operations[1].name, "item_");
|
assert_eq!(descriptor.operations[1].name, "item_");
|
||||||
|
|
||||||
let first = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", vec![])
|
let first =
|
||||||
.unwrap()
|
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", BTreeMap::new())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let second = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", vec![])
|
let second =
|
||||||
.unwrap()
|
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", BTreeMap::new())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(first, Value::String("item".into()));
|
assert_eq!(first, Value::String("item".into()));
|
||||||
assert_eq!(second, 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;
|
use wip_interface::WipType;
|
||||||
|
|
||||||
#[derive(WipType)]
|
#[derive(WipType)]
|
||||||
enum MixedEnum {
|
enum UnsupportedEnum {
|
||||||
Empty,
|
Empty,
|
||||||
Payload(String),
|
Payload { value: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {}
|
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
|
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:4:1
|
--> 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>;
|
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||||
|
|
|
|
||||||
= help: the following other types implement trait `WipType`:
|
help: the trait `WipType` is implemented for `()`
|
||||||
JsonValue
|
--> src/lib.rs
|
||||||
Vec<T>
|
|
|
||||||
bool
|
| impl WipType for () {
|
||||||
f32
|
| ^^^^^^^^^^^^^^^^^^^
|
||||||
f64
|
|
||||||
i128
|
|
||||||
i16
|
|
||||||
i32
|
|
||||||
and $N others
|
|
||||||
|
|
||||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||||
--> tests/ui/unsupported_type.rs:5:26
|
--> 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>;
|
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||||
|
|
|
|
||||||
= help: the following other types implement trait `WipType`:
|
help: the trait `WipType` is implemented for `()`
|
||||||
JsonValue
|
--> src/lib.rs
|
||||||
Vec<T>
|
|
|
||||||
bool
|
| impl WipType for () {
|
||||||
f32
|
| ^^^^^^^^^^^^^^^^^^^
|
||||||
f64
|
|
||||||
i128
|
|
||||||
i16
|
|
||||||
i32
|
|
||||||
and $N others
|
|
||||||
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
||||||
--> src/lib.rs
|
--> src/lib.rs
|
||||||
|
|
|
|
||||||
|
|||||||
@@ -8,79 +8,65 @@ pub enum NameNamespace {
|
|||||||
TypeDeclaration,
|
TypeDeclaration,
|
||||||
/// Operations in an interface descriptor.
|
/// Operations in an interface descriptor.
|
||||||
Operation,
|
Operation,
|
||||||
/// Fields in a record declaration.
|
/// Fields in an inline or named record type.
|
||||||
Field,
|
Field,
|
||||||
/// Parameters in an operation declaration.
|
/// Parameters in an operation declaration.
|
||||||
Parameter,
|
Parameter,
|
||||||
/// Variants in an enum declaration.
|
/// Cases in an enum type.
|
||||||
EnumVariant,
|
EnumCase,
|
||||||
/// Variants in a union declaration.
|
/// Cases in a union type.
|
||||||
UnionVariant,
|
UnionCase,
|
||||||
/// Fields supplied in a record value.
|
/// Child object names beneath one tree node.
|
||||||
RecordValueField,
|
ChildObject,
|
||||||
/// Arguments supplied in an operation call.
|
|
||||||
Argument,
|
|
||||||
/// Members in a logical JSON object.
|
|
||||||
JsonMember,
|
|
||||||
/// Descriptors in an interface observation.
|
|
||||||
InterfaceDescriptor,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Structural kind of a logical protocol value.
|
/// Structural kind of a schema-neutral logical value.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ValueKind {
|
pub enum ValueKind {
|
||||||
/// String value.
|
/// Unit value.
|
||||||
String,
|
Unit,
|
||||||
/// Boolean value.
|
/// Boolean value.
|
||||||
Boolean,
|
Boolean,
|
||||||
/// Integer value.
|
/// Integer value.
|
||||||
Integer,
|
Integer,
|
||||||
/// Floating-point number value.
|
/// Floating-point number value.
|
||||||
Number,
|
Number,
|
||||||
|
/// String value.
|
||||||
|
String,
|
||||||
/// Byte sequence.
|
/// Byte sequence.
|
||||||
Bytes,
|
Bytes,
|
||||||
/// List value.
|
|
||||||
List,
|
|
||||||
/// Key/value entry.
|
|
||||||
Entry,
|
|
||||||
/// Record value.
|
/// Record value.
|
||||||
Record,
|
Record,
|
||||||
/// Enum value.
|
/// List value.
|
||||||
Enum,
|
List,
|
||||||
/// Tagged-union value.
|
|
||||||
Union,
|
|
||||||
/// Logical JSON value.
|
|
||||||
Json,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A typed segment identifying a declaration or value location.
|
/// A typed segment identifying a declaration or value location.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum PathSegment {
|
pub enum PathSegment {
|
||||||
/// Interface descriptor.
|
/// Descriptor root.
|
||||||
Interface(String),
|
Descriptor,
|
||||||
/// Named type declaration.
|
/// Named type declaration.
|
||||||
Declaration(String),
|
Declaration(String),
|
||||||
/// Operation declaration or call.
|
/// Operation declaration or call.
|
||||||
Operation(String),
|
Operation(String),
|
||||||
/// Record field declaration or value.
|
/// Record field declaration or value.
|
||||||
Field(String),
|
Field(String),
|
||||||
/// Operation parameter declaration or argument.
|
/// Operation parameter or argument.
|
||||||
Parameter(String),
|
Parameter(String),
|
||||||
/// Enum or union variant.
|
/// Enum or union case.
|
||||||
Variant(String),
|
Case(String),
|
||||||
/// List or JSON array index.
|
/// List index.
|
||||||
Index(usize),
|
Index(usize),
|
||||||
/// Entry key.
|
|
||||||
EntryKey,
|
|
||||||
/// Entry value.
|
|
||||||
EntryValue,
|
|
||||||
/// Operation return value.
|
/// Operation return value.
|
||||||
Return,
|
Return,
|
||||||
/// JSON object member.
|
/// Object at a Worldspace path.
|
||||||
JsonMember(String),
|
Object(String),
|
||||||
|
/// Child object in an observation response.
|
||||||
|
Child(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Machine-readable reason why protocol validation failed.
|
/// Machine-readable reason why logical protocol validation failed.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum ValidationErrorKind {
|
pub enum ValidationErrorKind {
|
||||||
/// A name occurred more than once in one namespace.
|
/// A name occurred more than once in one namespace.
|
||||||
@@ -117,11 +103,15 @@ pub enum ValidationErrorKind {
|
|||||||
/// Missing field name.
|
/// Missing field name.
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
/// An enum or union value selected an undeclared variant.
|
/// An enum or union selected an undeclared case.
|
||||||
UnknownVariant {
|
UnknownCase {
|
||||||
/// Unknown variant name.
|
/// Unknown case name.
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
|
/// A payload-bearing union case omitted `value`.
|
||||||
|
MissingUnionPayload,
|
||||||
|
/// A payload-free union case supplied `value`.
|
||||||
|
UnexpectedUnionPayload,
|
||||||
/// An operation call contains an undeclared argument.
|
/// An operation call contains an undeclared argument.
|
||||||
UnknownParameter {
|
UnknownParameter {
|
||||||
/// Unknown parameter name.
|
/// Unknown parameter name.
|
||||||
@@ -132,44 +122,64 @@ pub enum ValidationErrorKind {
|
|||||||
/// Missing parameter name.
|
/// Missing parameter name.
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
/// An integer is outside the JavaScript-lossless range.
|
/// An operation is not declared by the descriptor.
|
||||||
|
UnknownOperation {
|
||||||
|
/// Unknown operation name.
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
|
/// An integer is outside the interoperable safe range.
|
||||||
IntegerOutOfRange {
|
IntegerOutOfRange {
|
||||||
/// Rejected integer.
|
/// Rejected integer.
|
||||||
value: i64,
|
value: i64,
|
||||||
},
|
},
|
||||||
/// A numeric value is NaN or infinite.
|
/// A numeric value is NaN or infinite.
|
||||||
NonFiniteNumber,
|
NonFiniteNumber,
|
||||||
|
/// A JSON-interpreted value tree contains protocol bytes.
|
||||||
|
BytesInJson,
|
||||||
|
/// An object name is not a valid root or non-root path segment.
|
||||||
|
InvalidObjectName {
|
||||||
|
/// Rejected object name.
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
/// An object's ordered interface set contains a duplicate.
|
/// An object's ordered interface set contains a duplicate.
|
||||||
DuplicateInterface {
|
DuplicateInterface {
|
||||||
/// Duplicate interface name.
|
/// Duplicate opaque interface reference.
|
||||||
name: String,
|
reference: String,
|
||||||
},
|
},
|
||||||
/// An observation omits a descriptor named by its object.
|
/// A string is not a canonical absolute Worldspace path.
|
||||||
MissingInterfaceDescriptor {
|
InvalidPath {
|
||||||
/// Missing interface name.
|
/// Rejected path.
|
||||||
name: String,
|
path: String,
|
||||||
},
|
},
|
||||||
/// An observation contains a descriptor not named by its object.
|
/// An object name does not match the path where it was observed.
|
||||||
UnexpectedInterfaceDescriptor {
|
ObjectNameMismatch {
|
||||||
/// Unexpected interface name.
|
/// Name required by the observation path.
|
||||||
name: String,
|
|
||||||
},
|
|
||||||
/// A call targets an interface other than the descriptor being used.
|
|
||||||
InterfaceMismatch {
|
|
||||||
/// Descriptor interface name.
|
|
||||||
expected: String,
|
expected: String,
|
||||||
/// Call target interface name.
|
/// Name supplied by the object.
|
||||||
actual: String,
|
actual: String,
|
||||||
},
|
},
|
||||||
/// An operation is not declared by the interface.
|
/// Equivalent ref/validator observations disagree on object representation.
|
||||||
UnknownOperation {
|
InconsistentObjectObservation {
|
||||||
/// Unknown operation name.
|
/// Shared opaque object reference.
|
||||||
name: String,
|
reference: String,
|
||||||
|
},
|
||||||
|
/// An observation omitted children before reaching the requested depth.
|
||||||
|
ChildrenMissingBeforeDepth {
|
||||||
|
/// Node depth where children were required.
|
||||||
|
depth: u32,
|
||||||
|
},
|
||||||
|
/// An observation included children at the requested depth boundary.
|
||||||
|
ChildrenAtDepthBoundary {
|
||||||
|
/// Boundary depth where children must be unobserved.
|
||||||
|
depth: u32,
|
||||||
|
},
|
||||||
|
/// A response refers to a different interface than its request.
|
||||||
|
InterfaceResponseMismatch {
|
||||||
|
/// Requested opaque reference.
|
||||||
|
expected: String,
|
||||||
|
/// Returned opaque reference.
|
||||||
|
actual: String,
|
||||||
},
|
},
|
||||||
/// A no-return operation produced a value.
|
|
||||||
UnexpectedReturnValue,
|
|
||||||
/// An operation with a return declaration produced no value.
|
|
||||||
MissingReturnValue,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A validation failure with a typed path to the failing location.
|
/// A validation failure with a typed path to the failing location.
|
||||||
@@ -211,30 +221,150 @@ impl Display for ValidationError {
|
|||||||
|
|
||||||
impl Error for ValidationError {}
|
impl Error for ValidationError {}
|
||||||
|
|
||||||
/// Stable category of an error returned by a protocol host runtime.
|
/// One core interaction whose failure codes form a closed set.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ProtocolErrorCategory {
|
pub enum ProtocolInteraction {
|
||||||
/// The request is structurally invalid.
|
/// Observe one object and its indexable descendants to a requested depth.
|
||||||
InvalidRequest,
|
Observe,
|
||||||
/// The target object is not published.
|
/// Fetch one interface descriptor by its opaque reference.
|
||||||
ObjectNotFound,
|
FetchInterface,
|
||||||
/// The target interface is not implemented by the object.
|
/// Invoke one operation on a path-targeted object.
|
||||||
InterfaceNotFound,
|
CallOperation,
|
||||||
/// 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,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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, FetchInterface, Observe};
|
||||||
|
|
||||||
|
match (interaction, self) {
|
||||||
|
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
|
||||||
|
(Observe, NotFound) => true,
|
||||||
|
(FetchInterface, InterfaceNotFound) => true,
|
||||||
|
(
|
||||||
|
CallOperation,
|
||||||
|
NotFound
|
||||||
|
| InterfaceMismatch
|
||||||
|
| OperationNotFound
|
||||||
|
| InvalidArguments
|
||||||
|
| ValidatorRequired
|
||||||
|
| ValidatorMismatch
|
||||||
|
| InterfaceValidatorRequired
|
||||||
|
| InterfaceValidatorMismatch
|
||||||
|
| PermissionDenied
|
||||||
|
| OperationOutcomeUnknown,
|
||||||
|
) => true,
|
||||||
|
(
|
||||||
|
_,
|
||||||
|
NotFound
|
||||||
|
| InterfaceNotFound
|
||||||
|
| InterfaceMismatch
|
||||||
|
| OperationNotFound
|
||||||
|
| InvalidArguments
|
||||||
|
| ValidatorRequired
|
||||||
|
| ValidatorMismatch
|
||||||
|
| InterfaceValidatorRequired
|
||||||
|
| InterfaceValidatorMismatch
|
||||||
|
| PermissionDenied
|
||||||
|
| OperationOutcomeUnknown,
|
||||||
|
) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transport-independent protocol failure.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ProtocolError {
|
pub struct ProtocolError {
|
||||||
/// Stable programmatic category.
|
/// Stable programmatic code. Consumers must branch on this field.
|
||||||
pub category: ProtocolErrorCategory,
|
pub code: ProtocolErrorCode,
|
||||||
/// Human-readable diagnostic. Consumers must not branch on this text.
|
/// Bounded human-readable diagnostic. Consumers must not branch on it.
|
||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Display for ProtocolError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"protocol failure ({:?}): {}",
|
||||||
|
self.code, self.message
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ProtocolError {}
|
||||||
|
|||||||
@@ -1,9 +1,44 @@
|
|||||||
//! Transport-independent logical types for the Web Interface Protocol (WIP).
|
//! Canonical transport-independent logical types for the Web Interface Protocol.
|
||||||
//!
|
//!
|
||||||
//! This crate deliberately models interface declarations, published objects,
|
//! This crate follows the Core Model and `3-protocol.md` without assigning HTTP
|
||||||
//! operation calls, and operation results without assigning them HTTP routes,
|
//! routes, methods, headers, URL encodings, or JSON envelopes. The correspondence
|
||||||
//! methods, headers, or JSON envelopes. A transport can encode these values,
|
//! between canonical logical concepts and this crate is direct:
|
||||||
//! but the encoding is outside this crate's contract.
|
//!
|
||||||
|
//! | Canonical protocol concept | Rust API |
|
||||||
|
//! | --- | --- |
|
||||||
|
//! | Object projection and ordered interface set | [`Object`] |
|
||||||
|
//! | Optional object identity / state precondition | `Object::ref` / [`Object::validator`] |
|
||||||
|
//! | Interface Descriptor | [`InterfaceDescriptor`] |
|
||||||
|
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
|
||||||
|
//! | Schema-neutral primitive/composite value | [`Value`] |
|
||||||
|
//! | `observe` | [`ObserveRequest`] / [`ObserveResponse`] |
|
||||||
|
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
||||||
|
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
||||||
|
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
||||||
|
//! | Stable Host failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
||||||
|
//! | Per-interaction allowed failure codes | [`ProtocolInteraction`] / [`ProtocolErrorCode::is_allowed_for`] |
|
||||||
|
//!
|
||||||
|
//! [`ProtocolErrorCode`] is a closed set of Host-returned wire failures. After a
|
||||||
|
//! Client receives a response, an invalid Object, Descriptor, operation result,
|
||||||
|
//! malformed error, or error code disallowed by [`ProtocolInteraction`] is a
|
||||||
|
//! Client-local `InvalidResponse`, not another wire error. A descriptor whose
|
||||||
|
//! `format` is not supported is a Client-local `UnsupportedDescriptorFormat`.
|
||||||
|
//!
|
||||||
|
//! For `call_operation`, [`ProtocolErrorCode::Internal`] and
|
||||||
|
//! [`ProtocolErrorCode::ResourceLimitExceeded`] guarantee that the operation did
|
||||||
|
//! not run or that all effects were rolled back. Only
|
||||||
|
//! [`ProtocolErrorCode::OperationOutcomeUnknown`] means the Host cannot make that
|
||||||
|
//! guarantee; Clients must not automatically retry it.
|
||||||
|
//!
|
||||||
|
//! Paths, object refs, interface refs, and validators remain separate concepts.
|
||||||
|
//! They are represented by ordinary protocol strings/bytes in the corresponding
|
||||||
|
//! fields. In particular, object refs are optional, operation targeting uses a
|
||||||
|
//! path, and this crate defines no interaction that fetches an object by ref.
|
||||||
|
//!
|
||||||
|
//! [`Value`] contains only the canonical raw value kinds. A descriptor interprets
|
||||||
|
//! enum values as strings, entries as canonical-path strings, and unions as
|
||||||
|
//! records with a `$case` string plus an optional `value` payload. JSON uses the
|
||||||
|
//! same value tree (`Unit` is JSON null) and rejects bytes.
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
@@ -12,19 +47,32 @@ mod model;
|
|||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub use error::{
|
pub use error::{
|
||||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCategory, ValidationError,
|
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
ValidationErrorKind, ValueKind,
|
ValidationError, ValidationErrorKind, ValueKind,
|
||||||
};
|
};
|
||||||
pub use model::{
|
pub use model::{
|
||||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
InterfaceObservation, JsonMember, JsonValue, NamedValue, Object, ObjectId, OperationCall,
|
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object,
|
||||||
OperationDeclaration, OperationOutcome, OperationResult, OperationTarget, ParameterDeclaration,
|
ObjectObservation, ObserveRequest, ObserveResponse, OperationDeclaration, ParameterDeclaration,
|
||||||
RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr, UnionDeclaration,
|
ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||||
UnionVariantDeclaration, Value,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Largest integer that is exactly interoperable with a JavaScript `Number`.
|
/// Validates a canonical absolute Worldspace path.
|
||||||
|
pub fn validate_path(path: &str) -> Result<(), ValidationError> {
|
||||||
|
validation::validate_path(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Canonical format identifier for the first Interface Descriptor format.
|
||||||
|
pub const INTERFACE_FORMAT_V1: &str = "wip-interface/1";
|
||||||
|
|
||||||
|
/// Discriminator field used by a union's raw record value.
|
||||||
|
pub const UNION_CASE_FIELD: &str = "$case";
|
||||||
|
|
||||||
|
/// Optional payload field used by a union's raw record value.
|
||||||
|
pub const UNION_VALUE_FIELD: &str = "value";
|
||||||
|
|
||||||
|
/// Largest integer exactly interoperable with a JavaScript `Number`.
|
||||||
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
||||||
|
|
||||||
/// Smallest integer that is exactly interoperable with a JavaScript `Number`.
|
/// Smallest integer exactly interoperable with a JavaScript `Number`.
|
||||||
pub const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER;
|
pub const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER;
|
||||||
|
|||||||
+273
-253
@@ -1,6 +1,8 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use crate::{ProtocolError, ValidationError};
|
use crate::{ProtocolError, ValidationError};
|
||||||
|
|
||||||
/// Human-readable documentation attached to a protocol declaration.
|
/// Human-readable plain-text documentation attached to a protocol declaration.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
pub struct Documentation {
|
pub struct Documentation {
|
||||||
/// A short, self-contained description.
|
/// A short, self-contained description.
|
||||||
@@ -9,242 +11,194 @@ pub struct Documentation {
|
|||||||
pub details: Option<String>,
|
pub details: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stable logical identity of a published object.
|
/// The protocol projection currently published at one Worldspace path.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct ObjectId(pub String);
|
|
||||||
|
|
||||||
/// A published object and the ordered set of interfaces it implements.
|
|
||||||
///
|
///
|
||||||
/// The vector order is significant. Call [`Object::validate`] before
|
/// `name` is a path segment, `interfaces` is an ordered set of opaque interface
|
||||||
/// publication to reject duplicate interface names.
|
/// references, `r#ref` is optional object identity, and `validator` is an
|
||||||
|
/// independent optional observation precondition. In particular, neither the
|
||||||
|
/// path nor `r#ref` is a mandatory object identifier.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Object {
|
pub struct Object {
|
||||||
/// Logical object identity.
|
/// Path-segment name. The root object's name is empty.
|
||||||
pub id: ObjectId,
|
pub name: String,
|
||||||
/// Interface names in publication order.
|
/// Short public description of the object.
|
||||||
|
pub description: Option<String>,
|
||||||
|
/// Opaque interface references in host publication order.
|
||||||
pub interfaces: Vec<String>,
|
pub interfaces: Vec<String>,
|
||||||
}
|
/// Optional opaque identity within one client-facing Worldspace.
|
||||||
|
pub r#ref: Option<String>,
|
||||||
/// A complete logical observation of an object and its interface descriptors.
|
/// Optional opaque validator for the object's observed state.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
pub validator: Option<Vec<u8>>,
|
||||||
pub struct InterfaceObservation {
|
|
||||||
/// Observed object.
|
|
||||||
pub object: Object,
|
|
||||||
/// Descriptors corresponding to `object.interfaces`.
|
|
||||||
pub descriptors: Vec<InterfaceDescriptor>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport-independent description of one interface.
|
/// Transport-independent description of one interface.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
///
|
||||||
|
/// Interface identity is supplied by interaction fields such as
|
||||||
|
/// [`FetchInterfaceResponse::interface`], not embedded in the descriptor.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct InterfaceDescriptor {
|
pub struct InterfaceDescriptor {
|
||||||
/// Interface name.
|
/// Descriptor format version understood by clients and hosts.
|
||||||
pub name: String,
|
pub format: String,
|
||||||
/// Optional interface documentation.
|
/// Optional interface documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Named type declarations local to this descriptor.
|
/// Named declarations local to this descriptor.
|
||||||
pub declarations: Vec<TypeDeclaration>,
|
pub types: Vec<TypeDeclaration>,
|
||||||
/// Operations exposed by this interface.
|
/// Operations exposed by this interface.
|
||||||
pub operations: Vec<OperationDeclaration>,
|
pub operations: Vec<OperationDeclaration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A named type declaration local to an interface descriptor.
|
/// A descriptor-local named type declaration.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum TypeDeclaration {
|
pub struct TypeDeclaration {
|
||||||
/// A record declaration.
|
|
||||||
Record(RecordDeclaration),
|
|
||||||
/// An enumeration declaration.
|
|
||||||
Enum(EnumDeclaration),
|
|
||||||
/// A tagged union declaration.
|
|
||||||
Union(UnionDeclaration),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TypeDeclaration {
|
|
||||||
/// Returns the descriptor-local declaration name.
|
|
||||||
#[must_use]
|
|
||||||
pub fn name(&self) -> &str {
|
|
||||||
match self {
|
|
||||||
Self::Record(declaration) => &declaration.name,
|
|
||||||
Self::Enum(declaration) => &declaration.name,
|
|
||||||
Self::Union(declaration) => &declaration.name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Declaration of a record with named fields.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct RecordDeclaration {
|
|
||||||
/// Descriptor-local type name.
|
/// Descriptor-local type name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Optional record documentation.
|
/// Optional type documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Fields in declaration order.
|
/// Definition associated with `name`.
|
||||||
pub fields: Vec<FieldDeclaration>,
|
pub definition: TypeExpr,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A type expression used by declarations, fields, parameters, and returns.
|
||||||
|
///
|
||||||
|
/// [`TypeExpr::Named`] references are resolved only within the containing
|
||||||
|
/// descriptor. Recursive references, including recursion through lists,
|
||||||
|
/// records, and unions, are invalid.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum TypeExpr {
|
||||||
|
/// A value carrying no data.
|
||||||
|
Unit,
|
||||||
|
/// A boolean.
|
||||||
|
Boolean,
|
||||||
|
/// A JavaScript-lossless signed integer.
|
||||||
|
Integer,
|
||||||
|
/// A finite IEEE-754 binary64 number.
|
||||||
|
Number,
|
||||||
|
/// A Unicode string.
|
||||||
|
String,
|
||||||
|
/// An opaque byte sequence.
|
||||||
|
Bytes,
|
||||||
|
/// A schema-opaque JSON-compatible value tree.
|
||||||
|
Json,
|
||||||
|
/// A canonical absolute Worldspace path represented by a string value.
|
||||||
|
Entry,
|
||||||
|
/// A descriptor-local named declaration.
|
||||||
|
Named {
|
||||||
|
/// Referenced declaration name.
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
|
/// A record with named fields.
|
||||||
|
Record {
|
||||||
|
/// Fields in declaration order.
|
||||||
|
fields: Vec<FieldDeclaration>,
|
||||||
|
},
|
||||||
|
/// An ordered list.
|
||||||
|
List {
|
||||||
|
/// Type of every list item.
|
||||||
|
items: Box<TypeExpr>,
|
||||||
|
},
|
||||||
|
/// A closed set of payload-free cases represented by strings.
|
||||||
|
Enum {
|
||||||
|
/// Cases in declaration order.
|
||||||
|
cases: Vec<EnumCase>,
|
||||||
|
},
|
||||||
|
/// A discriminated union represented by a record.
|
||||||
|
Union {
|
||||||
|
/// Cases in declaration order.
|
||||||
|
cases: Vec<UnionCase>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of a record field.
|
/// Declaration of a record field.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct FieldDeclaration {
|
pub struct FieldDeclaration {
|
||||||
/// Field name.
|
/// Field name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
/// Whether the field must be present.
|
||||||
|
pub required: bool,
|
||||||
/// Optional field documentation.
|
/// Optional field documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Field value type.
|
/// Field value type.
|
||||||
pub ty: TypeExpr,
|
pub r#type: TypeExpr,
|
||||||
/// Whether the field may be omitted.
|
|
||||||
///
|
|
||||||
/// Optionality represents absence, not a `null` value.
|
|
||||||
pub optional: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of an enumeration.
|
/// One payload-free enum case.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct EnumDeclaration {
|
pub struct EnumCase {
|
||||||
/// Descriptor-local type name.
|
/// Case name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Optional enum documentation.
|
/// Optional case documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Allowed variants in declaration order.
|
|
||||||
pub variants: Vec<EnumVariantDeclaration>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of one enumeration variant.
|
/// One union case with zero or one payload.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct EnumVariantDeclaration {
|
pub struct UnionCase {
|
||||||
/// Variant name.
|
/// Case name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Optional variant documentation.
|
/// Optional case documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
}
|
/// Optional payload type.
|
||||||
|
pub payload: Option<TypeExpr>,
|
||||||
/// Declaration of a tagged union.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct UnionDeclaration {
|
|
||||||
/// Descriptor-local type name.
|
|
||||||
pub name: String,
|
|
||||||
/// Optional union documentation.
|
|
||||||
pub documentation: Option<Documentation>,
|
|
||||||
/// Allowed tagged variants in declaration order.
|
|
||||||
pub variants: Vec<UnionVariantDeclaration>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Declaration of one tagged-union variant.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct UnionVariantDeclaration {
|
|
||||||
/// Variant tag.
|
|
||||||
pub name: String,
|
|
||||||
/// Optional variant documentation.
|
|
||||||
pub documentation: Option<Documentation>,
|
|
||||||
/// Payload type.
|
|
||||||
pub ty: TypeExpr,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A type expression used by fields, parameters, returns, and union payloads.
|
|
||||||
///
|
|
||||||
/// `Named` references are resolved only within the containing descriptor.
|
|
||||||
/// Optional values are represented by the containing field or parameter and
|
|
||||||
/// therefore are intentionally not a type expression.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum TypeExpr {
|
|
||||||
/// A UTF-8 string.
|
|
||||||
String,
|
|
||||||
/// A boolean.
|
|
||||||
Boolean,
|
|
||||||
/// A JavaScript-lossless integer.
|
|
||||||
Integer,
|
|
||||||
/// A finite IEEE-754 double precision number.
|
|
||||||
Number,
|
|
||||||
/// An opaque byte sequence.
|
|
||||||
Bytes,
|
|
||||||
/// An ordered sequence of values.
|
|
||||||
List(Box<TypeExpr>),
|
|
||||||
/// A key/value entry.
|
|
||||||
Entry {
|
|
||||||
/// Entry key type.
|
|
||||||
key: Box<TypeExpr>,
|
|
||||||
/// Entry value type.
|
|
||||||
value: Box<TypeExpr>,
|
|
||||||
},
|
|
||||||
/// A logical JSON value.
|
|
||||||
Json,
|
|
||||||
/// A descriptor-local named declaration.
|
|
||||||
Named(String),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of one interface operation.
|
/// Declaration of one interface operation.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct OperationDeclaration {
|
pub struct OperationDeclaration {
|
||||||
/// Operation name, unique within its interface.
|
/// Operation name, unique within its descriptor.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Optional operation documentation.
|
/// Optional operation documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Parameters in declaration order.
|
/// Parameters in declaration order.
|
||||||
pub parameters: Vec<ParameterDeclaration>,
|
pub parameters: Vec<ParameterDeclaration>,
|
||||||
/// Return declaration, or `None` for an operation with no return value.
|
/// Return declaration. No-data operations return [`TypeExpr::Unit`].
|
||||||
pub returns: Option<ReturnDeclaration>,
|
pub returns: ReturnDeclaration,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of one operation parameter.
|
/// Declaration of one operation parameter.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ParameterDeclaration {
|
pub struct ParameterDeclaration {
|
||||||
/// Parameter name.
|
/// Parameter name.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
/// Whether the parameter must be present.
|
||||||
|
pub required: bool,
|
||||||
/// Optional parameter documentation.
|
/// Optional parameter documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Parameter value type.
|
/// Parameter value type.
|
||||||
pub ty: TypeExpr,
|
pub r#type: TypeExpr,
|
||||||
/// Whether the parameter may be omitted.
|
|
||||||
///
|
|
||||||
/// Optionality represents absence, not a `null` value.
|
|
||||||
pub optional: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration of an operation return value.
|
/// Declaration of an operation return value.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ReturnDeclaration {
|
pub struct ReturnDeclaration {
|
||||||
/// Optional return-value documentation.
|
/// Optional return-value documentation.
|
||||||
pub documentation: Option<Documentation>,
|
pub documentation: Option<Documentation>,
|
||||||
/// Return value type.
|
/// Return value type.
|
||||||
pub ty: TypeExpr,
|
pub r#type: TypeExpr,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A logical protocol value.
|
/// A schema-neutral logical protocol value.
|
||||||
///
|
///
|
||||||
/// There is no general `Null` variant: optional record fields and operation
|
/// Enum cases, union cases, entries, and JSON are interpretations imposed by a
|
||||||
/// parameters are omitted. JSON null remains available inside [`Value::Json`].
|
/// descriptor. They are deliberately not variants of this enum. Record key
|
||||||
|
/// ordering is not protocol-significant.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum Value {
|
pub enum Value {
|
||||||
/// A UTF-8 string.
|
/// A value carrying no data; it also represents JSON null under `Json`.
|
||||||
String(String),
|
Unit,
|
||||||
/// A boolean.
|
/// A boolean.
|
||||||
Boolean(bool),
|
Boolean(bool),
|
||||||
/// An integer, validated against the JavaScript safe integer range.
|
/// A JavaScript-lossless integer.
|
||||||
Integer(i64),
|
Integer(i64),
|
||||||
/// A number, validated to be finite.
|
/// A finite IEEE-754 binary64 number.
|
||||||
Number(f64),
|
Number(f64),
|
||||||
|
/// A Unicode string.
|
||||||
|
String(String),
|
||||||
/// An opaque byte sequence.
|
/// An opaque byte sequence.
|
||||||
Bytes(Vec<u8>),
|
Bytes(Vec<u8>),
|
||||||
|
/// String-keyed fields with order-insensitive semantics.
|
||||||
|
Record(BTreeMap<String, Value>),
|
||||||
/// An ordered sequence.
|
/// An ordered sequence.
|
||||||
List(Vec<Value>),
|
List(Vec<Value>),
|
||||||
/// A key/value entry.
|
|
||||||
Entry {
|
|
||||||
/// Entry key.
|
|
||||||
key: Box<Value>,
|
|
||||||
/// Entry value.
|
|
||||||
value: Box<Value>,
|
|
||||||
},
|
|
||||||
/// Record fields. Duplicate names are invalid.
|
|
||||||
Record(Vec<NamedValue>),
|
|
||||||
/// An enum variant name.
|
|
||||||
Enum(String),
|
|
||||||
/// A tagged-union value.
|
|
||||||
Union {
|
|
||||||
/// Selected variant tag.
|
|
||||||
variant: String,
|
|
||||||
/// Variant payload.
|
|
||||||
value: Box<Value>,
|
|
||||||
},
|
|
||||||
/// A logical JSON value.
|
|
||||||
Json(JsonValue),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Value {
|
impl Value {
|
||||||
@@ -252,132 +206,198 @@ impl Value {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn kind(&self) -> crate::ValueKind {
|
pub fn kind(&self) -> crate::ValueKind {
|
||||||
match self {
|
match self {
|
||||||
Self::String(_) => crate::ValueKind::String,
|
Self::Unit => crate::ValueKind::Unit,
|
||||||
Self::Boolean(_) => crate::ValueKind::Boolean,
|
Self::Boolean(_) => crate::ValueKind::Boolean,
|
||||||
Self::Integer(_) => crate::ValueKind::Integer,
|
Self::Integer(_) => crate::ValueKind::Integer,
|
||||||
Self::Number(_) => crate::ValueKind::Number,
|
Self::Number(_) => crate::ValueKind::Number,
|
||||||
|
Self::String(_) => crate::ValueKind::String,
|
||||||
Self::Bytes(_) => crate::ValueKind::Bytes,
|
Self::Bytes(_) => crate::ValueKind::Bytes,
|
||||||
Self::List(_) => crate::ValueKind::List,
|
|
||||||
Self::Entry { .. } => crate::ValueKind::Entry,
|
|
||||||
Self::Record(_) => crate::ValueKind::Record,
|
Self::Record(_) => crate::ValueKind::Record,
|
||||||
Self::Enum(_) => crate::ValueKind::Enum,
|
Self::List(_) => crate::ValueKind::List,
|
||||||
Self::Union { .. } => crate::ValueKind::Union,
|
|
||||||
Self::Json(_) => crate::ValueKind::Json,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A named value used by records and operation arguments.
|
/// Request for the object currently published at one path and its indexable descendants.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct NamedValue {
|
|
||||||
/// Field or parameter name.
|
|
||||||
pub name: String,
|
|
||||||
/// Associated value.
|
|
||||||
pub value: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A transport-independent JSON value.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum JsonValue {
|
|
||||||
/// JSON null.
|
|
||||||
Null,
|
|
||||||
/// JSON boolean.
|
|
||||||
Boolean(bool),
|
|
||||||
/// JSON integer, validated against the JavaScript safe integer range.
|
|
||||||
Integer(i64),
|
|
||||||
/// JSON number, validated to be finite.
|
|
||||||
Number(f64),
|
|
||||||
/// JSON string.
|
|
||||||
String(String),
|
|
||||||
/// JSON array.
|
|
||||||
Array(Vec<JsonValue>),
|
|
||||||
/// JSON object. Duplicate member names are invalid.
|
|
||||||
Object(Vec<JsonMember>),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A member of a logical JSON object.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct JsonMember {
|
|
||||||
/// Member name.
|
|
||||||
pub name: String,
|
|
||||||
/// Member value.
|
|
||||||
pub value: JsonValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Logical destination of an operation call.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct OperationTarget {
|
pub struct ObserveRequest {
|
||||||
/// Target object.
|
/// Canonical absolute path of the observation root.
|
||||||
pub object: ObjectId,
|
pub path: String,
|
||||||
/// Target interface name.
|
/// Maximum observed depth, where the requested object has depth zero.
|
||||||
|
pub depth: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node in an object observation.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ObjectObservation {
|
||||||
|
/// Object observed at this Worldspace position.
|
||||||
|
pub object: Object,
|
||||||
|
/// Complete direct children when observed, or `None` at the requested depth boundary.
|
||||||
|
pub children: Option<Vec<ObjectObservation>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Successful `observe` response.
|
||||||
|
pub type ObserveResponse = ObjectObservation;
|
||||||
|
|
||||||
|
/// Request for the current descriptor of one opaque interface reference.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct FetchInterfaceRequest {
|
||||||
|
/// Opaque interface reference obtained from an object.
|
||||||
pub interface: String,
|
pub interface: String,
|
||||||
/// Target operation name.
|
}
|
||||||
|
|
||||||
|
/// Successful `fetch_interface` response.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct FetchInterfaceResponse {
|
||||||
|
/// Opaque interface reference corresponding to the request.
|
||||||
|
pub interface: String,
|
||||||
|
/// Current validated descriptor.
|
||||||
|
pub descriptor: InterfaceDescriptor,
|
||||||
|
/// Optional opaque validator for this descriptor observation.
|
||||||
|
pub validator: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Object portion of an operation target.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Target {
|
||||||
|
/// Canonical absolute path of the target object.
|
||||||
|
pub path: String,
|
||||||
|
/// Optional validator copied from the object observation.
|
||||||
|
pub validator: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Interface portion of an operation target.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct InterfaceTarget {
|
||||||
|
/// Opaque interface reference selected from the object's interface set.
|
||||||
|
pub reference: String,
|
||||||
|
/// Optional validator copied from the interface observation.
|
||||||
|
pub validator: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Transport-independent request to execute one operation.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct CallOperationRequest {
|
||||||
|
/// Path and optional object-state precondition.
|
||||||
|
pub target: Target,
|
||||||
|
/// Interface reference and its independent optional precondition.
|
||||||
|
pub interface: InterfaceTarget,
|
||||||
|
/// Operation name within the selected descriptor.
|
||||||
pub operation: String,
|
pub operation: String,
|
||||||
|
/// Named arguments; map iteration order has no protocol meaning.
|
||||||
|
pub arguments: BTreeMap<String, Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A transport-independent operation call.
|
/// Successful operation response.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct OperationCall {
|
pub struct CallOperationResponse {
|
||||||
/// Logical call target.
|
/// Application result validated against the operation return declaration.
|
||||||
pub target: OperationTarget,
|
pub result: Value,
|
||||||
/// Named arguments. Optional arguments are represented by omission.
|
/// Optional validator for the object state observed after execution.
|
||||||
pub arguments: Vec<NamedValue>,
|
pub validator: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Successful or failed logical outcome of an operation.
|
/// Logical outcome of any core interaction.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum OperationOutcome {
|
pub enum ProtocolResult<T> {
|
||||||
/// Operation returned. `None` represents a declared no-return operation.
|
/// The interaction succeeded.
|
||||||
Returned(Option<Value>),
|
Success(T),
|
||||||
/// Operation failed with a protocol-level error.
|
/// The interaction failed at the protocol boundary.
|
||||||
Failed(ProtocolError),
|
Failure(ProtocolError),
|
||||||
}
|
|
||||||
|
|
||||||
/// A transport-independent operation result.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct OperationResult {
|
|
||||||
/// Target corresponding to the result.
|
|
||||||
pub target: OperationTarget,
|
|
||||||
/// Logical outcome.
|
|
||||||
pub outcome: OperationOutcome,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Object {
|
impl Object {
|
||||||
/// Validates ordered-set interface semantics.
|
/// Validates the object-independent name and ordered-interface-set rules.
|
||||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_object(self)
|
crate::validation::validate_object(self)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl InterfaceObservation {
|
/// Validates this object as the response observed at `path`.
|
||||||
/// Validates the object, descriptor structure, and their correspondence.
|
pub fn validate_at_path(&self, path: &str) -> Result<(), ValidationError> {
|
||||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
crate::validation::validate_object_at_path(self, path)
|
||||||
crate::validation::validate_observation(self)
|
}
|
||||||
|
|
||||||
|
/// Validates equal representations for a shared ref and present validator.
|
||||||
|
pub fn validate_consistency_with(&self, other: &Self) -> Result<(), ValidationError> {
|
||||||
|
crate::validation::validate_object_consistency(self, other)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InterfaceDescriptor {
|
impl InterfaceDescriptor {
|
||||||
/// Validates declaration structure, references, and absence of recursion.
|
/// Validates declaration structure, named references, and absence of cycles.
|
||||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_descriptor(self)
|
crate::validation::validate_descriptor(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates a value against a type expression in this descriptor.
|
/// Validates a raw value against a type expression in this descriptor.
|
||||||
pub fn validate_value(&self, ty: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
|
pub fn validate_value(&self, r#type: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_root_value(self, ty, value)
|
crate::validation::validate_root_value(self, r#type, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates a call target and arguments against this descriptor.
|
/// Validates named arguments for one declared operation.
|
||||||
pub fn validate_call(&self, call: &OperationCall) -> Result<(), ValidationError> {
|
pub fn validate_arguments(
|
||||||
crate::validation::validate_call(self, call)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Validates an operation's returned value against this descriptor.
|
|
||||||
pub fn validate_return(
|
|
||||||
&self,
|
&self,
|
||||||
operation: &str,
|
operation: &str,
|
||||||
value: Option<&Value>,
|
arguments: &BTreeMap<String, Value>,
|
||||||
) -> Result<(), ValidationError> {
|
) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_return(self, operation, value)
|
crate::validation::validate_arguments(self, operation, arguments)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates one operation result against its return declaration.
|
||||||
|
pub fn validate_result(&self, operation: &str, result: &Value) -> Result<(), ValidationError> {
|
||||||
|
crate::validation::validate_result(self, operation, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates the path, operation, and arguments in a call request.
|
||||||
|
pub fn validate_call(&self, request: &CallOperationRequest) -> Result<(), ValidationError> {
|
||||||
|
crate::validation::validate_call(self, request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObserveRequest {
|
||||||
|
/// Validates the request path.
|
||||||
|
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||||
|
crate::validation::validate_path(&self.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates observation shape, names, and requested depth.
|
||||||
|
///
|
||||||
|
/// Failure means the Client received an invalid success response; it is not a
|
||||||
|
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||||
|
pub fn validate_response(&self, response: &ObserveResponse) -> Result<(), ValidationError> {
|
||||||
|
crate::validation::validate_observe_response(response, self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.observe_object(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-tui"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
|
crossterm = "0.28.1"
|
||||||
|
ratatui = "0.29.0"
|
||||||
|
serde_json = "1"
|
||||||
|
ureq = "3.1.2"
|
||||||
|
wip-client = { path = "../wip-client" }
|
||||||
|
wip-http = { path = "../wip-http" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
|
wip-fs-server = { path = "../wip-fs-server" }
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# wip-tui
|
||||||
|
|
||||||
|
`wip-tui` is an interactive terminal client for exploring and operating a WIP
|
||||||
|
Worldspace. It is a presentation and terminal-interaction layer over
|
||||||
|
`wip-client`: Known Space, request identity, validators, immutable operation call
|
||||||
|
contexts, stale transitions, response classification, and bounded histories remain
|
||||||
|
owned by the client runtime.
|
||||||
|
|
||||||
|
## Start
|
||||||
|
|
||||||
|
Supply one `http` or `https` endpoint:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-tui -- --endpoint https://wip.example.test/api/wip
|
||||||
|
```
|
||||||
|
|
||||||
|
The same canonical endpoint is used unchanged to construct requests, perform
|
||||||
|
HTTP I/O, and partition the client cache. WIP over HTTP does not define separate
|
||||||
|
HTTPS and development-HTTP profiles; URL scheme, TLS, certificate, authentication,
|
||||||
|
and proxy policy belong to the HTTP implementation and deployment.
|
||||||
|
|
||||||
|
The endpoint may instead be supplied as `WIP_ENDPOINT`. A non-secret cache
|
||||||
|
partition identity may be supplied with `--security-context NAME` or
|
||||||
|
`WIP_SECURITY_CONTEXT`. The default request timeout is 30 seconds and can be
|
||||||
|
changed with `--timeout SECONDS`.
|
||||||
|
|
||||||
|
An Authorization header can be read from an environment variable without placing
|
||||||
|
its value in arguments, application state, errors, snapshots, or debug output:
|
||||||
|
|
||||||
|
```console
|
||||||
|
export WIP_AUTHORIZATION='Bearer …'
|
||||||
|
cargo run -p wip-tui -- https://wip.example.test/wip
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `--authorization-env OTHER_VARIABLE` to select another variable. The value is
|
||||||
|
redacted from `Debug` and is never rendered. Shell and process environment security
|
||||||
|
remain the operator's responsibility.
|
||||||
|
|
||||||
|
### Filesystem server example
|
||||||
|
|
||||||
|
In one terminal:
|
||||||
|
|
||||||
|
```console
|
||||||
|
mkdir -p /tmp/wip-example
|
||||||
|
printf 'hello world' >/tmp/wip-example/notes.txt
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root /tmp/wip-example \
|
||||||
|
--listen 127.0.0.1:8080 \
|
||||||
|
--base-path /wip \
|
||||||
|
--read-write
|
||||||
|
```
|
||||||
|
|
||||||
|
In another:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-tui -- http://127.0.0.1:8080/wip
|
||||||
|
```
|
||||||
|
|
||||||
|
Expand `/`, select `notes.txt`, focus the Interface/Operation pane, and choose
|
||||||
|
`read`; descriptors advertised by visible Objects are normally prefetched already.
|
||||||
|
The editor labels `offset` and `length` as optional; leave both blank to read the
|
||||||
|
bounded file. `Bytes` results are shown as a bounded hex preview. For `replace`,
|
||||||
|
enter `contents` as RFC 4648 base64—for example, `dXBkYXRlZA==` for
|
||||||
|
`updated`—then review the target Entry, interface reference, operation, and value
|
||||||
|
on the confirmation screen before pressing Enter again.
|
||||||
|
|
||||||
|
## Keyboard bindings
|
||||||
|
|
||||||
|
All required actions are keyboard-accessible.
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| `↑`/`k`, `↓`/`j` | Move within the focused tree, operation list, history, or editor |
|
||||||
|
| `→`/`l`, `Enter` | Expand a tree node lazily; load/select an interface or operation |
|
||||||
|
| `←`/`h` | Collapse a node or move to its parent |
|
||||||
|
| `Tab` | Cycle Tree → Selected Entry → Operations → History |
|
||||||
|
| `r` | Reobserve the selected Entry and its direct subtree |
|
||||||
|
| `c` | Cancel the newest retrieval; a dispatched operation is never presented as canceled |
|
||||||
|
| `R` | Reconnect after connection failure |
|
||||||
|
| `?` | Open help |
|
||||||
|
| `Esc` | Close a modal or return to the tree |
|
||||||
|
| `q`, `Ctrl-C` | Exit and restore the terminal |
|
||||||
|
|
||||||
|
Inside an argument editor, printable keys are field input, arrows move fields,
|
||||||
|
Backspace edits, Enter validates, and Esc cancels. The confirmation screen requires
|
||||||
|
a second explicit Enter (or `e`) to execute once. There is no operation auto-retry.
|
||||||
|
|
||||||
|
## Screen model
|
||||||
|
|
||||||
|
- **Worldspace tree** starts at `/`, lazily materializes expanded nodes, and
|
||||||
|
prefetches children for each visible Object so emptiness and the next expansion
|
||||||
|
frontier are known without selecting that Object first. Text labels distinguish
|
||||||
|
unloaded, loading, empty, stale, and failed state; color is supplemental. Every
|
||||||
|
successful expansion is complete for its requested depth.
|
||||||
|
- **Selected Entry** shows only public WIP path, object name, description, ordered
|
||||||
|
interfaces, and freshness. Validators, credentials, Host internals, and backend
|
||||||
|
paths are deliberately hidden. If current metadata disappears, old text is not
|
||||||
|
presented as current.
|
||||||
|
- **Interfaces / Operations** identifies every operation by `(interface reference,
|
||||||
|
operation name)`. Descriptor lookahead follows fresh visible Objects, shares the
|
||||||
|
client's in-flight/cache bounds, and never retries retained failures implicitly.
|
||||||
|
The pane shows descriptor documentation, ordered parameters, required/optional
|
||||||
|
status, and result types.
|
||||||
|
- **Argument editor** supports Unit, Boolean, Integer, Number, String, base64 Bytes,
|
||||||
|
Record, List, Entry, Enum, Union, Json, and descriptor-local named types. Record,
|
||||||
|
List, Union, and Json values use JSON syntax. Union input is
|
||||||
|
`{"$case":"name","value":…}` when the selected case has a payload. Diagnostics
|
||||||
|
remain attached to the failing field.
|
||||||
|
- **Recent results / diagnostics** explicitly distinguishes success, Host failure,
|
||||||
|
invalid protocol response, transport failure, client-local failure, and unknown
|
||||||
|
operation outcome. Large values, bytes, nesting, and control characters are
|
||||||
|
bounded before rendering. Only descriptor-declared `Entry` results become
|
||||||
|
navigation targets; path-looking String or Json values do not.
|
||||||
|
|
||||||
|
Terminals below 48×14 show a minimum-size screen instead of attempting the full
|
||||||
|
layout.
|
||||||
|
|
||||||
|
## Validator and failure behavior
|
||||||
|
|
||||||
|
Object and interface validators are observed and attached automatically by
|
||||||
|
`wip-client`; users neither copy nor edit them. A successful operation may update the
|
||||||
|
cached Object validator but does not by itself make the Object observation stale.
|
||||||
|
Validator mismatch, interface mismatch, `OperationOutcomeUnknown`, undecodable
|
||||||
|
post-dispatch responses, and post-dispatch timeout/disconnect are displayed using
|
||||||
|
the runtime's authoritative transition.
|
||||||
|
|
||||||
|
For an unknown outcome, the UI states that execution or side effects may have
|
||||||
|
occurred, marks the related Entry stale, and tells the user to refresh. Refreshing
|
||||||
|
does not recreate the call: the user must select the operation, review fresh input,
|
||||||
|
and explicitly execute again. The same no-auto-retry rule applies after validator
|
||||||
|
or interface mismatch.
|
||||||
|
|
||||||
|
Retrieval work runs on I/O workers while the input/render loop continues. Responses
|
||||||
|
return with the original `RequestId`, so an old completion cannot populate another
|
||||||
|
Entry's details. Canceling a retrieval records a local cancellation and drops its
|
||||||
|
late response. Once an operation crosses dispatch, cancellation is never described
|
||||||
|
as undoing execution.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The library form keeps reducers and rendering independent of a real terminal.
|
||||||
|
`ratatui::TestBackend` snapshots cover tree/detail/result states and the minimum-size
|
||||||
|
fallback. Unit tests cover reducer focus, selection, modal confirmation, key
|
||||||
|
translation, descriptor inputs, bounded values, and descriptor-directed Entry
|
||||||
|
results. The real HTTP integration test launches `wip-fs-server` on a temporary
|
||||||
|
root and covers tree selection, reads, validator-protected replacement, external
|
||||||
|
stale-validator rejection without retry, explicit refresh/re-execution, and
|
||||||
|
symlink confinement.
|
||||||
@@ -0,0 +1,952 @@
|
|||||||
|
//! Pure application state, selection, modal, focus, and key reducer.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
|
||||||
|
use wip_protocol::{InterfaceDescriptor, Object, Value};
|
||||||
|
|
||||||
|
use crate::editor::ArgumentEditor;
|
||||||
|
|
||||||
|
const MAX_PRESENTATION_ENTRIES: usize = 2048;
|
||||||
|
const MAX_PRESENTATION_INTERFACES: usize = 256;
|
||||||
|
|
||||||
|
/// A terminal-independent key understood by the reducer.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum InputKey {
|
||||||
|
/// Up arrow or `k`.
|
||||||
|
Up,
|
||||||
|
/// Down arrow or `j`.
|
||||||
|
Down,
|
||||||
|
/// Left arrow or `h`.
|
||||||
|
Left,
|
||||||
|
/// Right arrow or `l`.
|
||||||
|
Right,
|
||||||
|
/// Focus the next pane.
|
||||||
|
Tab,
|
||||||
|
/// Activate the selected item.
|
||||||
|
Enter,
|
||||||
|
/// Close the current modal or return to the tree.
|
||||||
|
Escape,
|
||||||
|
/// Delete one editor character.
|
||||||
|
Backspace,
|
||||||
|
/// Refresh the selected Entry.
|
||||||
|
Refresh,
|
||||||
|
/// Cancel the newest cancel-safe retrieval.
|
||||||
|
CancelRead,
|
||||||
|
/// Show key help.
|
||||||
|
Help,
|
||||||
|
/// Quit the application.
|
||||||
|
Quit,
|
||||||
|
/// Reconnect after startup or transport failure.
|
||||||
|
Reconnect,
|
||||||
|
/// A printable editor character.
|
||||||
|
Character(char),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pane receiving navigation keys.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Focus {
|
||||||
|
/// Worldspace tree.
|
||||||
|
Tree,
|
||||||
|
/// Selected Entry metadata.
|
||||||
|
Entry,
|
||||||
|
/// Interfaces and operations.
|
||||||
|
Operations,
|
||||||
|
/// Recent result and diagnostic history.
|
||||||
|
History,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Focus {
|
||||||
|
fn next(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Self::Tree => Self::Entry,
|
||||||
|
Self::Entry => Self::Operations,
|
||||||
|
Self::Operations => Self::History,
|
||||||
|
Self::History => Self::Tree,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connection lifecycle shown without relying on color.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ConnectionState {
|
||||||
|
/// No request has been attempted.
|
||||||
|
Disconnected,
|
||||||
|
/// Initial root request or reconnect is in progress.
|
||||||
|
Connecting,
|
||||||
|
/// The root was observed successfully.
|
||||||
|
Connected,
|
||||||
|
/// Connection failed; reconnect and exit remain available.
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Presentation-safe observation state.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ViewState {
|
||||||
|
/// No observation has been requested.
|
||||||
|
Unloaded,
|
||||||
|
/// One request is in flight.
|
||||||
|
Loading(u64),
|
||||||
|
/// The observation is current.
|
||||||
|
Fresh,
|
||||||
|
/// The retained value needs reobservation.
|
||||||
|
Stale,
|
||||||
|
/// The latest attempt failed.
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&ObservationState> for ViewState {
|
||||||
|
fn from(value: &ObservationState) -> Self {
|
||||||
|
match value {
|
||||||
|
ObservationState::Loading(id) => Self::Loading(id.get()),
|
||||||
|
ObservationState::Fresh => Self::Fresh,
|
||||||
|
ObservationState::Stale => Self::Stale,
|
||||||
|
ObservationState::Error(error) => Self::Error(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One materialized tree Entry.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct EntryView {
|
||||||
|
/// Canonical WIP path.
|
||||||
|
pub path: String,
|
||||||
|
/// Latest object when retained by the client runtime.
|
||||||
|
pub object: Option<Object>,
|
||||||
|
/// Object observation state.
|
||||||
|
pub state: ViewState,
|
||||||
|
/// Direct child paths in Host order.
|
||||||
|
pub children: Vec<String>,
|
||||||
|
/// Expansion observation state.
|
||||||
|
pub tree_state: ViewState,
|
||||||
|
/// Whether the user expanded this row.
|
||||||
|
pub expanded: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EntryView {
|
||||||
|
fn placeholder(path: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
path: path.into(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: Vec::new(),
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cached interface descriptor state used by presentation.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct InterfaceView {
|
||||||
|
/// Opaque interface reference.
|
||||||
|
pub reference: String,
|
||||||
|
/// Descriptor when accepted by the client runtime.
|
||||||
|
pub descriptor: Option<InterfaceDescriptor>,
|
||||||
|
/// Descriptor observation state.
|
||||||
|
pub state: ViewState,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable result/diagnostic category.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum HistoryKind {
|
||||||
|
/// A descriptor-validated operation result.
|
||||||
|
Success,
|
||||||
|
/// A valid Host-declared failure.
|
||||||
|
DomainFailure,
|
||||||
|
/// An invalid protocol response.
|
||||||
|
ProtocolError,
|
||||||
|
/// Network or TLS failure.
|
||||||
|
TransportFailure,
|
||||||
|
/// Client-local validation or capacity failure.
|
||||||
|
ClientFailure,
|
||||||
|
/// Dispatch occurred but execution or commit is uncertain.
|
||||||
|
OutcomeUnknown,
|
||||||
|
/// Informational request state.
|
||||||
|
Information,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One bounded recent result or diagnostic.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct HistoryItem {
|
||||||
|
/// Explicit outcome category.
|
||||||
|
pub kind: HistoryKind,
|
||||||
|
/// Short bounded heading.
|
||||||
|
pub title: String,
|
||||||
|
/// Bounded, terminal-safe detail.
|
||||||
|
pub detail: String,
|
||||||
|
/// Navigation target only when declared as descriptor `Entry`.
|
||||||
|
pub entry_target: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kind of request currently in flight.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum InFlightKind {
|
||||||
|
/// Object refresh.
|
||||||
|
Object(String),
|
||||||
|
/// Tree expansion or refresh.
|
||||||
|
Tree(String),
|
||||||
|
/// Descriptor fetch.
|
||||||
|
Interface(String),
|
||||||
|
/// Explicit operation call.
|
||||||
|
Operation {
|
||||||
|
/// Target path.
|
||||||
|
path: String,
|
||||||
|
/// Interface reference.
|
||||||
|
interface: String,
|
||||||
|
/// Operation name.
|
||||||
|
operation: String,
|
||||||
|
/// Whether the transport dispatch boundary was crossed.
|
||||||
|
dispatched: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InFlightKind {
|
||||||
|
/// Whether dropping the response is a safe cancellation operation.
|
||||||
|
#[must_use]
|
||||||
|
pub fn cancel_safe(&self) -> bool {
|
||||||
|
!matches!(self, Self::Operation { .. })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Active overlay.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Modal {
|
||||||
|
/// No overlay.
|
||||||
|
None,
|
||||||
|
/// Keyboard help.
|
||||||
|
Help,
|
||||||
|
/// Descriptor-driven field editor.
|
||||||
|
Editor(ArgumentEditor),
|
||||||
|
/// Explicit pre-execution confirmation.
|
||||||
|
Confirm {
|
||||||
|
/// Editor retained when confirmation is cancelled.
|
||||||
|
editor: ArgumentEditor,
|
||||||
|
/// Validated arguments that will be sent.
|
||||||
|
arguments: BTreeMap<String, Value>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Side effect requested by the pure reducer.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Action {
|
||||||
|
/// Expand one node lazily.
|
||||||
|
Expand {
|
||||||
|
/// Tree root path.
|
||||||
|
path: String,
|
||||||
|
},
|
||||||
|
/// Reobserve an Entry and its direct children.
|
||||||
|
Refresh {
|
||||||
|
/// Selected path.
|
||||||
|
path: String,
|
||||||
|
},
|
||||||
|
/// Retrieve one interface descriptor.
|
||||||
|
FetchInterface(String),
|
||||||
|
/// Execute only after explicit confirmation.
|
||||||
|
Execute {
|
||||||
|
/// Entry target.
|
||||||
|
path: String,
|
||||||
|
/// Interface reference.
|
||||||
|
interface: String,
|
||||||
|
/// Operation name.
|
||||||
|
operation: String,
|
||||||
|
/// Descriptor-validated arguments.
|
||||||
|
arguments: BTreeMap<String, Value>,
|
||||||
|
},
|
||||||
|
/// Cancel the newest safe retrieval.
|
||||||
|
CancelRead,
|
||||||
|
/// Reconnect and observe the root.
|
||||||
|
Reconnect,
|
||||||
|
/// Navigate to a descriptor-declared Entry result.
|
||||||
|
NavigateEntry(String),
|
||||||
|
/// Exit normally.
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Complete presentation model.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct App {
|
||||||
|
/// Effective endpoint label (never credential material).
|
||||||
|
pub endpoint: String,
|
||||||
|
/// Connection lifecycle.
|
||||||
|
pub connection: ConnectionState,
|
||||||
|
/// Materialized tree nodes by path.
|
||||||
|
pub entries: BTreeMap<String, EntryView>,
|
||||||
|
/// Selected Entry path.
|
||||||
|
pub selected_path: String,
|
||||||
|
/// Focused pane.
|
||||||
|
pub focus: Focus,
|
||||||
|
/// Interface descriptor views by opaque reference.
|
||||||
|
pub interfaces: BTreeMap<String, InterfaceView>,
|
||||||
|
/// Selected row in the flattened interface/operation view.
|
||||||
|
pub operation_cursor: usize,
|
||||||
|
/// Selected recent-history row.
|
||||||
|
pub history_cursor: usize,
|
||||||
|
/// Active overlay.
|
||||||
|
pub modal: Modal,
|
||||||
|
/// In-flight requests keyed by client request identity.
|
||||||
|
pub in_flight: BTreeMap<u64, InFlightKind>,
|
||||||
|
/// Recent result and diagnostic history, newest first.
|
||||||
|
pub history: Vec<HistoryItem>,
|
||||||
|
/// Maximum retained presentation history.
|
||||||
|
pub history_limit: usize,
|
||||||
|
/// One-line status for local action feedback.
|
||||||
|
pub status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
/// Creates a disconnected model with `/` selected.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(endpoint: impl Into<String>) -> Self {
|
||||||
|
let mut entries = BTreeMap::new();
|
||||||
|
let mut root = EntryView::placeholder("/");
|
||||||
|
root.expanded = true;
|
||||||
|
entries.insert("/".into(), root);
|
||||||
|
Self {
|
||||||
|
endpoint: endpoint.into(),
|
||||||
|
connection: ConnectionState::Disconnected,
|
||||||
|
entries,
|
||||||
|
selected_path: "/".into(),
|
||||||
|
focus: Focus::Tree,
|
||||||
|
interfaces: BTreeMap::new(),
|
||||||
|
operation_cursor: 0,
|
||||||
|
history_cursor: 0,
|
||||||
|
modal: Modal::None,
|
||||||
|
in_flight: BTreeMap::new(),
|
||||||
|
history: Vec::new(),
|
||||||
|
history_limit: 64,
|
||||||
|
status: "press ? for help".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies one key and returns requested effects without performing I/O.
|
||||||
|
pub fn reduce(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
match std::mem::replace(&mut self.modal, Modal::None) {
|
||||||
|
Modal::Help => {
|
||||||
|
if !matches!(key, InputKey::Escape | InputKey::Help) {
|
||||||
|
self.modal = Modal::Help;
|
||||||
|
}
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
Modal::Editor(mut editor) => {
|
||||||
|
match key {
|
||||||
|
InputKey::Escape => {}
|
||||||
|
InputKey::Up => {
|
||||||
|
editor.previous_field();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Down | InputKey::Tab => {
|
||||||
|
editor.next_field();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Backspace => {
|
||||||
|
editor.backspace();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Character(character) => {
|
||||||
|
editor.insert(character);
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Enter => match editor.validate() {
|
||||||
|
Ok(arguments) => self.modal = Modal::Confirm { editor, arguments },
|
||||||
|
Err(_) => self.modal = Modal::Editor(editor),
|
||||||
|
},
|
||||||
|
_ => self.modal = Modal::Editor(editor),
|
||||||
|
}
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
Modal::Confirm { editor, arguments } => match key {
|
||||||
|
InputKey::Escape => {
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
InputKey::Enter | InputKey::Character('e') => {
|
||||||
|
let action = Action::Execute {
|
||||||
|
path: self.selected_path.clone(),
|
||||||
|
interface: editor.interface.clone(),
|
||||||
|
operation: editor.operation.name.clone(),
|
||||||
|
arguments,
|
||||||
|
};
|
||||||
|
self.status =
|
||||||
|
"operation confirmed; preparing request (not yet dispatched)".into();
|
||||||
|
return vec![action];
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.modal = Modal::Confirm { editor, arguments };
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Modal::None => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if key == InputKey::Help {
|
||||||
|
self.modal = Modal::Help;
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
if key == InputKey::Quit {
|
||||||
|
return vec![Action::Quit];
|
||||||
|
}
|
||||||
|
if key == InputKey::Reconnect {
|
||||||
|
return vec![Action::Reconnect];
|
||||||
|
}
|
||||||
|
if key == InputKey::CancelRead {
|
||||||
|
return vec![Action::CancelRead];
|
||||||
|
}
|
||||||
|
if key == InputKey::Tab {
|
||||||
|
self.focus = self.focus.next();
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.focus {
|
||||||
|
Focus::Tree => self.reduce_tree(key),
|
||||||
|
Focus::Operations => self.reduce_operations(key),
|
||||||
|
Focus::History => self.reduce_history(key),
|
||||||
|
Focus::Entry => {
|
||||||
|
if key == InputKey::Escape {
|
||||||
|
self.focus = Focus::Tree;
|
||||||
|
} else if key == InputKey::Refresh {
|
||||||
|
return vec![self.refresh_action()];
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_tree(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
let visible = self.visible_paths();
|
||||||
|
let position = visible
|
||||||
|
.iter()
|
||||||
|
.position(|path| path == &self.selected_path)
|
||||||
|
.unwrap_or(0);
|
||||||
|
match key {
|
||||||
|
InputKey::Up if position > 0 => self.selected_path = visible[position - 1].clone(),
|
||||||
|
InputKey::Down if position + 1 < visible.len() => {
|
||||||
|
self.selected_path = visible[position + 1].clone();
|
||||||
|
}
|
||||||
|
InputKey::Right | InputKey::Enter => {
|
||||||
|
let node = self
|
||||||
|
.entries
|
||||||
|
.entry(self.selected_path.clone())
|
||||||
|
.or_insert_with(|| EntryView::placeholder(&self.selected_path));
|
||||||
|
node.expanded = true;
|
||||||
|
if !matches!(node.tree_state, ViewState::Fresh) {
|
||||||
|
return vec![Action::Expand {
|
||||||
|
path: node.path.clone(),
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Left => {
|
||||||
|
let node = self
|
||||||
|
.entries
|
||||||
|
.get_mut(&self.selected_path)
|
||||||
|
.expect("selected Entry exists");
|
||||||
|
if node.expanded {
|
||||||
|
node.expanded = false;
|
||||||
|
} else if self.selected_path != "/" {
|
||||||
|
self.selected_path = parent_path(&self.selected_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Refresh => return vec![self.refresh_action()],
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
self.operation_cursor = 0;
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_operations(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
let rows = self.operation_rows();
|
||||||
|
match key {
|
||||||
|
InputKey::Up => self.operation_cursor = self.operation_cursor.saturating_sub(1),
|
||||||
|
InputKey::Down if self.operation_cursor + 1 < rows.len() => self.operation_cursor += 1,
|
||||||
|
InputKey::Refresh => return vec![self.refresh_action()],
|
||||||
|
InputKey::Escape => self.focus = Focus::Tree,
|
||||||
|
InputKey::Enter => {
|
||||||
|
if let Some(row) = rows.get(self.operation_cursor) {
|
||||||
|
if let Some(operation_name) = &row.operation {
|
||||||
|
if let Some(interface) = self.interfaces.get(&row.interface)
|
||||||
|
&& let Some(descriptor) = &interface.descriptor
|
||||||
|
&& let Some(operation) = descriptor
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.name == *operation_name)
|
||||||
|
{
|
||||||
|
self.modal = Modal::Editor(ArgumentEditor::new(
|
||||||
|
row.interface.clone(),
|
||||||
|
descriptor.clone(),
|
||||||
|
operation.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return vec![Action::FetchInterface(row.interface.clone())];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_history(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
match key {
|
||||||
|
InputKey::Up => self.history_cursor = self.history_cursor.saturating_sub(1),
|
||||||
|
InputKey::Down if self.history_cursor + 1 < self.history.len() => {
|
||||||
|
self.history_cursor += 1;
|
||||||
|
}
|
||||||
|
InputKey::Enter => {
|
||||||
|
if let Some(path) = self
|
||||||
|
.history
|
||||||
|
.get(self.history_cursor)
|
||||||
|
.and_then(|item| item.entry_target.clone())
|
||||||
|
{
|
||||||
|
return vec![Action::NavigateEntry(path)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Escape => self.focus = Focus::Tree,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_action(&self) -> Action {
|
||||||
|
Action::Refresh {
|
||||||
|
path: self.selected_path.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records a pending request separately by interaction type.
|
||||||
|
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
|
||||||
|
match &kind {
|
||||||
|
InFlightKind::Object(path) => {
|
||||||
|
self.ensure_entry(path).state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Tree(path) => {
|
||||||
|
let entry = self.ensure_entry(path);
|
||||||
|
entry.state = ViewState::Loading(id);
|
||||||
|
entry.tree_state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Interface(reference) => {
|
||||||
|
self.ensure_interface(reference).state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Operation { .. } => {}
|
||||||
|
}
|
||||||
|
self.in_flight.insert(id, kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks an operation as handed to the transport.
|
||||||
|
pub fn request_dispatched(&mut self, id: u64) {
|
||||||
|
if let Some(InFlightKind::Operation { dispatched, .. }) = self.in_flight.get_mut(&id) {
|
||||||
|
*dispatched = true;
|
||||||
|
self.status = "operation dispatched once; automatic retry is disabled".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a completed request identity.
|
||||||
|
pub fn request_finished(&mut self, id: u64) -> Option<InFlightKind> {
|
||||||
|
self.in_flight.remove(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies an object observation from `wip-client`.
|
||||||
|
pub fn apply_object(&mut self, observation: ObjectObservation) {
|
||||||
|
let entry = self.ensure_entry(&observation.path);
|
||||||
|
entry.object = observation.object;
|
||||||
|
entry.state = ViewState::from(&observation.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a lazy tree observation and ensures child placeholders exist.
|
||||||
|
pub fn apply_tree(&mut self, observation: TreeObservation) {
|
||||||
|
let children = observation.children.clone();
|
||||||
|
let entry = self.ensure_entry(&observation.path);
|
||||||
|
entry.children = children.clone();
|
||||||
|
entry.tree_state = ViewState::from(&observation.state);
|
||||||
|
for path in children {
|
||||||
|
self.ensure_entry(&path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies one interface observation from `wip-client`.
|
||||||
|
pub fn apply_interface(&mut self, observation: InterfaceObservation) {
|
||||||
|
let view = self.ensure_interface(&observation.reference);
|
||||||
|
*view = InterfaceView {
|
||||||
|
reference: observation.reference,
|
||||||
|
descriptor: observation.descriptor,
|
||||||
|
state: ViewState::from(&observation.state),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces current Entry details from the client's current snapshot.
|
||||||
|
pub fn sync_object(&mut self, path: &str, observation: Option<ObjectObservation>) {
|
||||||
|
match observation {
|
||||||
|
Some(observation) => self.apply_object(observation),
|
||||||
|
None => {
|
||||||
|
let entry = self.ensure_entry(path);
|
||||||
|
entry.object = None;
|
||||||
|
entry.state = ViewState::Stale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Selects a known or newly discovered descriptor-declared Entry path.
|
||||||
|
pub fn navigate_entry(&mut self, path: impl Into<String>) {
|
||||||
|
let path = path.into();
|
||||||
|
self.ensure_entry(&path);
|
||||||
|
self.selected_path = path;
|
||||||
|
self.focus = Focus::Tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds one bounded recent item.
|
||||||
|
pub fn push_history(&mut self, item: HistoryItem) {
|
||||||
|
self.history.insert(0, item);
|
||||||
|
self.history.truncate(self.history_limit);
|
||||||
|
self.history_cursor = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns visible tree paths in display order.
|
||||||
|
#[must_use]
|
||||||
|
pub fn visible_paths(&self) -> Vec<String> {
|
||||||
|
let mut visible = Vec::new();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
self.collect_visible("/", &mut seen, &mut visible);
|
||||||
|
if !seen.contains(&self.selected_path) && self.entries.contains_key(&self.selected_path) {
|
||||||
|
visible.push(self.selected_path.clone());
|
||||||
|
}
|
||||||
|
visible
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns interface references advertised by fresh visible Objects in display
|
||||||
|
/// and per-Object declaration order, with duplicates removed.
|
||||||
|
#[must_use]
|
||||||
|
pub fn visible_interface_references(&self) -> Vec<String> {
|
||||||
|
let mut references = Vec::new();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for path in self.visible_paths() {
|
||||||
|
let Some(object) = self
|
||||||
|
.entries
|
||||||
|
.get(&path)
|
||||||
|
.filter(|entry| entry.state == ViewState::Fresh)
|
||||||
|
.and_then(|entry| entry.object.as_ref())
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for reference in &object.interfaces {
|
||||||
|
if seen.insert(reference.clone()) {
|
||||||
|
references.push(reference.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
references
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_visible(&self, path: &str, seen: &mut BTreeSet<String>, visible: &mut Vec<String>) {
|
||||||
|
if !seen.insert(path.to_owned()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
visible.push(path.to_owned());
|
||||||
|
let Some(entry) = self.entries.get(path) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if entry.expanded {
|
||||||
|
for child in &entry.children {
|
||||||
|
self.collect_visible(child, seen, visible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns flattened interface headers and operations for the selected Entry.
|
||||||
|
#[must_use]
|
||||||
|
pub fn operation_rows(&self) -> Vec<OperationRow> {
|
||||||
|
let Some(object) = self
|
||||||
|
.entries
|
||||||
|
.get(&self.selected_path)
|
||||||
|
.filter(|entry| entry.state == ViewState::Fresh)
|
||||||
|
.and_then(|entry| entry.object.as_ref())
|
||||||
|
else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for reference in &object.interfaces {
|
||||||
|
rows.push(OperationRow {
|
||||||
|
interface: reference.clone(),
|
||||||
|
operation: None,
|
||||||
|
});
|
||||||
|
if let Some(descriptor) = self
|
||||||
|
.interfaces
|
||||||
|
.get(reference)
|
||||||
|
.filter(|view| view.state == ViewState::Fresh)
|
||||||
|
.and_then(|view| view.descriptor.as_ref())
|
||||||
|
{
|
||||||
|
rows.extend(descriptor.operations.iter().map(|operation| OperationRow {
|
||||||
|
interface: reference.clone(),
|
||||||
|
operation: Some(operation.name.clone()),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
|
||||||
|
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
|
||||||
|
let candidate = self
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.find(|(candidate, entry)| {
|
||||||
|
candidate.as_str() != "/"
|
||||||
|
&& candidate.as_str() != self.selected_path
|
||||||
|
&& matches!(
|
||||||
|
entry.state,
|
||||||
|
ViewState::Unloaded | ViewState::Stale | ViewState::Error(_)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.entries.iter().find(|(candidate, entry)| {
|
||||||
|
candidate.as_str() != "/"
|
||||||
|
&& candidate.as_str() != self.selected_path
|
||||||
|
&& !matches!(entry.state, ViewState::Loading(_))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(|(candidate, _)| candidate.clone());
|
||||||
|
if let Some(candidate) = candidate {
|
||||||
|
self.entries.remove(&candidate);
|
||||||
|
for entry in self.entries.values_mut() {
|
||||||
|
entry.children.retain(|child| child != &candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.entries
|
||||||
|
.entry(path.to_owned())
|
||||||
|
.or_insert_with(|| EntryView::placeholder(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_interface(&mut self, reference: &str) -> &mut InterfaceView {
|
||||||
|
if !self.interfaces.contains_key(reference)
|
||||||
|
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
|
||||||
|
{
|
||||||
|
let protected = self
|
||||||
|
.entries
|
||||||
|
.get(&self.selected_path)
|
||||||
|
.and_then(|entry| entry.object.as_ref())
|
||||||
|
.map(|object| object.interfaces.iter().cloned().collect::<BTreeSet<_>>())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let candidate = self
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.find(|(candidate, interface)| {
|
||||||
|
!protected.contains(*candidate)
|
||||||
|
&& !matches!(interface.state, ViewState::Loading(_))
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.interfaces
|
||||||
|
.iter()
|
||||||
|
.find(|(_, interface)| !matches!(interface.state, ViewState::Loading(_)))
|
||||||
|
})
|
||||||
|
.map(|(candidate, _)| candidate.clone());
|
||||||
|
if let Some(candidate) = candidate {
|
||||||
|
self.interfaces.remove(&candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.interfaces
|
||||||
|
.entry(reference.to_owned())
|
||||||
|
.or_insert_with(|| InterfaceView {
|
||||||
|
reference: reference.to_owned(),
|
||||||
|
descriptor: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row in the combined Interface and Operation pane.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct OperationRow {
|
||||||
|
/// Interface reference, which participates in operation identity.
|
||||||
|
pub interface: String,
|
||||||
|
/// Operation name, or `None` for the interface heading.
|
||||||
|
pub operation: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical parent of a non-root path.
|
||||||
|
#[must_use]
|
||||||
|
pub fn parent_path(path: &str) -> String {
|
||||||
|
match path.rsplit_once('/') {
|
||||||
|
Some(("", _)) | None => "/".into(),
|
||||||
|
Some((parent, _)) => parent.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
|
||||||
|
|
||||||
|
fn object(name: &str, interfaces: &[&str]) -> Object {
|
||||||
|
Object {
|
||||||
|
name: name.into(),
|
||||||
|
description: Some(format!("{name} description")),
|
||||||
|
interfaces: interfaces.iter().map(|value| (*value).into()).collect(),
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tree_navigation_and_lazy_expansion_are_pure() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.apply_tree(TreeObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
children: vec!["/a".into(), "/b".into()],
|
||||||
|
revision: request_id(),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
assert_eq!(app.visible_paths(), ["/", "/a", "/b"]);
|
||||||
|
app.reduce(InputKey::Down);
|
||||||
|
assert_eq!(app.selected_path, "/a");
|
||||||
|
assert!(matches!(
|
||||||
|
app.reduce(InputKey::Right).as_slice(),
|
||||||
|
[Action::Expand { path }] if path == "/a"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn visible_interface_references_are_ordered_deduplicated_and_fresh() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.apply_tree(TreeObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
children: vec!["/a".into(), "/stale".into()],
|
||||||
|
revision: request_id(),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(object("", &["root", "shared"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/a".into(),
|
||||||
|
object: Some(object("a", &["shared", "child"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/stale".into(),
|
||||||
|
object: Some(object("stale", &["ignored"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Stale,
|
||||||
|
});
|
||||||
|
app.apply_tree(TreeObservation {
|
||||||
|
path: "/a".into(),
|
||||||
|
children: vec!["/a/hidden".into()],
|
||||||
|
revision: request_id(),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/a/hidden".into(),
|
||||||
|
object: Some(object("hidden", &["hidden"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
app.visible_interface_references(),
|
||||||
|
["root", "shared", "child"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn focus_modal_and_explicit_confirmation_gate_execution() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(object("", &["iface"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let descriptor = InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "ping".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "iface".into(),
|
||||||
|
descriptor: Some(descriptor),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.focus = Focus::Operations;
|
||||||
|
app.operation_cursor = 1;
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
assert!(matches!(app.modal, Modal::Editor(_)));
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
assert!(matches!(app.modal, Modal::Confirm { .. }));
|
||||||
|
assert!(matches!(
|
||||||
|
app.reduce(InputKey::Enter).as_slice(),
|
||||||
|
[Action::Execute { operation, .. }] if operation == "ping"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presentation_maps_enforce_client_sized_hard_bounds() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
for index in 0..(MAX_PRESENTATION_ENTRIES + 100) {
|
||||||
|
app.navigate_entry(format!("/discovered-{index}"));
|
||||||
|
app.selected_path = "/".into();
|
||||||
|
}
|
||||||
|
assert!(app.entries.len() <= MAX_PRESENTATION_ENTRIES);
|
||||||
|
assert!(app.entries.contains_key("/"));
|
||||||
|
|
||||||
|
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: format!("interface-{index}"),
|
||||||
|
descriptor: None,
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert!(app.interfaces.len() <= MAX_PRESENTATION_INTERFACES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn result_navigation_only_uses_explicit_entry_target() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Success,
|
||||||
|
title: "string".into(),
|
||||||
|
detail: "/looks/like/a/path".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
app.focus = Focus::History;
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Success,
|
||||||
|
title: "Entry".into(),
|
||||||
|
detail: "/actual".into(),
|
||||||
|
entry_target: Some("/actual".into()),
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
app.reduce(InputKey::Enter),
|
||||||
|
vec![Action::NavigateEntry("/actual".into())]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_id() -> wip_client::RequestId {
|
||||||
|
// A request identity has no public constructor; derive one through the runtime.
|
||||||
|
let mut client = wip_client::Client::new(
|
||||||
|
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
||||||
|
wip_http::Limits::new(1024, 1024, 8, 8).unwrap(),
|
||||||
|
);
|
||||||
|
let session = client
|
||||||
|
.open_session(
|
||||||
|
"https://example.test/wip",
|
||||||
|
wip_client::SecurityContext::new("test"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.refresh_object(&session, "/").unwrap().id
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
//! Command-line and environment configuration for the HTTP client.
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Debug, Display, Formatter};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use wip_http::Endpoint;
|
||||||
|
|
||||||
|
/// Credential wrapper whose debug output is always redacted.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Secret(String);
|
||||||
|
|
||||||
|
impl Secret {
|
||||||
|
pub(crate) fn expose(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for Secret {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter.write_str("Secret([REDACTED])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validated runtime configuration.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Canonical endpoint used for request construction, transport, and cache partitioning.
|
||||||
|
endpoint: String,
|
||||||
|
/// Non-secret cache partition identity.
|
||||||
|
security_context: String,
|
||||||
|
/// Bounded network timeout.
|
||||||
|
timeout: Duration,
|
||||||
|
/// Optional complete Authorization header value, never rendered or logged.
|
||||||
|
authorization: Option<Secret>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for Config {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter
|
||||||
|
.debug_struct("Config")
|
||||||
|
.field("endpoint", &self.endpoint)
|
||||||
|
.field("security_context", &self.security_context)
|
||||||
|
.field("timeout", &self.timeout)
|
||||||
|
.field("authorization", &self.authorization)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// Returns the canonical endpoint used by the client and HTTP transport.
|
||||||
|
#[must_use]
|
||||||
|
pub fn endpoint(&self) -> &str {
|
||||||
|
&self.endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the non-secret session cache partition identity.
|
||||||
|
#[must_use]
|
||||||
|
pub fn security_context(&self) -> &str {
|
||||||
|
&self.security_context
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the end-to-end request timeout.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn timeout(&self) -> Duration {
|
||||||
|
self.timeout
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn authorization(&self) -> Option<&Secret> {
|
||||||
|
self.authorization.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses process arguments and supported environment variables.
|
||||||
|
///
|
||||||
|
/// Endpoint precedence is `--endpoint`, a positional endpoint, then
|
||||||
|
/// `WIP_ENDPOINT`. Authorization is read only from the variable named by
|
||||||
|
/// `--authorization-env` (default `WIP_AUTHORIZATION`).
|
||||||
|
pub fn from_env() -> Result<Self, ConfigError> {
|
||||||
|
let arguments = std::env::args().skip(1).collect::<Vec<_>>();
|
||||||
|
let endpoint_env = std::env::var("WIP_ENDPOINT").ok();
|
||||||
|
let security_context = std::env::var("WIP_SECURITY_CONTEXT").ok();
|
||||||
|
Self::parse(arguments, endpoint_env, security_context, |name| {
|
||||||
|
std::env::var(name).ok()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses supplied values; exposed to make startup policy independently testable.
|
||||||
|
pub fn parse<I, S, F>(
|
||||||
|
arguments: I,
|
||||||
|
endpoint_env: Option<String>,
|
||||||
|
security_context_env: Option<String>,
|
||||||
|
mut read_secret: F,
|
||||||
|
) -> Result<Self, ConfigError>
|
||||||
|
where
|
||||||
|
I: IntoIterator<Item = S>,
|
||||||
|
S: Into<String>,
|
||||||
|
F: FnMut(&str) -> Option<String>,
|
||||||
|
{
|
||||||
|
let mut endpoint = None;
|
||||||
|
let mut timeout = Duration::from_secs(30);
|
||||||
|
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
|
||||||
|
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
|
||||||
|
let mut iter = arguments.into_iter().map(Into::into);
|
||||||
|
while let Some(argument) = iter.next() {
|
||||||
|
match argument.as_str() {
|
||||||
|
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
|
||||||
|
"--security-context" => {
|
||||||
|
security_context = next_value(&mut iter, "--security-context")?;
|
||||||
|
}
|
||||||
|
"--authorization-env" => {
|
||||||
|
authorization_env = next_value(&mut iter, "--authorization-env")?;
|
||||||
|
}
|
||||||
|
"--timeout" => {
|
||||||
|
let raw = next_value(&mut iter, "--timeout")?;
|
||||||
|
let seconds = raw
|
||||||
|
.parse::<u64>()
|
||||||
|
.ok()
|
||||||
|
.filter(|seconds| *seconds > 0)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
ConfigError::Invalid("--timeout must be a positive integer".into())
|
||||||
|
})?;
|
||||||
|
timeout = Duration::from_secs(seconds);
|
||||||
|
}
|
||||||
|
"--help" | "-h" => return Err(ConfigError::Help),
|
||||||
|
value if value.starts_with('-') => {
|
||||||
|
return Err(ConfigError::Invalid(format!("unknown option {value}")));
|
||||||
|
}
|
||||||
|
value if endpoint.is_none() => endpoint = Some(value.to_owned()),
|
||||||
|
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let supplied = endpoint
|
||||||
|
.or(endpoint_env)
|
||||||
|
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
|
||||||
|
let endpoint =
|
||||||
|
Endpoint::parse(&supplied).map_err(|error| ConfigError::Invalid(error.to_string()))?;
|
||||||
|
if !endpoint.as_url().username().is_empty() || endpoint.as_url().password().is_some() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"endpoint userinfo is not accepted; supply credentials through the configured environment variable"
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !matches!(endpoint.as_url().scheme(), "http" | "https") {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"this HTTP client supports http and https endpoint schemes".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if security_context.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"security context must not be empty".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let authorization = read_secret(&authorization_env)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(Secret);
|
||||||
|
Ok(Self {
|
||||||
|
endpoint: endpoint.to_string(),
|
||||||
|
security_context,
|
||||||
|
timeout,
|
||||||
|
authorization,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns concise command usage without mentioning credential values.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn usage() -> &'static str {
|
||||||
|
"usage: wip-tui [--endpoint] URL [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
|
||||||
|
URL may also be supplied as WIP_ENDPOINT; the HTTP adapter supports http and https."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_value(
|
||||||
|
iter: &mut impl Iterator<Item = String>,
|
||||||
|
option: &str,
|
||||||
|
) -> Result<String, ConfigError> {
|
||||||
|
iter.next()
|
||||||
|
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Startup configuration failure.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
/// Help was requested.
|
||||||
|
Help,
|
||||||
|
/// A safe, non-secret configuration diagnostic.
|
||||||
|
Invalid(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ConfigError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Help => formatter.write_str(Config::usage()),
|
||||||
|
Self::Invalid(detail) => write!(formatter, "{detail}\n{}", Config::usage()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ConfigError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endpoint_is_canonical_and_secrets_are_redacted() {
|
||||||
|
let config = Config::parse(
|
||||||
|
["https://example.test/wip", "--authorization-env", "TOKEN"],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(config.endpoint(), "https://example.test/wip/");
|
||||||
|
let debug = format!("{config:?}");
|
||||||
|
assert!(debug.contains("[REDACTED]"));
|
||||||
|
assert!(!debug.contains("secret-value"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
|
||||||
|
for endpoint in [
|
||||||
|
"https://user:password@example.test/wip",
|
||||||
|
"http://user:password@localhost:3000/wip",
|
||||||
|
] {
|
||||||
|
let error = Config::parse([endpoint], None, None, |_| None).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("userinfo"));
|
||||||
|
assert!(!error.to_string().contains("password"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn http_and_https_are_preserved_as_the_single_endpoint() {
|
||||||
|
for expected in ["http://example.test:3000/wip/", "https://example.test/wip/"] {
|
||||||
|
let supplied = expected.trim_end_matches('/');
|
||||||
|
let config = Config::parse([supplied], None, None, |_| None).unwrap();
|
||||||
|
assert_eq!(config.endpoint(), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,628 @@
|
|||||||
|
//! Descriptor-driven operation argument editing and validation.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::STANDARD;
|
||||||
|
use wip_protocol::{InterfaceDescriptor, OperationDeclaration, TypeExpr, Value};
|
||||||
|
|
||||||
|
const MAX_FIELD_INPUT_BYTES: usize = 256 * 1024;
|
||||||
|
|
||||||
|
/// One editable top-level operation parameter.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArgumentField {
|
||||||
|
/// Parameter name.
|
||||||
|
pub name: String,
|
||||||
|
/// Whether the parameter must be supplied.
|
||||||
|
pub required: bool,
|
||||||
|
/// Canonical descriptor type.
|
||||||
|
pub r#type: TypeExpr,
|
||||||
|
/// User-entered text.
|
||||||
|
pub input: String,
|
||||||
|
/// Field-local validation diagnostic.
|
||||||
|
pub diagnostic: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marker returned when one or more field diagnostics prevent submission.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct InvalidArguments;
|
||||||
|
|
||||||
|
/// Pure, terminal-independent editor built from an operation descriptor.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArgumentEditor {
|
||||||
|
/// Opaque interface reference selected for the call.
|
||||||
|
pub interface: String,
|
||||||
|
/// Selected operation declaration.
|
||||||
|
pub operation: OperationDeclaration,
|
||||||
|
/// Complete descriptor used to resolve named types.
|
||||||
|
pub descriptor: InterfaceDescriptor,
|
||||||
|
/// Top-level parameter fields in declaration order.
|
||||||
|
pub fields: Vec<ArgumentField>,
|
||||||
|
/// Index of the active field.
|
||||||
|
pub cursor: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArgumentEditor {
|
||||||
|
/// Builds an editor whose fields preserve descriptor order.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(
|
||||||
|
interface: impl Into<String>,
|
||||||
|
descriptor: InterfaceDescriptor,
|
||||||
|
operation: OperationDeclaration,
|
||||||
|
) -> Self {
|
||||||
|
let fields = operation
|
||||||
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| ArgumentField {
|
||||||
|
name: parameter.name.clone(),
|
||||||
|
required: parameter.required,
|
||||||
|
r#type: parameter.r#type.clone(),
|
||||||
|
input: if parameter.required && parameter.r#type == TypeExpr::Unit {
|
||||||
|
"null".into()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
|
diagnostic: None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
interface: interface.into(),
|
||||||
|
operation,
|
||||||
|
descriptor,
|
||||||
|
fields,
|
||||||
|
cursor: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves to the preceding field without wrapping.
|
||||||
|
pub fn previous_field(&mut self) {
|
||||||
|
self.cursor = self.cursor.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves to the following field without wrapping.
|
||||||
|
pub fn next_field(&mut self) {
|
||||||
|
if self.cursor + 1 < self.fields.len() {
|
||||||
|
self.cursor += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one printable character to the active field.
|
||||||
|
pub fn insert(&mut self, character: char) {
|
||||||
|
if !character.is_control()
|
||||||
|
&& let Some(field) = self.fields.get_mut(self.cursor)
|
||||||
|
{
|
||||||
|
if field.input.len().saturating_add(character.len_utf8()) <= MAX_FIELD_INPUT_BYTES {
|
||||||
|
field.input.push(character);
|
||||||
|
field.diagnostic = None;
|
||||||
|
} else {
|
||||||
|
field.diagnostic = Some("field input reached the 256 KiB limit".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes one scalar value from the active field.
|
||||||
|
pub fn backspace(&mut self) {
|
||||||
|
if let Some(field) = self.fields.get_mut(self.cursor) {
|
||||||
|
field.input.pop();
|
||||||
|
field.diagnostic = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates all fields and returns protocol values when every field is valid.
|
||||||
|
///
|
||||||
|
/// Invalid or missing values are retained as field-local diagnostics. Optional
|
||||||
|
/// blank fields are omitted from the resulting argument map.
|
||||||
|
pub fn validate(&mut self) -> Result<BTreeMap<String, Value>, InvalidArguments> {
|
||||||
|
let mut arguments = BTreeMap::new();
|
||||||
|
let mut invalid = false;
|
||||||
|
for field in &mut self.fields {
|
||||||
|
field.diagnostic = None;
|
||||||
|
if field.input.len() > MAX_FIELD_INPUT_BYTES {
|
||||||
|
field.diagnostic = Some("field input exceeds the 256 KiB limit".into());
|
||||||
|
invalid = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if field.input.trim().is_empty() {
|
||||||
|
if field.required {
|
||||||
|
field.diagnostic = Some("required value is missing".into());
|
||||||
|
invalid = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match parse_value(
|
||||||
|
&self.descriptor,
|
||||||
|
&field.r#type,
|
||||||
|
field.input.trim(),
|
||||||
|
&field.name,
|
||||||
|
) {
|
||||||
|
Ok(value) => {
|
||||||
|
arguments.insert(field.name.clone(), value);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
field.diagnostic = Some(error);
|
||||||
|
invalid = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if invalid {
|
||||||
|
return Err(InvalidArguments);
|
||||||
|
}
|
||||||
|
if let Err(error) = self
|
||||||
|
.descriptor
|
||||||
|
.validate_arguments(&self.operation.name, &arguments)
|
||||||
|
{
|
||||||
|
if let Some(field) = self.fields.get_mut(self.cursor) {
|
||||||
|
field.diagnostic = Some(error.to_string());
|
||||||
|
}
|
||||||
|
return Err(InvalidArguments);
|
||||||
|
}
|
||||||
|
Ok(arguments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a compact canonical spelling for a type expression.
|
||||||
|
#[must_use]
|
||||||
|
pub fn type_name(r#type: &TypeExpr) -> String {
|
||||||
|
match r#type {
|
||||||
|
TypeExpr::Unit => "Unit".into(),
|
||||||
|
TypeExpr::Boolean => "Boolean".into(),
|
||||||
|
TypeExpr::Integer => "Integer".into(),
|
||||||
|
TypeExpr::Number => "Number".into(),
|
||||||
|
TypeExpr::String => "String".into(),
|
||||||
|
TypeExpr::Bytes => "Bytes(base64)".into(),
|
||||||
|
TypeExpr::Json => "Json".into(),
|
||||||
|
TypeExpr::Entry => "Entry".into(),
|
||||||
|
TypeExpr::Named { name } => name.clone(),
|
||||||
|
TypeExpr::Record { fields } => format!(
|
||||||
|
"Record{{{}}}",
|
||||||
|
fields
|
||||||
|
.iter()
|
||||||
|
.map(|field| format!(
|
||||||
|
"{}{}: {}",
|
||||||
|
field.name,
|
||||||
|
if field.required { "" } else { "?" },
|
||||||
|
type_name(&field.r#type)
|
||||||
|
))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
),
|
||||||
|
TypeExpr::List { items } => format!("List<{}>", type_name(items)),
|
||||||
|
TypeExpr::Enum { cases } => format!(
|
||||||
|
"Enum<{}>",
|
||||||
|
cases
|
||||||
|
.iter()
|
||||||
|
.map(|case| case.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" | ")
|
||||||
|
),
|
||||||
|
TypeExpr::Union { cases } => format!(
|
||||||
|
"Union<{}>",
|
||||||
|
cases
|
||||||
|
.iter()
|
||||||
|
.map(|case| case.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" | ")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_value(
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
r#type: &TypeExpr,
|
||||||
|
input: &str,
|
||||||
|
field: &str,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
if let TypeExpr::Named { name } = r#type {
|
||||||
|
let declaration = descriptor
|
||||||
|
.types
|
||||||
|
.iter()
|
||||||
|
.find(|declaration| declaration.name == *name)
|
||||||
|
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
|
||||||
|
return parse_value(descriptor, &declaration.definition, input, field);
|
||||||
|
}
|
||||||
|
let value = match r#type {
|
||||||
|
TypeExpr::Unit => {
|
||||||
|
if matches!(input, "null" | "()") {
|
||||||
|
Value::Unit
|
||||||
|
} else {
|
||||||
|
return Err(format!("{field}: expected null"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TypeExpr::Boolean => input
|
||||||
|
.parse::<bool>()
|
||||||
|
.map(Value::Boolean)
|
||||||
|
.map_err(|_| format!("{field}: expected true or false"))?,
|
||||||
|
TypeExpr::Integer => input
|
||||||
|
.parse::<i64>()
|
||||||
|
.map(Value::Integer)
|
||||||
|
.map_err(|_| format!("{field}: expected a signed integer"))?,
|
||||||
|
TypeExpr::Number => {
|
||||||
|
let number = input
|
||||||
|
.parse::<f64>()
|
||||||
|
.map_err(|_| format!("{field}: expected a finite number"))?;
|
||||||
|
if !number.is_finite() {
|
||||||
|
return Err(format!("{field}: expected a finite number"));
|
||||||
|
}
|
||||||
|
Value::Number(number)
|
||||||
|
}
|
||||||
|
TypeExpr::String => Value::String(parse_string(input)),
|
||||||
|
TypeExpr::Bytes => Value::Bytes(
|
||||||
|
STANDARD
|
||||||
|
.decode(input)
|
||||||
|
.map_err(|_| format!("{field}: expected RFC 4648 base64"))?,
|
||||||
|
),
|
||||||
|
TypeExpr::Entry => {
|
||||||
|
let path = parse_string(input);
|
||||||
|
wip_protocol::validate_path(&path)
|
||||||
|
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
|
||||||
|
Value::String(path)
|
||||||
|
}
|
||||||
|
TypeExpr::Enum { cases } => {
|
||||||
|
let case = parse_string(input);
|
||||||
|
if !cases.iter().any(|candidate| candidate.name == case) {
|
||||||
|
return Err(format!("{field}: unknown enum case {case}"));
|
||||||
|
}
|
||||||
|
Value::String(case)
|
||||||
|
}
|
||||||
|
TypeExpr::Json => {
|
||||||
|
let json = serde_json::from_str(input)
|
||||||
|
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
|
||||||
|
json_to_untyped(&json, field)?
|
||||||
|
}
|
||||||
|
TypeExpr::Record { .. } | TypeExpr::List { .. } | TypeExpr::Union { .. } => {
|
||||||
|
let json = serde_json::from_str(input)
|
||||||
|
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
|
||||||
|
json_to_typed(descriptor, r#type, &json, field)?
|
||||||
|
}
|
||||||
|
TypeExpr::Named { .. } => unreachable!("named types handled above"),
|
||||||
|
};
|
||||||
|
descriptor
|
||||||
|
.validate_value(r#type, &value)
|
||||||
|
.map_err(|error| format!("{field}: {error}"))?;
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_string(input: &str) -> String {
|
||||||
|
serde_json::from_str::<String>(input).unwrap_or_else(|_| input.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_to_typed(
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
r#type: &TypeExpr,
|
||||||
|
json: &serde_json::Value,
|
||||||
|
field: &str,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
if let TypeExpr::Named { name } = r#type {
|
||||||
|
let declaration = descriptor
|
||||||
|
.types
|
||||||
|
.iter()
|
||||||
|
.find(|declaration| declaration.name == *name)
|
||||||
|
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
|
||||||
|
return json_to_typed(descriptor, &declaration.definition, json, field);
|
||||||
|
}
|
||||||
|
match r#type {
|
||||||
|
TypeExpr::Unit if json.is_null() => Ok(Value::Unit),
|
||||||
|
TypeExpr::Boolean => json
|
||||||
|
.as_bool()
|
||||||
|
.map(Value::Boolean)
|
||||||
|
.ok_or_else(|| format!("{field}: expected boolean")),
|
||||||
|
TypeExpr::Integer => json
|
||||||
|
.as_i64()
|
||||||
|
.map(Value::Integer)
|
||||||
|
.ok_or_else(|| format!("{field}: expected integer")),
|
||||||
|
TypeExpr::Number => json
|
||||||
|
.as_f64()
|
||||||
|
.filter(|value| value.is_finite())
|
||||||
|
.map(Value::Number)
|
||||||
|
.ok_or_else(|| format!("{field}: expected finite number")),
|
||||||
|
TypeExpr::String => json
|
||||||
|
.as_str()
|
||||||
|
.map(|value| Value::String(value.into()))
|
||||||
|
.ok_or_else(|| format!("{field}: expected string")),
|
||||||
|
TypeExpr::Bytes => json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected base64 string"))
|
||||||
|
.and_then(|value| {
|
||||||
|
STANDARD
|
||||||
|
.decode(value)
|
||||||
|
.map(Value::Bytes)
|
||||||
|
.map_err(|_| format!("{field}: expected RFC 4648 base64"))
|
||||||
|
}),
|
||||||
|
TypeExpr::Entry => {
|
||||||
|
let path = json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected Entry string"))?;
|
||||||
|
wip_protocol::validate_path(path)
|
||||||
|
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
|
||||||
|
Ok(Value::String(path.into()))
|
||||||
|
}
|
||||||
|
TypeExpr::Enum { cases } => {
|
||||||
|
let case = json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected enum string"))?;
|
||||||
|
if !cases.iter().any(|candidate| candidate.name == case) {
|
||||||
|
return Err(format!("{field}: unknown enum case {case}"));
|
||||||
|
}
|
||||||
|
Ok(Value::String(case.into()))
|
||||||
|
}
|
||||||
|
TypeExpr::Json => json_to_untyped(json, field),
|
||||||
|
TypeExpr::List { items } => json
|
||||||
|
.as_array()
|
||||||
|
.ok_or_else(|| format!("{field}: expected array"))?
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, item)| {
|
||||||
|
json_to_typed(descriptor, items, item, &format!("{field}[{index}]"))
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map(Value::List),
|
||||||
|
TypeExpr::Record { fields } => {
|
||||||
|
let object = json
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| format!("{field}: expected object"))?;
|
||||||
|
for name in object.keys() {
|
||||||
|
if !fields.iter().any(|candidate| candidate.name == *name) {
|
||||||
|
return Err(format!("{field}.{name}: unknown field"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut values = BTreeMap::new();
|
||||||
|
for declaration in fields {
|
||||||
|
match object.get(&declaration.name) {
|
||||||
|
Some(value) => {
|
||||||
|
values.insert(
|
||||||
|
declaration.name.clone(),
|
||||||
|
json_to_typed(
|
||||||
|
descriptor,
|
||||||
|
&declaration.r#type,
|
||||||
|
value,
|
||||||
|
&format!("{field}.{}", declaration.name),
|
||||||
|
)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
None if declaration.required => {
|
||||||
|
return Err(format!(
|
||||||
|
"{field}.{}: required field is missing",
|
||||||
|
declaration.name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Value::Record(values))
|
||||||
|
}
|
||||||
|
TypeExpr::Union { cases } => {
|
||||||
|
let object = json
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| format!("{field}: expected union object"))?;
|
||||||
|
if object.keys().any(|name| name != "$case" && name != "value") {
|
||||||
|
return Err(format!("{field}: union accepts only $case and value"));
|
||||||
|
}
|
||||||
|
let case_name = object
|
||||||
|
.get("$case")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.ok_or_else(|| format!("{field}.$case: required string is missing"))?;
|
||||||
|
let case = cases
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.name == case_name)
|
||||||
|
.ok_or_else(|| format!("{field}.$case: unknown union case {case_name}"))?;
|
||||||
|
let mut values = BTreeMap::from([("$case".into(), Value::String(case_name.into()))]);
|
||||||
|
match (&case.payload, object.get("value")) {
|
||||||
|
(Some(payload), Some(value)) => {
|
||||||
|
values.insert(
|
||||||
|
"value".into(),
|
||||||
|
json_to_typed(descriptor, payload, value, &format!("{field}.value"))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
(Some(_), None) => {
|
||||||
|
return Err(format!("{field}.value: required payload is missing"));
|
||||||
|
}
|
||||||
|
(None, Some(_)) => {
|
||||||
|
return Err(format!("{field}.value: payload-free case has a value"));
|
||||||
|
}
|
||||||
|
(None, None) => {}
|
||||||
|
}
|
||||||
|
Ok(Value::Record(values))
|
||||||
|
}
|
||||||
|
TypeExpr::Named { .. } => unreachable!("named types handled above"),
|
||||||
|
_ => Err(format!(
|
||||||
|
"{field}: value does not match {}",
|
||||||
|
type_name(r#type)
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_to_untyped(json: &serde_json::Value, field: &str) -> Result<Value, String> {
|
||||||
|
match json {
|
||||||
|
serde_json::Value::Null => Ok(Value::Unit),
|
||||||
|
serde_json::Value::Bool(value) => Ok(Value::Boolean(*value)),
|
||||||
|
serde_json::Value::Number(value) => {
|
||||||
|
if let Some(integer) = value.as_i64() {
|
||||||
|
Ok(Value::Integer(integer))
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
.as_f64()
|
||||||
|
.filter(|number| number.is_finite())
|
||||||
|
.map(Value::Number)
|
||||||
|
.ok_or_else(|| format!("{field}: number is not finite"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::String(value) => Ok(Value::String(value.clone())),
|
||||||
|
serde_json::Value::Array(values) => values
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, value)| json_to_untyped(value, &format!("{field}[{index}]")))
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map(Value::List),
|
||||||
|
serde_json::Value::Object(values) => values
|
||||||
|
.iter()
|
||||||
|
.map(|(name, value)| {
|
||||||
|
json_to_untyped(value, &format!("{field}.{name}"))
|
||||||
|
.map(|value| (name.clone(), value))
|
||||||
|
})
|
||||||
|
.collect::<Result<BTreeMap<_, _>, _>>()
|
||||||
|
.map(Value::Record),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use wip_protocol::{
|
||||||
|
EnumCase, FieldDeclaration, INTERFACE_FORMAT_V1, ParameterDeclaration, ReturnDeclaration,
|
||||||
|
TypeDeclaration, UnionCase,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn descriptor(
|
||||||
|
parameters: Vec<ParameterDeclaration>,
|
||||||
|
types: Vec<TypeDeclaration>,
|
||||||
|
) -> InterfaceDescriptor {
|
||||||
|
InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types,
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "run".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters,
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_every_canonical_shape_and_reports_fields() {
|
||||||
|
let parameters = vec![
|
||||||
|
parameter("unit", true, TypeExpr::Unit),
|
||||||
|
parameter("flag", true, TypeExpr::Boolean),
|
||||||
|
parameter("count", true, TypeExpr::Integer),
|
||||||
|
parameter("number", true, TypeExpr::Number),
|
||||||
|
parameter("text", true, TypeExpr::String),
|
||||||
|
parameter("bytes", true, TypeExpr::Bytes),
|
||||||
|
parameter("entry", true, TypeExpr::Entry),
|
||||||
|
parameter("json", true, TypeExpr::Json),
|
||||||
|
parameter(
|
||||||
|
"list",
|
||||||
|
true,
|
||||||
|
TypeExpr::List {
|
||||||
|
items: Box::new(TypeExpr::Integer),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"record",
|
||||||
|
true,
|
||||||
|
TypeExpr::Record {
|
||||||
|
fields: vec![FieldDeclaration {
|
||||||
|
name: "name".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"choice",
|
||||||
|
true,
|
||||||
|
TypeExpr::Enum {
|
||||||
|
cases: vec![EnumCase {
|
||||||
|
name: "yes".into(),
|
||||||
|
documentation: None,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"union",
|
||||||
|
true,
|
||||||
|
TypeExpr::Union {
|
||||||
|
cases: vec![UnionCase {
|
||||||
|
name: "some".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: Some(TypeExpr::Integer),
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"named",
|
||||||
|
true,
|
||||||
|
TypeExpr::Named {
|
||||||
|
name: "Alias".into(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let descriptor = descriptor(
|
||||||
|
parameters,
|
||||||
|
vec![TypeDeclaration {
|
||||||
|
name: "Alias".into(),
|
||||||
|
documentation: None,
|
||||||
|
definition: TypeExpr::String,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let operation = descriptor.operations[0].clone();
|
||||||
|
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
||||||
|
let inputs = [
|
||||||
|
"null",
|
||||||
|
"true",
|
||||||
|
"7",
|
||||||
|
"2.5",
|
||||||
|
"hello",
|
||||||
|
"aGk=",
|
||||||
|
"/item",
|
||||||
|
"{\"safe\":true}",
|
||||||
|
"[1,2]",
|
||||||
|
"{\"name\":\"n\"}",
|
||||||
|
"yes",
|
||||||
|
"{\"$case\":\"some\",\"value\":4}",
|
||||||
|
"value",
|
||||||
|
];
|
||||||
|
for (field, input) in editor.fields.iter_mut().zip(inputs) {
|
||||||
|
field.input = input.into();
|
||||||
|
}
|
||||||
|
let values = editor.validate().expect("valid values");
|
||||||
|
assert_eq!(values["bytes"], Value::Bytes(b"hi".to_vec()));
|
||||||
|
assert_eq!(values["entry"], Value::String("/item".into()));
|
||||||
|
assert!(editor.fields.iter().all(|field| field.diagnostic.is_none()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_invalid_and_optional_fields_are_field_local() {
|
||||||
|
let descriptor = descriptor(
|
||||||
|
vec![
|
||||||
|
parameter("required", true, TypeExpr::Integer),
|
||||||
|
parameter("optional", false, TypeExpr::Boolean),
|
||||||
|
],
|
||||||
|
vec![],
|
||||||
|
);
|
||||||
|
let operation = descriptor.operations[0].clone();
|
||||||
|
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
||||||
|
editor.fields[1].input = "not-a-bool".into();
|
||||||
|
assert_eq!(editor.validate(), Err(InvalidArguments));
|
||||||
|
assert!(
|
||||||
|
editor.fields[0]
|
||||||
|
.diagnostic
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("required")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
editor.fields[1]
|
||||||
|
.diagnostic
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("true or false")
|
||||||
|
);
|
||||||
|
editor.fields[0].input = "1".into();
|
||||||
|
editor.fields[1].input.clear();
|
||||||
|
assert_eq!(editor.validate().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter(name: &str, required: bool, r#type: TypeExpr) -> ParameterDeclaration {
|
||||||
|
ParameterDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
required,
|
||||||
|
documentation: None,
|
||||||
|
r#type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//! Presentation and terminal interaction for stateful WIP client sessions.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
pub mod app;
|
||||||
|
pub mod config;
|
||||||
|
pub mod editor;
|
||||||
|
pub mod render;
|
||||||
|
pub mod runtime;
|
||||||
|
pub mod terminal;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
fn main() {
|
||||||
|
if let Err(error) = wip_tui::runtime::run_from_env() {
|
||||||
|
eprintln!("wip-tui: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,851 @@
|
|||||||
|
//! Deterministic bounded rendering for real and test terminal backends.
|
||||||
|
|
||||||
|
use ratatui::Frame;
|
||||||
|
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
|
||||||
|
use ratatui::style::{Color, Modifier, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap};
|
||||||
|
|
||||||
|
use crate::app::{App, ConnectionState, Focus, HistoryKind, Modal, OperationRow, ViewState};
|
||||||
|
use crate::editor::type_name;
|
||||||
|
|
||||||
|
const MAX_RENDER_TEXT: usize = 512;
|
||||||
|
|
||||||
|
/// Draws the complete application without mutating it.
|
||||||
|
pub fn draw(frame: &mut Frame<'_>, app: &App) {
|
||||||
|
let area = frame.area();
|
||||||
|
if area.width < 48 || area.height < 14 {
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new("wip-tui\nTerminal is too small. Resize to at least 48 x 14.\nq: quit")
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Minimum size "),
|
||||||
|
)
|
||||||
|
.alignment(Alignment::Center)
|
||||||
|
.wrap(Wrap { trim: true }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let vertical = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(2),
|
||||||
|
Constraint::Min(8),
|
||||||
|
Constraint::Length(2),
|
||||||
|
])
|
||||||
|
.split(area);
|
||||||
|
render_header(frame, vertical[0], app);
|
||||||
|
let columns = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([Constraint::Percentage(38), Constraint::Percentage(62)])
|
||||||
|
.split(vertical[1]);
|
||||||
|
render_tree(frame, columns[0], app);
|
||||||
|
let right = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(31),
|
||||||
|
Constraint::Percentage(39),
|
||||||
|
Constraint::Percentage(30),
|
||||||
|
])
|
||||||
|
.split(columns[1]);
|
||||||
|
render_selected(frame, right[0], app);
|
||||||
|
render_operations(frame, right[1], app);
|
||||||
|
render_history(frame, right[2], app);
|
||||||
|
render_footer(frame, vertical[2], app);
|
||||||
|
render_modal(frame, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_header(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let connection = match &app.connection {
|
||||||
|
ConnectionState::Disconnected => "DISCONNECTED",
|
||||||
|
ConnectionState::Connecting => "CONNECTING",
|
||||||
|
ConnectionState::Connected => "CONNECTED",
|
||||||
|
ConnectionState::Failed(_) => "FAILED (R reconnect / q quit)",
|
||||||
|
};
|
||||||
|
let text = format!(
|
||||||
|
" wip-tui {} [{}] in-flight: {}",
|
||||||
|
sanitize(&app.endpoint),
|
||||||
|
connection,
|
||||||
|
app.in_flight.len()
|
||||||
|
);
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(text).style(Style::default().add_modifier(Modifier::BOLD)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_tree(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let mut paths = app.visible_paths();
|
||||||
|
let selected_index = paths
|
||||||
|
.iter()
|
||||||
|
.position(|path| path == &app.selected_path)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let (start, end) = list_window(paths.len(), selected_index, area.height.saturating_sub(2));
|
||||||
|
let rows = paths.drain(start..end).map(|path| {
|
||||||
|
let node = app.entries.get(&path);
|
||||||
|
let selected = path == app.selected_path;
|
||||||
|
let depth = if path == "/" {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
path.trim_start_matches('/').split('/').count()
|
||||||
|
};
|
||||||
|
let marker = node.map_or('·', |node| if node.expanded { '▼' } else { '▶' });
|
||||||
|
let label = node.and_then(|node| node.object.as_ref()).map_or_else(
|
||||||
|
|| path.clone(),
|
||||||
|
|object| {
|
||||||
|
if path == "/" {
|
||||||
|
"/".into()
|
||||||
|
} else {
|
||||||
|
object.name.clone()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let mut suffix = node.map_or_else(
|
||||||
|
|| " [unloaded]".into(),
|
||||||
|
|node| {
|
||||||
|
let tree = match &node.tree_state {
|
||||||
|
ViewState::Loading(_) => " [loading children]",
|
||||||
|
ViewState::Stale => " [stale children]",
|
||||||
|
ViewState::Error(_) => " [failed children]",
|
||||||
|
ViewState::Fresh if node.children.is_empty() => " [empty]",
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
let object = state_suffix(&node.state);
|
||||||
|
format!("{object}{tree}")
|
||||||
|
},
|
||||||
|
);
|
||||||
|
suffix = sanitize(&suffix);
|
||||||
|
let style = if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
};
|
||||||
|
ListItem::new(Line::from(vec![
|
||||||
|
Span::raw(" ".repeat(depth)),
|
||||||
|
Span::raw(format!("{marker} {}", sanitize(&label))),
|
||||||
|
Span::styled(suffix, state_style(node.map(|value| &value.state))),
|
||||||
|
]))
|
||||||
|
.style(style)
|
||||||
|
});
|
||||||
|
frame.render_widget(
|
||||||
|
List::new(rows).block(focused_block(" Worldspace tree ", app.focus == Focus::Tree)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_selected(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let mut lines = vec![Line::from(format!(
|
||||||
|
"Path: {}",
|
||||||
|
sanitize(&app.selected_path)
|
||||||
|
))];
|
||||||
|
if let Some(entry) = app.entries.get(&app.selected_path) {
|
||||||
|
lines.push(Line::from(format!("State: {}", state_label(&entry.state))));
|
||||||
|
if entry.state == ViewState::Fresh {
|
||||||
|
if let Some(object) = &entry.object {
|
||||||
|
lines.push(Line::from(format!("Name: {}", sanitize(&object.name))));
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"Description: {}",
|
||||||
|
object
|
||||||
|
.description
|
||||||
|
.as_deref()
|
||||||
|
.map(sanitize)
|
||||||
|
.unwrap_or_else(|| "(none)".into())
|
||||||
|
)));
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"Interfaces (ordered): {}",
|
||||||
|
if object.interfaces.is_empty() {
|
||||||
|
"(none)".into()
|
||||||
|
} else {
|
||||||
|
object
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.map(|value| sanitize(value))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
}
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(Line::from(
|
||||||
|
"No current object metadata; refresh required (old metadata hidden).",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(focused_block(" Selected Entry ", app.focus == Focus::Entry))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_operations(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let rows = app.operation_rows();
|
||||||
|
let selected_index = app.operation_cursor.min(rows.len().saturating_sub(1));
|
||||||
|
let (start, end) = list_window(rows.len(), selected_index, area.height.saturating_sub(2));
|
||||||
|
let items = rows[start..end].iter().enumerate().map(|(offset, row)| {
|
||||||
|
let index = start + offset;
|
||||||
|
let (text, style) = operation_line(app, row);
|
||||||
|
let selected = app.focus == Focus::Operations && index == app.operation_cursor;
|
||||||
|
ListItem::new(text).style(if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
style
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let title = " Interfaces / Operations (Enter: load or edit) ";
|
||||||
|
if rows.is_empty() {
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new("No declared interfaces or no current object.")
|
||||||
|
.block(focused_block(title, app.focus == Focus::Operations)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
frame.render_widget(
|
||||||
|
List::new(items).block(focused_block(title, app.focus == Focus::Operations)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
|
||||||
|
if let Some(name) = &row.operation {
|
||||||
|
let descriptor = app
|
||||||
|
.interfaces
|
||||||
|
.get(&row.interface)
|
||||||
|
.and_then(|view| view.descriptor.as_ref());
|
||||||
|
let declaration = descriptor.and_then(|descriptor| {
|
||||||
|
descriptor
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.name == *name)
|
||||||
|
});
|
||||||
|
let signature = declaration.map_or_else(
|
||||||
|
|| format!(" ({}, {})", row.interface, name),
|
||||||
|
|operation| {
|
||||||
|
let parameters = operation
|
||||||
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| {
|
||||||
|
format!(
|
||||||
|
"{}{}: {}",
|
||||||
|
parameter.name,
|
||||||
|
if parameter.required { "" } else { "?" },
|
||||||
|
type_name(¶meter.r#type)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
let documentation = operation
|
||||||
|
.documentation
|
||||||
|
.as_ref()
|
||||||
|
.map(|documentation| format!(" — {}", documentation.summary))
|
||||||
|
.unwrap_or_default();
|
||||||
|
format!(
|
||||||
|
" ({}, {}) ({parameters}) -> {}{}",
|
||||||
|
row.interface,
|
||||||
|
name,
|
||||||
|
type_name(&operation.returns.r#type),
|
||||||
|
documentation
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
|
(Line::from(sanitize(&signature)), Style::default())
|
||||||
|
} else {
|
||||||
|
let interface = app.interfaces.get(&row.interface);
|
||||||
|
let state = interface.map_or("unloaded".into(), |view| state_label(&view.state));
|
||||||
|
let documentation = interface
|
||||||
|
.filter(|view| view.state == ViewState::Fresh)
|
||||||
|
.and_then(|view| view.descriptor.as_ref())
|
||||||
|
.and_then(|descriptor| descriptor.documentation.as_ref())
|
||||||
|
.map(|documentation| format!(" — {}", sanitize(&documentation.summary)))
|
||||||
|
.unwrap_or_default();
|
||||||
|
(
|
||||||
|
Line::from(format!(
|
||||||
|
"Interface {} [{}]{}",
|
||||||
|
sanitize(&row.interface),
|
||||||
|
state,
|
||||||
|
documentation
|
||||||
|
)),
|
||||||
|
Style::default().add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_history(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let selected_index = app.history_cursor.min(app.history.len().saturating_sub(1));
|
||||||
|
let (start, end) = list_window(
|
||||||
|
app.history.len(),
|
||||||
|
selected_index,
|
||||||
|
area.height.saturating_sub(2),
|
||||||
|
);
|
||||||
|
let items = app.history[start..end]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(offset, item)| {
|
||||||
|
let index = start + offset;
|
||||||
|
let label = match item.kind {
|
||||||
|
HistoryKind::Success => "SUCCESS",
|
||||||
|
HistoryKind::DomainFailure => "HOST FAILURE",
|
||||||
|
HistoryKind::ProtocolError => "PROTOCOL ERROR",
|
||||||
|
HistoryKind::TransportFailure => "TRANSPORT FAILURE",
|
||||||
|
HistoryKind::ClientFailure => "CLIENT FAILURE",
|
||||||
|
HistoryKind::OutcomeUnknown => "OUTCOME UNKNOWN",
|
||||||
|
HistoryKind::Information => "INFO",
|
||||||
|
};
|
||||||
|
let link = item
|
||||||
|
.entry_target
|
||||||
|
.as_ref()
|
||||||
|
.map_or("", |_| " [Enter: go to Entry]");
|
||||||
|
let text = format!(
|
||||||
|
"[{label}] {}: {}{link}",
|
||||||
|
sanitize(&item.title),
|
||||||
|
sanitize(&item.detail)
|
||||||
|
);
|
||||||
|
let selected = app.focus == Focus::History && index == app.history_cursor;
|
||||||
|
ListItem::new(text).style(if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else if item.kind == HistoryKind::OutcomeUnknown {
|
||||||
|
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let block = focused_block(
|
||||||
|
" Recent results / diagnostics ",
|
||||||
|
app.focus == Focus::History,
|
||||||
|
);
|
||||||
|
if app.history.is_empty() {
|
||||||
|
frame.render_widget(Paragraph::new("No results yet.").block(block), area);
|
||||||
|
} else {
|
||||||
|
frame.render_widget(List::new(items).block(block), area);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_footer(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let help = " ↑↓/jk move ←→/hl parent/expand Tab focus Enter select r refresh + larger tree c cancel read ? help q quit ";
|
||||||
|
let text = format!("{}\n{}", help, sanitize(&app.status));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(text).style(Style::default().fg(Color::DarkGray)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_modal(frame: &mut Frame<'_>, app: &App) {
|
||||||
|
match &app.modal {
|
||||||
|
Modal::None => {}
|
||||||
|
Modal::Help => {
|
||||||
|
let area = centered(frame.area(), 76, 70);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(
|
||||||
|
"Keyboard help\n\n↑/↓ or j/k move selection / editor field\n←/→ or h/l collapse/expand or parent\nTab next pane\nEnter load interface, edit operation, confirm execute\nr refresh selected Entry and subtree\nc cancel newest retrieval (never cancels a sent operation)\nR reconnect after failure\nEsc close modal\nq quit\n\nOperations are never sent until the confirmation screen is accepted.",
|
||||||
|
)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title(" Help "))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Modal::Editor(editor) => {
|
||||||
|
let area = centered(frame.area(), 86, 78);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
let mut lines = vec![Line::from(format!(
|
||||||
|
"Target: {} Operation: ({}, {})",
|
||||||
|
sanitize(&app.selected_path),
|
||||||
|
sanitize(&editor.interface),
|
||||||
|
sanitize(&editor.operation.name)
|
||||||
|
))];
|
||||||
|
if editor.fields.is_empty() {
|
||||||
|
lines.push(Line::from("(no parameters)"));
|
||||||
|
}
|
||||||
|
for (index, field) in editor.fields.iter().enumerate() {
|
||||||
|
let cursor = if index == editor.cursor { ">" } else { " " };
|
||||||
|
let requirement = if field.required {
|
||||||
|
"required"
|
||||||
|
} else {
|
||||||
|
"optional"
|
||||||
|
};
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"{cursor} {} [{requirement}, {}] = {}",
|
||||||
|
sanitize(&field.name),
|
||||||
|
sanitize(&type_name(&field.r#type)),
|
||||||
|
sanitize(&field.input)
|
||||||
|
)));
|
||||||
|
if let Some(diagnostic) = &field.diagnostic {
|
||||||
|
lines.push(Line::styled(
|
||||||
|
format!(" ERROR: {}", sanitize(diagnostic)),
|
||||||
|
Style::default().fg(Color::Red),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(Line::from("Enter: validate and review Esc: cancel"));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Argument editor "),
|
||||||
|
)
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Modal::Confirm { editor, arguments } => {
|
||||||
|
let area = centered(frame.area(), 82, 58);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
let mut lines = vec![
|
||||||
|
Line::styled(
|
||||||
|
"EXPLICIT EXECUTION CONFIRMATION",
|
||||||
|
Style::default()
|
||||||
|
.fg(Color::Yellow)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Line::from(format!("Entry: {}", sanitize(&app.selected_path))),
|
||||||
|
Line::from(format!("Interface: {}", sanitize(&editor.interface))),
|
||||||
|
Line::from(format!("Operation: {}", sanitize(&editor.operation.name))),
|
||||||
|
Line::from("Input values:"),
|
||||||
|
];
|
||||||
|
for (name, value) in arguments {
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
" {} = {}",
|
||||||
|
sanitize(name),
|
||||||
|
sanitize(&bounded_value(value))
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(Line::styled(
|
||||||
|
"Enter/e: EXECUTE ONCE Esc: back to editor",
|
||||||
|
Style::default().add_modifier(Modifier::BOLD),
|
||||||
|
));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title(" Confirm "))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_window(total: usize, selected: usize, area_height: u16) -> (usize, usize) {
|
||||||
|
let capacity = usize::from(area_height);
|
||||||
|
if total == 0 || capacity == 0 {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
let selected = selected.min(total - 1);
|
||||||
|
let start = selected
|
||||||
|
.saturating_add(1)
|
||||||
|
.saturating_sub(capacity)
|
||||||
|
.min(total.saturating_sub(capacity));
|
||||||
|
(start, start.saturating_add(capacity).min(total))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn focused_block(title: &'static str, focused: bool) -> Block<'static> {
|
||||||
|
let style = if focused {
|
||||||
|
Style::default().fg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
};
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(title)
|
||||||
|
.border_style(style)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn centered(area: Rect, percent_x: u16, percent_y: u16) -> Rect {
|
||||||
|
let vertical = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
|
Constraint::Percentage(percent_y),
|
||||||
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
|
])
|
||||||
|
.split(area);
|
||||||
|
Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
|
Constraint::Percentage(percent_x),
|
||||||
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
|
])
|
||||||
|
.split(vertical[1])[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_suffix(state: &ViewState) -> &'static str {
|
||||||
|
match state {
|
||||||
|
ViewState::Unloaded => " [unloaded]",
|
||||||
|
ViewState::Loading(_) => " [loading]",
|
||||||
|
ViewState::Fresh => "",
|
||||||
|
ViewState::Stale => " [stale: refresh required]",
|
||||||
|
ViewState::Error(_) => " [error]",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_label(state: &ViewState) -> String {
|
||||||
|
match state {
|
||||||
|
ViewState::Unloaded => "unloaded".into(),
|
||||||
|
ViewState::Loading(id) => format!("loading request #{id}"),
|
||||||
|
ViewState::Fresh => "fresh".into(),
|
||||||
|
ViewState::Stale => "stale — refresh required".into(),
|
||||||
|
ViewState::Error(error) => format!("error — {}", sanitize(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_style(state: Option<&ViewState>) -> Style {
|
||||||
|
match state {
|
||||||
|
Some(ViewState::Stale) => Style::default().fg(Color::Yellow),
|
||||||
|
Some(ViewState::Error(_)) => Style::default().fg(Color::Red),
|
||||||
|
Some(ViewState::Loading(_)) => Style::default().fg(Color::Blue),
|
||||||
|
_ => Style::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces terminal control characters and bounds user/remote text by Unicode scalars.
|
||||||
|
#[must_use]
|
||||||
|
pub fn sanitize(input: &str) -> String {
|
||||||
|
let mut output = String::new();
|
||||||
|
for (count, character) in input.chars().enumerate() {
|
||||||
|
if count >= MAX_RENDER_TEXT {
|
||||||
|
output.push('…');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if character.is_control() && !matches!(character, '\n' | '\t') {
|
||||||
|
output.push('�');
|
||||||
|
} else {
|
||||||
|
output.push(character);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formats a protocol value with strict byte and collection bounds.
|
||||||
|
#[must_use]
|
||||||
|
pub fn bounded_value(value: &wip_protocol::Value) -> String {
|
||||||
|
bounded_value_at(value, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bounded_value_at(value: &wip_protocol::Value, depth: usize) -> String {
|
||||||
|
if depth >= 8 {
|
||||||
|
return "…".into();
|
||||||
|
}
|
||||||
|
match value {
|
||||||
|
wip_protocol::Value::Unit => "null".into(),
|
||||||
|
wip_protocol::Value::Boolean(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::Integer(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::Number(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::String(value) => format!("{:?}", sanitize(value)),
|
||||||
|
wip_protocol::Value::Bytes(bytes) => {
|
||||||
|
let shown = bytes
|
||||||
|
.iter()
|
||||||
|
.take(32)
|
||||||
|
.map(|byte| format!("{byte:02x}"))
|
||||||
|
.collect::<String>();
|
||||||
|
if bytes.len() > 32 {
|
||||||
|
format!("bytes[{}]: {shown}…", bytes.len())
|
||||||
|
} else {
|
||||||
|
format!("bytes[{}]: {shown}", bytes.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wip_protocol::Value::Record(values) => {
|
||||||
|
let mut fields = values
|
||||||
|
.iter()
|
||||||
|
.take(16)
|
||||||
|
.map(|(name, value)| {
|
||||||
|
format!("{}: {}", sanitize(name), bounded_value_at(value, depth + 1))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if values.len() > 16 {
|
||||||
|
fields.push("…".into());
|
||||||
|
}
|
||||||
|
format!("{{{}}}", fields.join(", "))
|
||||||
|
}
|
||||||
|
wip_protocol::Value::List(values) => {
|
||||||
|
let mut items = values
|
||||||
|
.iter()
|
||||||
|
.take(16)
|
||||||
|
.map(|value| bounded_value_at(value, depth + 1))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if values.len() > 16 {
|
||||||
|
items.push("…".into());
|
||||||
|
}
|
||||||
|
format!("[{}]", items.join(", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::app::{EntryView, HistoryItem};
|
||||||
|
use crate::editor::ArgumentEditor;
|
||||||
|
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState};
|
||||||
|
use wip_protocol::{
|
||||||
|
INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, OperationDeclaration,
|
||||||
|
ParameterDeclaration, ReturnDeclaration, TypeExpr,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn rendered(app: &App, width: u16, height: u16) -> String {
|
||||||
|
let backend = TestBackend::new(width, height);
|
||||||
|
let mut terminal = Terminal::new(backend).unwrap();
|
||||||
|
terminal.draw(|frame| draw(frame, app)).unwrap();
|
||||||
|
terminal
|
||||||
|
.backend()
|
||||||
|
.buffer()
|
||||||
|
.content
|
||||||
|
.iter()
|
||||||
|
.map(|cell| cell.symbol())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.chunks(width as usize)
|
||||||
|
.map(|line| line.concat())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observed_empty_visible_entry_is_labeled_without_expansion() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
{
|
||||||
|
let root = app.entries.get_mut("/").unwrap();
|
||||||
|
root.children = vec!["/empty".into()];
|
||||||
|
root.tree_state = ViewState::Fresh;
|
||||||
|
}
|
||||||
|
app.entries.insert(
|
||||||
|
"/empty".into(),
|
||||||
|
EntryView {
|
||||||
|
path: "/empty".into(),
|
||||||
|
object: Some(Object {
|
||||||
|
name: "empty".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
}),
|
||||||
|
state: ViewState::Fresh,
|
||||||
|
children: vec![],
|
||||||
|
tree_state: ViewState::Fresh,
|
||||||
|
expanded: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let snapshot = rendered(&app, 80, 20);
|
||||||
|
assert!(snapshot.contains("empty [empty]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshot_contains_non_color_state_markers_and_hides_validators() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
app.entries.get_mut("/").unwrap().state = ViewState::Stale;
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::OutcomeUnknown,
|
||||||
|
title: "replace".into(),
|
||||||
|
detail: "execution and side effects are unknown; refresh before deciding again".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
let snapshot = rendered(&app, 110, 30);
|
||||||
|
assert!(snapshot.contains("stale"));
|
||||||
|
assert!(snapshot.contains("OUTCOME UNKNOWN"));
|
||||||
|
assert!(!snapshot.contains("validator"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshots_cover_selected_operation_editor_and_failure_categories() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(Object {
|
||||||
|
name: String::new(),
|
||||||
|
description: Some("public root description".into()),
|
||||||
|
interfaces: vec!["demo-interface".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
}),
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let descriptor = InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "run".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![ParameterDeclaration {
|
||||||
|
name: "count".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Integer,
|
||||||
|
}],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "demo-interface".into(),
|
||||||
|
descriptor: Some(descriptor.clone()),
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
for (kind, title) in [
|
||||||
|
(HistoryKind::Success, "result"),
|
||||||
|
(HistoryKind::ProtocolError, "invalid response"),
|
||||||
|
(HistoryKind::TransportFailure, "network"),
|
||||||
|
(HistoryKind::ClientFailure, "local"),
|
||||||
|
] {
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind,
|
||||||
|
title: title.into(),
|
||||||
|
detail: "bounded detail".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let snapshot = rendered(&app, 140, 40);
|
||||||
|
assert!(snapshot.contains("public root description"));
|
||||||
|
assert!(snapshot.contains("(demo-interface, run)"));
|
||||||
|
assert!(snapshot.contains("SUCCESS"));
|
||||||
|
assert!(snapshot.contains("PROTOCOL ERROR"));
|
||||||
|
assert!(snapshot.contains("TRANSPORT FAILURE"));
|
||||||
|
assert!(snapshot.contains("CLIENT FAILURE"));
|
||||||
|
assert!(!snapshot.contains("must-not-render"));
|
||||||
|
|
||||||
|
let mut editor = ArgumentEditor::new(
|
||||||
|
"demo-interface",
|
||||||
|
descriptor.clone(),
|
||||||
|
descriptor.operations[0].clone(),
|
||||||
|
);
|
||||||
|
editor.fields[0].diagnostic = Some("expected integer".into());
|
||||||
|
app.modal = Modal::Editor(editor);
|
||||||
|
let snapshot = rendered(&app, 140, 40);
|
||||||
|
assert!(snapshot.contains("Argument editor"));
|
||||||
|
assert!(snapshot.contains("count [required, Integer]"));
|
||||||
|
assert!(snapshot.contains("ERROR: expected integer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn list_panes_keep_the_active_row_inside_the_bounded_viewport() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
|
||||||
|
let children = (0..40)
|
||||||
|
.map(|index| format!("/tree-row-{index:02}"))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
{
|
||||||
|
let root = app.entries.get_mut("/").unwrap();
|
||||||
|
root.children = children.clone();
|
||||||
|
root.tree_state = ViewState::Fresh;
|
||||||
|
root.expanded = true;
|
||||||
|
}
|
||||||
|
for child in &children {
|
||||||
|
app.entries.insert(
|
||||||
|
child.clone(),
|
||||||
|
EntryView {
|
||||||
|
path: child.clone(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: vec![],
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
app.selected_path = children.last().unwrap().clone();
|
||||||
|
app.focus = Focus::Tree;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
let tree_pane = snapshot
|
||||||
|
.lines()
|
||||||
|
.map(|line| line.chars().take(38).collect::<String>())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
assert!(tree_pane.contains("tree-row-39"));
|
||||||
|
|
||||||
|
app.selected_path = "/".into();
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(Object {
|
||||||
|
name: String::new(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec!["many".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
}),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let operations = (0..20)
|
||||||
|
.map(|index| OperationDeclaration {
|
||||||
|
name: format!("operation-{index:02}"),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "many".into(),
|
||||||
|
descriptor: Some(InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations,
|
||||||
|
}),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.focus = Focus::Operations;
|
||||||
|
app.operation_cursor = app.operation_rows().len() - 1;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
assert!(snapshot.contains("(many, operation-19)"));
|
||||||
|
|
||||||
|
for index in 0..20 {
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Information,
|
||||||
|
title: format!("history-{index:02}"),
|
||||||
|
detail: "diagnostic".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
app.focus = Focus::History;
|
||||||
|
app.history_cursor = app.history.len() - 1;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
assert!(snapshot.contains("[INFO] history-00"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tiny_terminal_has_a_safe_fallback() {
|
||||||
|
let snapshot = rendered(&App::new("https://example.test/"), 30, 8);
|
||||||
|
assert!(snapshot.contains("too small"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn control_characters_and_large_bytes_are_bounded() {
|
||||||
|
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
|
||||||
|
let display = bounded_value(&wip_protocol::Value::Bytes(vec![7; 1000]));
|
||||||
|
assert!(display.starts_with("bytes[1000]"));
|
||||||
|
assert!(display.ends_with('…'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entry_view_type_remains_constructible_for_external_snapshots() {
|
||||||
|
let entry = EntryView {
|
||||||
|
path: "/".into(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: vec![],
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
};
|
||||||
|
assert_eq!(entry.path, "/");
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
|||||||
|
//! Terminal lifecycle guard and crossterm input translation.
|
||||||
|
|
||||||
|
use std::io::{self, Stdout};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crossterm::cursor::{Hide, Show};
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
|
use crossterm::execute;
|
||||||
|
use crossterm::terminal::{
|
||||||
|
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
|
||||||
|
};
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::CrosstermBackend;
|
||||||
|
|
||||||
|
use crate::app::InputKey;
|
||||||
|
|
||||||
|
type PanicHook = dyn for<'a> Fn(&std::panic::PanicHookInfo<'a>) + Send + Sync + 'static;
|
||||||
|
|
||||||
|
/// RAII owner of raw mode, alternate screen, cursor visibility, and panic recovery.
|
||||||
|
pub struct TerminalGuard {
|
||||||
|
terminal: Terminal<CrosstermBackend<Stdout>>,
|
||||||
|
previous_hook: Arc<PanicHook>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerminalGuard {
|
||||||
|
/// Enters terminal UI mode, restoring partial setup on failure.
|
||||||
|
pub fn enter() -> io::Result<Self> {
|
||||||
|
enable_raw_mode()?;
|
||||||
|
let mut stdout = io::stdout();
|
||||||
|
if let Err(error) = execute!(stdout, EnterAlternateScreen, Hide) {
|
||||||
|
let _ = disable_raw_mode();
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
let terminal = match Terminal::new(CrosstermBackend::new(stdout)) {
|
||||||
|
Ok(terminal) => terminal,
|
||||||
|
Err(error) => {
|
||||||
|
restore_terminal();
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let previous_hook: Arc<PanicHook> = std::panic::take_hook().into();
|
||||||
|
let panic_hook = Arc::clone(&previous_hook);
|
||||||
|
let terminal_owner = std::thread::current().id();
|
||||||
|
std::panic::set_hook(Box::new(move |information| {
|
||||||
|
if std::thread::current().id() == terminal_owner {
|
||||||
|
restore_terminal();
|
||||||
|
}
|
||||||
|
panic_hook(information);
|
||||||
|
}));
|
||||||
|
Ok(Self {
|
||||||
|
terminal,
|
||||||
|
previous_hook,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the ratatui terminal for drawing.
|
||||||
|
pub fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
|
||||||
|
&mut self.terminal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TerminalGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let previous = Arc::clone(&self.previous_hook);
|
||||||
|
std::panic::set_hook(Box::new(move |information| previous(information)));
|
||||||
|
restore_terminal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_terminal() {
|
||||||
|
let _ = disable_raw_mode();
|
||||||
|
let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts one crossterm key event into a terminal-independent reducer key.
|
||||||
|
///
|
||||||
|
/// When `editing` is true, printable command letters remain text input and only
|
||||||
|
/// Ctrl-C/Escape retain global meaning.
|
||||||
|
#[must_use]
|
||||||
|
pub fn translate_key(event: KeyEvent, editing: bool) -> Option<InputKey> {
|
||||||
|
if event.modifiers.contains(KeyModifiers::CONTROL) && event.code == KeyCode::Char('c') {
|
||||||
|
return Some(InputKey::Quit);
|
||||||
|
}
|
||||||
|
let key = match event.code {
|
||||||
|
KeyCode::Up => InputKey::Up,
|
||||||
|
KeyCode::Down => InputKey::Down,
|
||||||
|
KeyCode::Left => InputKey::Left,
|
||||||
|
KeyCode::Right => InputKey::Right,
|
||||||
|
KeyCode::Tab => InputKey::Tab,
|
||||||
|
KeyCode::Enter => InputKey::Enter,
|
||||||
|
KeyCode::Esc => InputKey::Escape,
|
||||||
|
KeyCode::Backspace => InputKey::Backspace,
|
||||||
|
KeyCode::Char(character) if editing => InputKey::Character(character),
|
||||||
|
KeyCode::Char('k') => InputKey::Up,
|
||||||
|
KeyCode::Char('j') => InputKey::Down,
|
||||||
|
KeyCode::Char('h') => InputKey::Left,
|
||||||
|
KeyCode::Char('l') => InputKey::Right,
|
||||||
|
KeyCode::Char('r') => InputKey::Refresh,
|
||||||
|
KeyCode::Char('R') => InputKey::Reconnect,
|
||||||
|
KeyCode::Char('c') => InputKey::CancelRead,
|
||||||
|
KeyCode::Char('?') => InputKey::Help,
|
||||||
|
KeyCode::Char('q') => InputKey::Quit,
|
||||||
|
KeyCode::Char(character) => InputKey::Character(character),
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn editing_keeps_command_letters_as_text_but_ctrl_c_quits() {
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), true),
|
||||||
|
Some(InputKey::Character('q'))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), false),
|
||||||
|
Some(InputKey::Quit)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(
|
||||||
|
KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
|
||||||
|
true
|
||||||
|
),
|
||||||
|
Some(InputKey::Quit)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
|
use wip_tui::app::{Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
|
use wip_tui::config::Config;
|
||||||
|
use wip_tui::runtime::{HttpTransport, Runtime, default_wire_limits};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_http_filesystem_workflow_is_lazy_validator_safe_and_symlink_confined() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let outside = tempdir().expect("outside root");
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
|
std::fs::create_dir(temporary.path().join("nested")).expect("create nested directory");
|
||||||
|
std::fs::write(outside.path().join("secret.txt"), b"outside-secret").expect("outside file");
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::symlink(outside.path(), temporary.path().join("outside-link"))
|
||||||
|
.expect("create symlink");
|
||||||
|
|
||||||
|
let mut server_config = ServerConfig::for_root(temporary.path());
|
||||||
|
server_config.access = AccessMode::ReadWrite;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(server_config)
|
||||||
|
.expect("build filesystem server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind filesystem server"),
|
||||||
|
);
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
let endpoint = format!("http://127.0.0.1:{}/wip", bound.local_addr().port());
|
||||||
|
let config = Config::parse([endpoint], None, Some("filesystem-test".into()), |_| None)
|
||||||
|
.expect("development config");
|
||||||
|
let transport = HttpTransport::new(&config, default_wire_limits().max_response_bytes())
|
||||||
|
.expect("HTTP transport");
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().selected_path, "/");
|
||||||
|
assert!(runtime.app().entries.contains_key("/hello.txt"));
|
||||||
|
assert!(runtime.app().entries.contains_key("/nested"));
|
||||||
|
assert!(runtime.app().entries.contains_key("/outside-link"));
|
||||||
|
let empty_directory = &runtime.app().entries["/nested"];
|
||||||
|
assert_eq!(empty_directory.tree_state, ViewState::Fresh);
|
||||||
|
assert!(empty_directory.children.is_empty());
|
||||||
|
assert!(!empty_directory.expanded);
|
||||||
|
|
||||||
|
// Visible Objects have their interface descriptors prefetched before selection.
|
||||||
|
let file_interfaces = runtime.app().entries["/hello.txt"]
|
||||||
|
.object
|
||||||
|
.as_ref()
|
||||||
|
.expect("file object")
|
||||||
|
.interfaces
|
||||||
|
.clone();
|
||||||
|
assert!(!file_interfaces.is_empty());
|
||||||
|
for reference in &file_interfaces {
|
||||||
|
assert_eq!(runtime.app().interfaces[reference].state, ViewState::Fresh);
|
||||||
|
assert!(runtime.app().interfaces[reference].descriptor.is_some());
|
||||||
|
}
|
||||||
|
let read_reference = file_interfaces[0].clone();
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().interfaces[&read_reference]
|
||||||
|
.descriptor
|
||||||
|
.as_ref()
|
||||||
|
.expect("read descriptor")
|
||||||
|
.operations[0]
|
||||||
|
.name,
|
||||||
|
"read"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Keyboard-select the already prefetched read operation.
|
||||||
|
runtime.app_mut().selected_path = "/hello.txt".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
assert!(!runtime.handle_key(InputKey::Enter));
|
||||||
|
|
||||||
|
// Descriptor-driven read editor, explicit confirmation, and execution.
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("68656c6c6f20776f726c64")
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Fresh);
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
|
||||||
|
// Use the separately-qualified prefetched write interface and replace with the
|
||||||
|
// automatically attached observed validator.
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "dXBkYXRlZA=="); // "updated"
|
||||||
|
confirm_and_execute(&mut runtime);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("updated file"),
|
||||||
|
b"updated"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Fresh);
|
||||||
|
|
||||||
|
// Prepare another replacement using the post-operation validator, then mutate
|
||||||
|
// the file externally before explicit execution. The stale validator is rejected,
|
||||||
|
// the Entry becomes stale, and no automatic call is created.
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "c3RhbGUtd3JpdGU=");
|
||||||
|
runtime.handle_key(InputKey::Enter); // confirmation fixes user input only
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"external").expect("external change");
|
||||||
|
let history_before = runtime.app().history.len();
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("externally changed file"),
|
||||||
|
b"external"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Stale);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history.len(), history_before + 1);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::DomainFailure);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("no automatic retry")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Refresh enables a new, separately confirmed execution.
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "ZmluYWw=");
|
||||||
|
confirm_and_execute(&mut runtime);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("final file"),
|
||||||
|
b"final"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Symlink inspection exposes the link payload only. It never traverses or
|
||||||
|
// materializes the target directory outside the configured root.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
runtime.app_mut().selected_path = "/outside-link".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 0;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
|
||||||
|
assert!(!runtime.app().history[0].detail.contains("outside-secret"));
|
||||||
|
assert!(
|
||||||
|
!runtime
|
||||||
|
.app()
|
||||||
|
.entries
|
||||||
|
.contains_key("/outside-link/secret.txt")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join filesystem listener")
|
||||||
|
.expect("filesystem listener exits");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(runtime: &mut Runtime<HttpTransport>) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !runtime.app().in_flight.is_empty() {
|
||||||
|
assert!(Instant::now() < deadline, "runtime requests did not settle");
|
||||||
|
runtime.wait_and_poll(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_only_field(runtime: &mut Runtime<HttpTransport>, input: &str) {
|
||||||
|
let Modal::Editor(editor) = &mut runtime.app_mut().modal else {
|
||||||
|
panic!("operation editor was not open")
|
||||||
|
};
|
||||||
|
assert_eq!(editor.fields.len(), 1);
|
||||||
|
editor.fields[0].input = input.into();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn confirm_and_execute(runtime: &mut Runtime<HttpTransport>) {
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
}
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{ServerConfig, WipFsServer};
|
||||||
|
use wip_http::encode_protocol_error_response;
|
||||||
|
use wip_http::http::{Request, Response};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
use wip_tui::app::{ConnectionState, Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
|
use wip_tui::config::Config;
|
||||||
|
use wip_tui::runtime::{
|
||||||
|
Runtime, Transport, TransportError, TransportErrorKind, default_wire_limits,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ScriptedTransport {
|
||||||
|
server: Arc<WipFsServer>,
|
||||||
|
sequence: Arc<AtomicUsize>,
|
||||||
|
delayed_after_startup: bool,
|
||||||
|
unknown_calls: bool,
|
||||||
|
fail_call_prepare: bool,
|
||||||
|
fail_tree_prepare: bool,
|
||||||
|
panic_calls: bool,
|
||||||
|
root_tree_protocol_failures: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScriptedTransport {
|
||||||
|
fn new(server: Arc<WipFsServer>) -> Self {
|
||||||
|
Self {
|
||||||
|
server,
|
||||||
|
sequence: Arc::new(AtomicUsize::new(0)),
|
||||||
|
delayed_after_startup: false,
|
||||||
|
unknown_calls: false,
|
||||||
|
fail_call_prepare: false,
|
||||||
|
fail_tree_prepare: false,
|
||||||
|
panic_calls: false,
|
||||||
|
root_tree_protocol_failures: Arc::new(AtomicUsize::new(0)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport for ScriptedTransport {
|
||||||
|
type Prepared = Request<Vec<u8>>;
|
||||||
|
|
||||||
|
fn prepare(&self, request: Request<Vec<u8>>) -> Result<Self::Prepared, TransportError> {
|
||||||
|
if self.fail_call_prepare && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
return Err(TransportError {
|
||||||
|
kind: TransportErrorKind::Disconnect,
|
||||||
|
detail: "scripted local conversion failure".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if self.fail_tree_prepare && request.uri().path().ends_with("/v1/observe") {
|
||||||
|
return Err(TransportError {
|
||||||
|
kind: TransportErrorKind::Disconnect,
|
||||||
|
detail: "scripted tree conversion failure".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&self, request: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError> {
|
||||||
|
let sequence = self.sequence.fetch_add(1, Ordering::AcqRel);
|
||||||
|
if request.uri().path().ends_with("/v1/observe")
|
||||||
|
&& self
|
||||||
|
.root_tree_protocol_failures
|
||||||
|
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| {
|
||||||
|
remaining.checked_sub(1)
|
||||||
|
})
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
return Ok(encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "scripted startup failure".into(),
|
||||||
|
},
|
||||||
|
default_wire_limits(),
|
||||||
|
)
|
||||||
|
.expect("encode tree failure"));
|
||||||
|
}
|
||||||
|
if self.delayed_after_startup && sequence > 0 {
|
||||||
|
// Delay the first refresh so the second wins and exercises exact
|
||||||
|
// RequestId ownership.
|
||||||
|
let delay = if sequence == 1 { 80 } else { 5 };
|
||||||
|
thread::sleep(Duration::from_millis(delay));
|
||||||
|
}
|
||||||
|
if self.panic_calls && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
panic!("scripted transport worker panic");
|
||||||
|
}
|
||||||
|
if self.unknown_calls && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
return Ok(encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::CallOperation,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
message: "scripted commit uncertainty".into(),
|
||||||
|
},
|
||||||
|
default_wire_limits(),
|
||||||
|
)
|
||||||
|
.expect("encode unknown outcome"));
|
||||||
|
}
|
||||||
|
Ok(self.server.handle_http(request))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_refresh_and_cancel_keep_request_identity_safe() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.delayed_after_startup = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().entries["/"].state, ViewState::Fresh);
|
||||||
|
assert!(runtime.app().history.iter().any(|item| {
|
||||||
|
item.kind == HistoryKind::Information && item.title.contains("stale response")
|
||||||
|
}));
|
||||||
|
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
runtime.handle_key(InputKey::CancelRead);
|
||||||
|
runtime.handle_key(InputKey::CancelRead);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert!(
|
||||||
|
runtime
|
||||||
|
.app()
|
||||||
|
.history
|
||||||
|
.iter()
|
||||||
|
.any(|item| item.title == "retrieval canceled")
|
||||||
|
);
|
||||||
|
|
||||||
|
// When a refreshed tree omits a formerly selected Entry, the client marks
|
||||||
|
// it stale and the presentation no longer exposes old metadata/operations
|
||||||
|
// as current.
|
||||||
|
std::fs::remove_file(temporary.path().join("file")).expect("remove file");
|
||||||
|
runtime.app_mut().selected_path = "/".into();
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
|
||||||
|
runtime.app_mut().selected_path = "/file".into();
|
||||||
|
assert!(runtime.app().operation_rows().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn startup_transport_preparation_failure_enters_failed_state() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.fail_tree_prepare = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(matches!(
|
||||||
|
runtime.app().connection,
|
||||||
|
ConnectionState::Failed(ref detail) if detail.contains("scripted tree conversion failure")
|
||||||
|
));
|
||||||
|
assert!(runtime.app().status.contains("press R to reconnect"));
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn startup_protocol_failure_enters_failed_state_and_reconnects() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let transport = ScriptedTransport::new(server);
|
||||||
|
transport
|
||||||
|
.root_tree_protocol_failures
|
||||||
|
.store(1, Ordering::Release);
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(matches!(
|
||||||
|
runtime.app().connection,
|
||||||
|
ConnectionState::Failed(ref detail) if detail.contains("scripted startup failure")
|
||||||
|
));
|
||||||
|
assert!(runtime.app().status.contains("press R to reconnect"));
|
||||||
|
assert!(runtime.app().history.iter().any(|item| {
|
||||||
|
item.kind == HistoryKind::DomainFailure && item.detail.contains("scripted startup failure")
|
||||||
|
}));
|
||||||
|
|
||||||
|
runtime.handle_key(InputKey::Reconnect);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().connection, ConnectionState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_transport_preparation_failure_is_definitely_not_dispatched() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.fail_call_prepare = true;
|
||||||
|
let execute_calls = Arc::clone(&transport.sequence);
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
let calls_before_operation = execute_calls.load(Ordering::Acquire);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert_eq!(
|
||||||
|
execute_calls.load(Ordering::Acquire),
|
||||||
|
calls_before_operation,
|
||||||
|
"preparation failure must not invoke transport I/O"
|
||||||
|
);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::TransportFailure);
|
||||||
|
assert!(runtime.app().history[0].detail.contains("not dispatched"));
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().status,
|
||||||
|
"operation not dispatched; not executed"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Fresh);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn worker_panic_settles_as_unknown_instead_of_stranding_the_main_loop() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.panic_calls = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("transport worker failed")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn post_dispatch_unknown_is_prominent_stale_and_never_retried() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.unknown_calls = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("side effects are unknown")
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
let history = runtime.app().history.len();
|
||||||
|
thread::sleep(Duration::from_millis(20));
|
||||||
|
runtime.poll();
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().history.len(),
|
||||||
|
history,
|
||||||
|
"no retry was manufactured"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config() -> Config {
|
||||||
|
Config::parse(
|
||||||
|
["https://example.test/wip"],
|
||||||
|
None,
|
||||||
|
Some("scripted-test".into()),
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.expect("config")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_read_editor(runtime: &mut Runtime<ScriptedTransport>) {
|
||||||
|
runtime.app_mut().selected_path = "/file".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 0;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(runtime);
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(runtime: &mut Runtime<ScriptedTransport>) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !runtime.app().in_flight.is_empty() {
|
||||||
|
assert!(Instant::now() < deadline, "scripted runtime did not settle");
|
||||||
|
runtime.wait_and_poll(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
println!("Hello, world!");
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user